Add the web editor driver and control protocol (#4657)

* Add the web editor driver, a Rust port of the editor driver run with `cargo run drive`, built on a new editor control protocol crate with Playwright kept only for browser input and screenshots

* Refuse oversized step counts and empty page sizes, stop Vite if its record can't be saved, center the crosshair on half-pixel pointers, skip Wasm Opt for drive, and re-save the demo artwork
This commit is contained in:
Keavon Chambers authored and GitHub committed 2026-10-08 02:17:20 -07:00
1 parent e391d10831
commit 4c3fabbaa5
33 files changed
+3212 -21

No files matched your search

Generated
+25
View File
@@ -2426,6 +2426,15 @@ dependencies = [
"zip",
]
[[package]]
name = "graphite-editor-control-protocol"
version = "0.0.0"
dependencies = [
"glam 0.33.10",
"serde",
"serde_json",
]
[[package]]
name = "graphite-proc-macros"
version = "0.0.0"
@@ -6896,6 +6905,22 @@ dependencies = [
"pkg-config",
]
[[package]]
name = "web-editor-driver"
version = "0.0.0"
dependencies = [
"base64",
"clap",
"getrandom 0.3.3",
"glam 0.33.10",
"graphite-editor-control-protocol",
"image",
"interprocess",
"serde",
"serde_json",
"windows-sys 0.61.2",
]
[[package]]
name = "web-sys"
version = "0.3.98"
+3
View File
@@ -12,6 +12,7 @@ members = [
"document/graph-storage",
"document/container",
"editor",
"editor/control-protocol",
"frontend/wrapper",
"libraries/dyn-any",
"libraries/math-parser",
@@ -35,6 +36,7 @@ members = [
"tools/third-party-licenses",
"tools/editor-message-tree",
"tools/node-docs",
"tools/web-editor-driver",
]
default-members = [
"editor",
@@ -107,6 +109,7 @@ wgpu-executor = { path = "node-graph/libraries/wgpu-executor" }
wgpu-sync = { path = "libraries/wgpu-sync" }
graphite-proc-macros = { path = "proc-macros" }
graphite-editor = { path = "editor" }
graphite-editor-control-protocol = { path = "editor/control-protocol" }
graphene-canvas-utils = { path = "node-graph/libraries/canvas-utils" }
ipsum = { path = "libraries/ipsum" }
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":fLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"Number":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplicationLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[194878846429432339,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4],"remove":[],"delta":[[1,[671.7691453623979,420.00000000000006]],[2,[559.8076211353317,450.0000000000001]],[3,[410.5255888325765,410.0]],[4,[522.4871130596428,380.00000000000006]]]},"segments":{"add":[1,2,3,4],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4]],"end_point":[[1,2],[2,3],[3Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[194878846429432339,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4],"remove":[],"delta":[[1,[671.7691453623979,420.00000000000006]],[2,[559.8076211353317,450.0000000000001]],[3,[410.5255888325765,410.0]],[4,[522.4871130596428,380.00000000000006]]]},"segments":{"add":[1,2,3,4],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4]],"end_point":[[1,2],[2,3]Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"I64":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"I64":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_vaLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"Integer":0},"exposed":false}},{"Value":{"tagged_value":{"Number":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"Number":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"Integer":3},"exposed":false}},{"Value":{"tagged_value":{"Number":2.0},"exposed":false}},{"Value":{"tagged_value":{"Number":0.5},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"Number":2.0},"exposed"Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::artboard::Artboard"}}}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"Generic":"T"}]},"import_index":1}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":2}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":3}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":4}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::artboard::Artboard"}}}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"Generic":"T"}]},"import_index":1}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":2}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":3}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":4}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<allocLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"BoxCorners":[0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"outLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Number":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"Number":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Number":4000.0},"exposed":false}},{"Value":{"tagged_value":{"Number":500.0},"exposed":false}},{"Value":{"tagged_value":{"BoxCorners":[0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":1415828794531Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_Line truncated
+21
View File
@@ -0,0 +1,21 @@
[package]
name = "graphite-editor-control-protocol"
description = "The commands, results, and scenarios that scripts, QA, and agents use to operate the Graphite editor"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[dependencies]
# Workspace dependencies
serde = { workspace = true }
serde_json = { workspace = true }
glam = { workspace = true, features = ["serde"] }
+323
View File
@@ -0,0 +1,323 @@
//! The commands that scripts, QA, and agents send to operate the Graphite editor the way a person does, the results they get back,
//! the scenario files that hold a sequence of commands, and the messages that carry them between a client and an editor host.
//!
//! Each message travels as one line of JSON.
use glam::{DVec2, UVec2};
use serde::{Deserialize, Serialize};
use std::num::NonZeroU32;
use std::path::PathBuf;
/// Increases whenever a change would break a client or host written against an earlier version.
pub const PROTOCOL_VERSION: u32 = 1;
/// Which origin a point is measured from.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Space {
/// The page's top left corner.
#[default]
Page,
/// The document viewport's top left corner.
Viewport,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum MouseButton {
#[default]
Left,
Middle,
Right,
}
/// An area of the page, in CSS pixels.
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct Rectangle {
pub x: f64,
pub y: f64,
pub width: f64,
pub height: f64,
}
/// Frames captured along a drag and laid out in one image, each marked with where the pointer was.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Filmstrip {
/// Where the image is written, with a relative path landing in the host's output directory.
pub path: PathBuf,
/// How many frames to capture, spread evenly along the drag.
pub frames: Option<NonZeroU32>,
/// Limits each frame to the document viewport (`"viewport"`) or the first element matching a CSS selector.
pub region: Option<String>,
/// Limits each frame to an exact area of the page, overriding the region.
pub clip: Option<Rectangle>,
}
/// One step of operating the editor with the mouse and keyboard, or of observing the result.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase", deny_unknown_fields)]
pub enum Command {
/// Moves the pointer one small step per rendered frame, as a real pointer does, or in the given number of steps.
Move { to: DVec2, space: Option<Space>, steps: Option<NonZeroU32> },
/// Presses a mouse button.
Down { button: Option<MouseButton> },
/// Releases a mouse button.
Up { button: Option<MouseButton> },
/// Moves the pointer to a point and clicks there, with the keys held from before the first press.
Click {
at: DVec2,
space: Option<Space>,
button: Option<MouseButton>,
count: Option<NonZeroU32>,
keys: Option<Vec<String>>,
},
/// Drags between two points with the keys held from before the press.
/// With `release` set to false, the button and keys stay held once the drag succeeds.
Drag {
from: DVec2,
to: DVec2,
space: Option<Space>,
button: Option<MouseButton>,
keys: Option<Vec<String>>,
steps: Option<NonZeroU32>,
release: Option<bool>,
filmstrip: Option<Filmstrip>,
},
/// Holds a key, named as in `KeyboardEvent.key` or `KeyboardEvent.code`, such as `Shift` or `KeyP`.
KeyDown { key: String },
/// Releases a held key.
KeyUp { key: String },
/// Taps a key, or a combination such as `Control+KeyZ`, where a final `+` is the plus key itself.
Press { key: String },
/// Types text into the focused field.
Type { text: String },
/// Turns the mouse wheel, in notches of up to 100 pixels, optionally after moving the pointer to a point.
Scroll { delta: DVec2, at: Option<DVec2>, space: Option<Space> },
/// Pauses for a number of milliseconds.
Wait { milliseconds: u64 },
/// Waits until the editor stops redrawing, giving up after the timeout in milliseconds.
WaitIdle { timeout: Option<u64> },
/// Captures the page, or part of it, optionally marking the pointer with a crosshair.
Screenshot {
path: PathBuf,
cursor: Option<bool>,
region: Option<String>,
clip: Option<Rectangle>,
},
/// Finds elements by a `data-*` attribute name, the visible text they contain, or both.
Locate { data: Option<String>, text: Option<String> },
/// Changes the size of the page, in CSS pixels.
Resize { size: UVec2 },
/// Reports the state of the session.
Status {},
}
impl Command {
/// The name the command is given by its `type` field.
pub fn name(&self) -> &'static str {
match self {
Command::Move { .. } => "move",
Command::Down { .. } => "down",
Command::Up { .. } => "up",
Command::Click { .. } => "click",
Command::Drag { .. } => "drag",
Command::KeyDown { .. } => "keyDown",
Command::KeyUp { .. } => "keyUp",
Command::Press { .. } => "press",
Command::Type { .. } => "type",
Command::Scroll { .. } => "scroll",
Command::Wait { .. } => "wait",
Command::WaitIdle { .. } => "waitIdle",
Command::Screenshot { .. } => "screenshot",
Command::Locate { .. } => "locate",
Command::Resize { .. } => "resize",
Command::Status {} => "status",
}
}
}
/// An element found by a `locate` command.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Located {
#[serde(rename = "box")]
pub bounds: Rectangle,
pub center: DVec2,
/// The start of the element's text, with its whitespace collapsed.
pub text: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionStatus {
pub url: String,
pub size: UVec2,
pub pointer: DVec2,
/// Where the document viewport is on the page, if one is open.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub viewport: Option<Rectangle>,
pub held_keys: Vec<String>,
pub held_buttons: Vec<MouseButton>,
pub crashed: bool,
/// The errors the page has logged since the last status report.
pub console_errors: Vec<String>,
}
/// What came of one command.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CommandResult {
/// The `type` of the command this reports on.
#[serde(rename = "type")]
pub command: String,
pub ok: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
/// Where a screenshot or filmstrip was written.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<PathBuf>,
/// The pointer's position on the page in each frame of a filmstrip, in the order the frames are laid out.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub frames: Option<Vec<DVec2>>,
/// Whether the editor stopped redrawing before the timeout.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub stable: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub located: Option<Vec<Located>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<SessionStatus>,
}
impl CommandResult {
pub fn succeeded(command: &Command) -> Self {
Self {
command: command.name().to_string(),
ok: true,
..Default::default()
}
}
pub fn failed(command: &Command, error: String) -> Self {
Self {
command: command.name().to_string(),
ok: false,
error: Some(error),
..Default::default()
}
}
}
/// Reads the steps of a scenario file, which holds one command per line written as JSON, leaving out blank lines and `//` comments.
pub fn parse_scenario(text: &str) -> Result<Vec<Command>, String> {
text.lines()
.enumerate()
.filter(|(_, line)| {
let line = line.trim();
!line.is_empty() && !line.starts_with("//")
})
.map(|(index, line)| serde_json::from_str(line).map_err(|error| format!("Line {}: {error}", index + 1)))
.collect()
}
/// A message from a client to an editor host.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum ClientMessage {
/// Attaches to the session, which the host refuses unless the protocol version matches and the token is the host's own.
Attach { version: u32, token: String },
/// Performs commands in order, stopping at the first that fails, since the later ones were written assuming it succeeded.
Perform { id: u64, commands: Vec<Command> },
/// Ends the session and closes the editor.
Shutdown,
}
/// A message from an editor host to a client.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum HostMessage {
/// Accepts a connection, naming the host's process so a client can tell it apart from one that has replaced it.
Attached { version: u32, process_id: u32 },
/// Turns away a connection, after which the host closes it.
Refused { reason: String },
/// Reports on each command performed, in order.
Results { id: u64, results: Vec<CommandResult> },
/// Confirms a shutdown, after which the connection closes once the host has exited.
ShuttingDown,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scenario_steps_parse() {
let steps = parse_scenario(
r#"// Draw a rectangle
{ "type": "resize", "size": [1600, 1000] }
{ "type": "press", "key": "KeyM" }
// Drag out the rectangle
{ "type": "drag", "from": [200, 150], "to": [500, 350], "space": "viewport", "filmstrip": { "path": "drag.png", "frames": 4 } }
{ "type": "waitIdle" }
{ "type": "screenshot", "path": "rectangle.png", "region": "viewport" }
{ "type": "status" }
"#,
)
.unwrap();
assert_eq!(steps.len(), 6);
assert_eq!(steps[0], Command::Resize { size: UVec2::new(1600, 1000) });
assert!(
matches!(&steps[2], Command::Drag { to, space: Some(Space::Viewport), filmstrip: Some(Filmstrip { frames: Some(frames), .. }), .. } if *to == DVec2::new(500., 350.) && frames.get() == 4)
);
assert_eq!(steps[5], Command::Status {});
}
#[test]
fn scenario_mistakes_name_their_line() {
let error = parse_scenario("// A mistake on the third line\n{ \"type\": \"status\" }\n{ \"type\": \"teleport\" }").unwrap_err();
assert!(error.starts_with("Line 3:"));
}
#[test]
fn mistakes_are_refused() {
// A misspelled field
assert!(serde_json::from_str::<Command>(r#"{ "type": "move", "to": [1, 2], "stpes": 3 }"#).is_err());
// A count that must be a positive integer
assert!(serde_json::from_str::<Command>(r#"{ "type": "click", "at": [1, 2], "count": 0 }"#).is_err());
// An unknown command
assert!(serde_json::from_str::<Command>(r#"{ "type": "teleport", "to": [1, 2] }"#).is_err());
// A field on a command that takes none
assert!(serde_json::from_str::<Command>(r#"{ "type": "status", "milliseconds": 5 }"#).is_err());
}
#[test]
fn names_match_the_type_field() {
let commands = [Command::KeyDown { key: "Shift".into() }, Command::WaitIdle { timeout: None }, Command::Status {}];
for command in commands {
let json = serde_json::to_value(&command).unwrap();
assert_eq!(json["type"], command.name());
}
}
}
+10 -10
View File
@@ -128,33 +128,34 @@ pub fn sequence<I: IntoIterator<Item = Expression>>(expressions: I) -> Sequence
let worker = std::thread::spawn(move || {
for expr in expressions {
if worker_killed.load(Ordering::SeqCst) {
return;
return false;
}
let handle = match expr.start() {
Ok(h) => Arc::new(h),
Err(e) => {
eprintln!("sequence: failed to start step: {e}");
return;
return false;
}
};
{
let mut slot = worker_current.lock().unwrap();
if worker_killed.load(Ordering::SeqCst) {
let _ = handle.kill();
return;
return false;
}
*slot = Some(Arc::clone(&handle));
}
let result = handle.wait().map(|_| ());
worker_current.lock().unwrap().take();
if worker_killed.load(Ordering::SeqCst) {
return;
return false;
}
if let Err(e) = result {
eprintln!("sequence: step failed: {e}");
return;
return false;
}
}
true
});
Sequence {
@@ -167,7 +168,7 @@ pub fn sequence<I: IntoIterator<Item = Expression>>(expressions: I) -> Sequence
pub struct Sequence {
current: Arc<Mutex<Option<Arc<Handle>>>>,
killed: Arc<AtomicBool>,
worker: Option<JoinHandle<()>>,
worker: Option<JoinHandle<bool>>,
}
impl Sequence {
pub fn kill(&self) {
@@ -178,10 +179,9 @@ impl Sequence {
}
}
pub fn wait(&mut self) {
if let Some(w) = self.worker.take() {
let _ = w.join();
}
/// Waits for the steps to finish, returning whether every one ran and succeeded.
pub fn wait(&mut self) -> bool {
self.worker.take().is_some_and(|worker| worker.join().unwrap_or(false))
}
}
impl Drop for Sequence {
+11
View File
@@ -9,6 +9,7 @@ pub enum Action {
Run,
Build,
Explore(Option<String>),
Drive,
}
pub enum Target {
@@ -32,6 +33,16 @@ pub struct Task {
impl Task {
pub fn parse(args: &[&str]) -> Option<Self> {
// Everything after `drive` belongs to the web editor driver, which has commands and options of its own
if args.first() == Some(&"drive") {
return Some(Task {
action: Action::Drive,
target: Target::Web,
profile: Profile::Default,
args: args[1..].iter().map(|s| s.to_string()).collect(),
});
}
let split = args.iter().position(|a| *a == "--").unwrap_or(args.len());
let passthru_args = args[split..].iter().skip(1).map(|s| s.to_string()).collect();
let args = &args[..split];
+36 -2
View File
@@ -17,6 +17,7 @@ fn usage() {
println!(" [run] Run the selected target (default)");
println!(" build Build the selected target");
println!(" explore Open an assortment of tools for exploring the codebase");
println!(" drive Drive the web editor in an isolated browser (see `cargo run drive help`)");
println!(" help Show this message");
println!("<target>:");
println!(" [web] Web app (default)");
@@ -47,6 +48,10 @@ fn main() -> ExitCode {
}
};
if matches!(task.action, Action::Drive) {
return drive(&task);
}
if let Err(e) = run_task(&task) {
eprintln!("Error: {e}");
return ExitCode::FAILURE;
@@ -67,6 +72,35 @@ fn explore_usage() {
println!();
}
// Exits with the driver's own status, since scripts read whether its commands succeeded from it
fn drive(task: &Task) -> ExitCode {
// Serving builds the editor's Wasm first, as `cargo run` does
let asking_for_help = task.args.iter().any(|argument| argument == "--help" || argument == "-h");
if task.args.first().map(String::as_str) == Some("serve") && !asking_for_help {
let prepared = requirements::check(task).and_then(|()| branding::setup()).and_then(|()| frontend::setup());
if let Err(e) = prepared {
eprintln!("Error: {e}");
return ExitCode::FAILURE;
}
// Unlike `frontend::build_wasm`, this stops at a failed build rather than going on to serve the previous one
if !sequence(frontend::build_wasm_steps(false, false)).wait() {
eprintln!("Error: The Wasm build failed");
return ExitCode::FAILURE;
}
}
// Run from the caller's own folder, which relative paths in the arguments are written from
let driver = cmd!("cargo", "run", "--quiet", "--package", "web-editor-driver", "--").args(&task.args).unchecked();
match Expression::run(&driver) {
Ok(output) => ExitCode::from(output.status.code().and_then(|code| u8::try_from(code).ok()).unwrap_or(1)),
Err(e) => {
eprintln!("Error: {e}");
ExitCode::FAILURE
}
}
}
fn run_task(task: &Task) -> Result<(), Error> {
if let Action::Explore(tool) = &task.action {
match tool.as_deref() {
@@ -111,7 +145,7 @@ fn run_task(task: &Task) -> Result<(), Error> {
profile = match action {
Action::Run => &Profile::Debug,
Action::Build => &Profile::Release,
Action::Explore(_) => unreachable!(),
Action::Explore(_) | Action::Drive => unreachable!(),
}
}
@@ -138,7 +172,7 @@ fn run_task(task: &Task) -> Result<(), Error> {
(Action::Build, Target::Cli, Profile::Debug) => cmd!("cargo", "build", "-p", "graphene-cli").run()?,
(Action::Build, Target::Cli, Profile::Release | Profile::Default) => cmd!("cargo", "build", "-r", "-p", "graphene-cli").run()?,
(Action::Explore(_), _, _) => unreachable!(),
(Action::Explore(_) | Action::Drive, _, _) => unreachable!(),
}
Ok(())
}
+1 -1
View File
@@ -45,7 +45,7 @@ fn requirements(task: &Task) -> Vec<Requirement> {
|| match task.profile {
Profile::Debug => true,
Profile::Release => false,
Profile::Default => matches!(task.action, Action::Run),
Profile::Default => matches!(task.action, Action::Run | Action::Drive),
}
}),
..Default::default()
+4
View File
@@ -0,0 +1,4 @@
node_modules/
.browsers/
.session/
output/
+34
View File
@@ -0,0 +1,34 @@
[package]
name = "web-editor-driver"
description = "Drives the Graphite web editor the way a person does, with real mouse and keyboard input, for scripts, QA, and agents"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[dependencies]
# Local dependencies
graphite-editor-control-protocol = { workspace = true }
# Workspace dependencies
serde = { workspace = true }
serde_json = { workspace = true }
glam = { workspace = true }
base64 = { workspace = true }
clap = { workspace = true, features = ["derive"] }
# Other dependencies
image = { version = "0.25", default-features = false, features = ["png"] }
interprocess = "2.4.2"
getrandom = "0.3"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_System_Threading"] }
+69
View File
@@ -0,0 +1,69 @@
# Web editor driver
Drives the Graphite web editor the way a person does. Every action is real mouse or keyboard input delivered to the page, so nothing bypasses the interface, and what comes back is a screenshot of the whole editor. It serves three audiences:
- **Scripts** that reproduce a sequence of interactions.
- **QA** that exercises the web editor end to end and records what it looked like.
- **Agents** that operate the editor by looking at screenshots and choosing the next input.
The driver runs its own copy of Chromium, downloaded into this directory, with a fresh profile every session. It never touches a browser, profile, or history already on the machine.
It is written in Rust, apart from the small Node.js process in `playwright/` that delivers input and takes screenshots through Playwright. The commands, their results, and scenario files are defined by the editor control protocol in `editor/control-protocol`.
The TypeScript in `playwright/` follows the frontend's lint rules, using the tools the frontend installs. Check it with `npm run check` in that folder, and fix what can be fixed automatically with `npm run fix`.
## Setup
Requires Node.js 22.18 or newer.
```sh
cargo run drive install
```
## Usage
```sh
cargo run drive serve --port 8090 # Build the Wasm and serve the editor (omit if `cargo run` is already serving it)
cargo run drive start # Open the editor in a new session
cargo run drive screenshot editor.png
cargo run drive key press KeyM # Switch to the Rectangle tool
cargo run drive drag 200 150 500 350 --in viewport --shot rectangle.png
cargo run drive shutdown # Close the session and the dev server
```
Run `cargo run drive help` for every command. Those that act on the editor print their results as JSON, and every command exits with a nonzero status if it failed. Every invocation goes through Cargo, so a batch with `act` or `run` is much faster than many separate commands.
Points are in CSS pixels from the page's top left corner, or from the document viewport's top left corner with `--in viewport`, and land on whole device pixels as a real pointer's do. Relative file paths are written to the `output` directory.
The `--keys` of a `click` or `drag` are held from before the button goes down, and `--hold` keeps them held along with the button. To press a key partway through a drag, use `drag --hold`, then `key down`, then `move`, then `up`. Combinations such as `Control+KeyZ` work with `key press`.
The session runs in the background and listens on a local socket, only accepting connections that open with the secret token in `.session/session.json`.
## Watching motion
A screenshot cannot show how an interaction felt partway through, and it leaves out the pointer. Two options cover that:
- `--cursor` on `screenshot` marks where the pointer is with a crosshair.
- `--filmstrip <file>` on `drag` captures frames along the drag and lays them out in one image, read left to right then top to bottom, each with its crosshair.
To look closely at a small area, limit either one with `--region viewport` or `--clip <x>,<y>,<width>,<height>`, and start the session with `--scale 2` for twice the pixel density.
## Scenarios
A scenario file holds the same commands the command line performs, one per line written as JSON, for replaying with `run`. Blank lines and lines starting with `//` are skipped, so a scenario can describe itself in its first line and group its steps:
```
// Draw a rectangle with the Rectangle tool
{ "type": "resize", "size": [1600, 1000] }
{ "type": "press", "key": "KeyM" }
// Drag out the rectangle, then capture the result
{ "type": "drag", "from": [200, 150], "to": [500, 350], "space": "viewport" }
{ "type": "waitIdle" }
{ "type": "screenshot", "path": "rectangle.png" }
```
Scenario files are named for what they do, ending in `.jsonl`, such as `draw-rectangle.jsonl`.
The commands and their fields are defined by `Command` in `editor/control-protocol/src/lib.rs`.
@@ -0,0 +1,152 @@
// The part of the web editor driver that needs Playwright: it owns the driver's own Chromium and carries out the basic steps
// the Rust session sends it, read as one JSON request per line on stdin and answered with one JSON line each on stdout
import readline from "node:readline";
import { setTimeout as sleep } from "node:timers/promises";
import { chromium } from "playwright-core";
import type { Browser, BrowserContext, Locator, Page } from "playwright-core";
const MAX_CONSOLE_ERRORS = 50;
type Point = [number, number];
type Box = { x: number; y: number; width: number; height: number };
type MouseButton = "left" | "middle" | "right";
type Request =
| { type: "launch"; url: string; size: Point; scale: number; headed: boolean; readySelector: string; timeout: number }
| { type: "close" }
| { type: "resize"; size: Point }
| { type: "mouseMove"; to: Point }
| { type: "mouseDown"; button: MouseButton; clickCount: number }
| { type: "mouseUp"; button: MouseButton; clickCount: number }
| { type: "wheel"; delta: Point }
| { type: "keyDown"; key: string }
| { type: "keyUp"; key: string }
| { type: "type"; text: string }
| { type: "screenshot"; clip?: Box }
| { type: "boundingBox"; selector: string }
| { type: "locate"; data?: string; text?: string }
| { type: "nextFrame"; timeout: number }
| { type: "takeEvents" };
type Envelope = { id: number; request: Request };
let browser: Browser | undefined;
let context: BrowserContext | undefined;
let page: Page | undefined;
let consoleErrors: string[] = [];
let crashed = false;
function recordError(message: string) {
if (consoleErrors.length < MAX_CONSOLE_ERRORS) consoleErrors.push(message);
}
async function launch(request: Extract<Request, { type: "launch" }>) {
if (browser) throw new Error("The browser is already open");
// The full browser in its new headless mode behaves like the one a person uses, unlike the lighter headless shell
browser = await chromium.launch({ channel: "chromium", headless: !request.headed });
context = await browser.newContext({ viewport: { width: request.size[0], height: request.size[1] }, deviceScaleFactor: request.scale });
page = await context.newPage();
page.on("console", (message) => message.type() === "error" && recordError(message.text()));
page.on("pageerror", (error) => recordError(String(error)));
page.on("crash", () => (crashed = true));
await page.goto(request.url, { waitUntil: "domcontentloaded", timeout: request.timeout });
await page.waitForSelector(request.readySelector, { timeout: request.timeout });
}
async function close() {
await context?.close();
await browser?.close();
}
function elementsWith(current: Page, data: string | undefined, text: string | undefined): Locator {
if (data === undefined) {
if (text === undefined) throw new Error("Locating needs a data attribute name or some text");
return current.getByText(text);
}
const withData = current.locator(`[data-${data}]`);
return text === undefined ? withData : withData.filter({ hasText: text });
}
async function locate(current: Page, data: string | undefined, text: string | undefined): Promise<{ box: Box; text: string }[]> {
const located: { box: Box; text: string }[] = [];
const elements = await elementsWith(current, data, text).all();
for (let i = 0; i < elements.length; i++) {
const box = await elements[i].boundingBox();
if (box) located.push({ box, text: (await elements[i].textContent()) || "" });
}
return located;
}
async function perform(request: Request): Promise<unknown> {
if (request.type === "launch") return launch(request);
if (request.type === "close") return close();
const current = page;
if (!current) throw new Error("The browser is not open");
switch (request.type) {
case "resize":
return current.setViewportSize({ width: request.size[0], height: request.size[1] });
case "mouseMove":
return current.mouse.move(request.to[0], request.to[1]);
case "mouseDown":
return current.mouse.down({ button: request.button, clickCount: request.clickCount });
case "mouseUp":
return current.mouse.up({ button: request.button, clickCount: request.clickCount });
case "wheel":
return current.mouse.wheel(request.delta[0], request.delta[1]);
case "keyDown":
return current.keyboard.down(request.key);
case "keyUp":
return current.keyboard.up(request.key);
case "type":
return current.keyboard.type(request.text);
case "screenshot":
return (await current.screenshot(request.clip ? { clip: request.clip } : {})).toString("base64");
case "boundingBox": {
const locator = current.locator(request.selector);
if ((await locator.count()) === 0) return undefined;
return locator.first().boundingBox();
}
case "locate":
return locate(current, request.data, request.text);
case "nextFrame": {
// Gives up after the timeout, so a page that has stopped drawing cannot hold up every later request
const frame = current.evaluate(() => new Promise((resolve) => requestAnimationFrame(resolve)));
await Promise.race([frame, sleep(request.timeout)]);
return undefined;
}
case "takeEvents": {
const events = { consoleErrors, crashed };
consoleErrors = [];
return events;
}
}
}
// Resolves once the reply is written, so exiting afterward cannot cut it off
function reply(message: { id: number; value?: unknown; error?: string }): Promise<void> {
return new Promise((resolve) => process.stdout.write(`${JSON.stringify(message)}\n`, () => resolve()));
}
// Requests are carried out as they arrive, so closing can interrupt a step that is still running
const lines = readline.createInterface({ input: process.stdin });
lines.on("line", (line) => {
let id = 0;
const handle = async () => {
const envelope: Envelope = JSON.parse(line);
id = envelope.id;
await reply({ id, value: await perform(envelope.request) });
if (envelope.request.type === "close") process.exit(0);
};
handle().catch((error) => reply({ id, error: error instanceof Error ? error.message : String(error) }));
});
// The browser has no reason to stay open once the session that sends the requests is gone
lines.on("close", () => close().finally(() => process.exit(0)));
@@ -0,0 +1,3 @@
// This folder follows the frontend's lint rules, checked by the ESLint the frontend installs
// eslint-disable-next-line no-restricted-imports, import/no-relative-packages -- The frontend's config is in another package, which isn't installed here
export { default } from "../../../frontend/eslint.config.js";
+29
View File
@@ -0,0 +1,29 @@
{
"name": "graphite-web-editor-driver-playwright",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "graphite-web-editor-driver-playwright",
"license": "MIT OR Apache-2.0",
"dependencies": {
"playwright-core": "^1.63.0"
},
"engines": {
"node": ">=22.18"
}
},
"node_modules/playwright-core": {
"version": "1.63.0",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",
"integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=20"
}
}
}
}
@@ -0,0 +1,23 @@
{
"name": "graphite-web-editor-driver-playwright",
"private": true,
"description": "The Playwright part of the web editor driver, which owns its isolated browser and delivers real input to it.",
"author": "Graphite Authors <[email protected]>",
"type": "module",
"engines": {
"node": ">=22.18"
},
"scripts": {
"check": "node ../../../frontend/node_modules/typescript/bin/tsc && node ../../../frontend/node_modules/eslint/bin/eslint.js",
"fix": "node ../../../frontend/node_modules/eslint/bin/eslint.js --fix"
},
"dependencies": {
"playwright-core": "^1.63.0"
},
"homepage": "https://graphite.art",
"license": "MIT OR Apache-2.0",
"repository": {
"type": "git",
"url": "git+https://github.com/GraphiteEditor/Graphite.git"
}
}
@@ -0,0 +1,16 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"skipLibCheck": true,
"verbatimModuleSyntax": true,
"erasableSyntaxOnly": true,
"noEmit": true,
"typeRoots": ["../../../frontend/node_modules/@types"],
"types": ["node"],
"lib": ["ESNext", "DOM", "DOM.Iterable"]
},
"include": ["*.ts"]
}
+307
View File
@@ -0,0 +1,307 @@
use base64::Engine;
use glam::{DVec2, UVec2};
use graphite_editor_control_protocol::{MouseButton, Rectangle};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::{BufRead, BufReader, Write};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError, mpsc};
use std::time::{Duration, Instant};
use crate::paths;
const REQUEST_TIMEOUT: Duration = Duration::from_secs(60);
const CLOSE_TIMEOUT: Duration = Duration::from_secs(10);
const EXIT_POLL_INTERVAL: Duration = Duration::from_millis(100);
/// The steps the Playwright process can carry out, matching the `Request` type in `playwright/browser.ts`.
#[derive(Serialize)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
enum Request<'a> {
Launch {
url: &'a str,
size: UVec2,
scale: f64,
headed: bool,
ready_selector: &'a str,
timeout: u64,
},
Close,
Resize {
size: UVec2,
},
MouseMove {
to: DVec2,
},
MouseDown {
button: MouseButton,
click_count: u32,
},
MouseUp {
button: MouseButton,
click_count: u32,
},
Wheel {
delta: DVec2,
},
KeyDown {
key: &'a str,
},
KeyUp {
key: &'a str,
},
Type {
text: &'a str,
},
Screenshot {
#[serde(skip_serializing_if = "Option::is_none")]
clip: Option<Rectangle>,
},
BoundingBox {
selector: &'a str,
},
Locate {
#[serde(skip_serializing_if = "Option::is_none")]
data: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
text: Option<&'a str>,
},
NextFrame {
timeout: u64,
},
TakeEvents,
}
#[derive(Serialize)]
struct Envelope<'a> {
id: u64,
request: Request<'a>,
}
#[derive(Deserialize)]
struct Reply {
id: u64,
#[serde(default)]
value: serde_json::Value,
error: Option<String>,
}
#[derive(Deserialize)]
pub struct RawLocated {
#[serde(rename = "box")]
pub bounds: Rectangle,
pub text: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PageEvents {
pub console_errors: Vec<String>,
pub crashed: bool,
}
type ReplySender = mpsc::Sender<Result<serde_json::Value, String>>;
fn exited_error() -> String {
"The Playwright process has exited, and the session log may say why".to_string()
}
/// The browser being driven, reached through the Node process that holds Playwright.
pub struct Browser {
process: Mutex<Child>,
stdin: Mutex<ChildStdin>,
// Becomes `None` once the process has exited, so no request can wait on a reply that will never come
pending: Arc<Mutex<Option<HashMap<u64, ReplySender>>>>,
next_id: AtomicU64,
}
impl Browser {
/// Starts the Playwright process, which shares this process's error output.
pub fn start() -> Result<Self, String> {
let script = paths::playwright_directory().join("browser.ts");
if !paths::playwright_directory().join("node_modules").join("playwright-core").exists() {
return Err("Playwright is not installed, so run `cargo run drive install` first".to_string());
}
let mut process = Command::new("node")
.arg(script)
.env("PLAYWRIGHT_BROWSERS_PATH", paths::browsers_directory())
.current_dir(paths::playwright_directory())
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.map_err(|error| format!("Failed to start Node.js, which runs Playwright: {error}"))?;
let (Some(stdin), Some(stdout)) = (process.stdin.take(), process.stdout.take()) else {
return Err("The Playwright process has no input or output to talk over".to_string());
};
let pending = Arc::new(Mutex::new(Some(HashMap::<u64, ReplySender>::new())));
let reader_pending = pending.clone();
std::thread::spawn(move || {
for line in BufReader::new(stdout).lines() {
let Ok(line) = line else { break };
let Ok(reply) = serde_json::from_str::<Reply>(&line) else {
eprintln!("The Playwright process sent a line that is not a reply: {line}");
continue;
};
let sender = reader_pending.lock().unwrap_or_else(PoisonError::into_inner).as_mut().and_then(|pending| pending.remove(&reply.id));
if let Some(sender) = sender {
let _ = sender.send(match reply.error {
Some(error) => Err(error),
None => Ok(reply.value),
});
}
}
// Dropping the senders fails every request still waiting
reader_pending.lock().unwrap_or_else(PoisonError::into_inner).take();
});
Ok(Self {
process: Mutex::new(process),
stdin: Mutex::new(stdin),
pending,
next_id: AtomicU64::new(1),
})
}
fn request<T: DeserializeOwned>(&self, request: Request) -> Result<T, String> {
self.request_within(request, REQUEST_TIMEOUT)
}
// A page stuck in a loop never acknowledges input, so waiting is bounded to keep it from holding up the session forever
fn request_within<T: DeserializeOwned>(&self, request: Request, timeout: Duration) -> Result<T, String> {
let (id, receiver) = self.send(request)?;
let value = match receiver.recv_timeout(timeout) {
Ok(reply) => reply?,
Err(mpsc::RecvTimeoutError::Timeout) => {
if let Some(pending) = self.pending.lock().unwrap_or_else(PoisonError::into_inner).as_mut() {
pending.remove(&id);
}
return Err("The page stopped responding".to_string());
}
Err(mpsc::RecvTimeoutError::Disconnected) => return Err(exited_error()),
};
serde_json::from_value(value).map_err(|error| format!("The Playwright process sent an unexpected reply: {error}"))
}
// Sends a request, returning its ID and where its reply will arrive
fn send(&self, request: Request) -> Result<(u64, mpsc::Receiver<Result<serde_json::Value, String>>), String> {
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
let (sender, receiver) = mpsc::channel();
match self.pending.lock().unwrap_or_else(PoisonError::into_inner).as_mut() {
Some(pending) => pending.insert(id, sender),
None => return Err(exited_error()),
};
let mut line = serde_json::to_string(&Envelope { id, request }).map_err(|error| error.to_string())?;
line.push('\n');
let written = self.stdin.lock().unwrap_or_else(PoisonError::into_inner).write_all(line.as_bytes());
if written.is_err() {
return Err(exited_error());
}
Ok((id, receiver))
}
pub fn launch(&self, url: &str, size: UVec2, scale: f64, headed: bool, ready_selector: &str, timeout: Duration) -> Result<(), String> {
let request = Request::Launch {
url,
size,
scale,
headed,
ready_selector,
timeout: timeout.as_millis() as u64,
};
// Loading the page and waiting for it to be ready may each take the whole timeout
self.request_within(request, timeout * 2 + REQUEST_TIMEOUT)
}
/// Closes the browser, ending the Playwright process if it does not exit in time.
pub fn close(&self) {
let deadline = Instant::now() + CLOSE_TIMEOUT;
let closed = self
.send(Request::Close)
.and_then(|(_, receiver)| receiver.recv_timeout(CLOSE_TIMEOUT).map_err(|_| "It did not answer in time".to_string())?);
if let Err(error) = closed {
eprintln!("Failed to close the browser: {error}");
}
let mut process = self.process.lock().unwrap_or_else(PoisonError::into_inner);
while Instant::now() < deadline {
if !matches!(process.try_wait(), Ok(None)) {
return;
}
std::thread::sleep(EXIT_POLL_INTERVAL);
}
let _ = process.kill();
}
pub fn resize(&self, size: UVec2) -> Result<(), String> {
self.request(Request::Resize { size })
}
pub fn mouse_move(&self, to: DVec2) -> Result<(), String> {
self.request(Request::MouseMove { to })
}
pub fn mouse_down(&self, button: MouseButton, click_count: u32) -> Result<(), String> {
self.request(Request::MouseDown { button, click_count })
}
pub fn mouse_up(&self, button: MouseButton, click_count: u32) -> Result<(), String> {
self.request(Request::MouseUp { button, click_count })
}
pub fn wheel(&self, delta: DVec2) -> Result<(), String> {
self.request(Request::Wheel { delta })
}
pub fn key_down(&self, key: &str) -> Result<(), String> {
self.request(Request::KeyDown { key })
}
pub fn key_up(&self, key: &str) -> Result<(), String> {
self.request(Request::KeyUp { key })
}
pub fn type_text(&self, text: &str) -> Result<(), String> {
self.request(Request::Type { text })
}
/// Captures the page, or an area of it, as a PNG.
pub fn screenshot(&self, clip: Option<Rectangle>) -> Result<Vec<u8>, String> {
let encoded: String = self.request(Request::Screenshot { clip })?;
base64::engine::general_purpose::STANDARD
.decode(encoded)
.map_err(|error| format!("The screenshot was not valid Base64: {error}"))
}
/// The area of the first element matching a CSS selector, if any matches and it is displayed.
pub fn bounding_box(&self, selector: &str) -> Result<Option<Rectangle>, String> {
self.request(Request::BoundingBox { selector })
}
pub fn locate(&self, data: Option<&str>, text: Option<&str>) -> Result<Vec<RawLocated>, String> {
self.request(Request::Locate { data, text })
}
/// Waits for the page to draw its next frame, or for the timeout if it has stopped drawing.
pub fn next_frame(&self, timeout: Duration) -> Result<(), String> {
let timeout = timeout.as_millis() as u64;
self.request(Request::NextFrame { timeout })
}
/// Whether the page has crashed, and the errors it has logged since this was last asked.
pub fn take_events(&self) -> Result<PageEvents, String> {
self.request(Request::TakeEvents)
}
}
+246
View File
@@ -0,0 +1,246 @@
//! Starting, reaching, and stopping the session host, which owns the browser so separate invocations can act on the same editor one after another.
use graphite_editor_control_protocol::{ClientMessage, Command, CommandResult, HostMessage, PROTOCOL_VERSION};
use interprocess::local_socket::{RecvHalf, SendHalf, Stream, prelude::*};
use serde::{Deserialize, Serialize};
use std::io::BufReader;
use std::path::PathBuf;
use std::sync::mpsc;
use std::time::{Duration, Instant};
use crate::paths;
use crate::processes::{POLL_INTERVAL, PROBE_TIMEOUT, read_log, read_record, spawn_detached, terminate};
use crate::session::SessionOptions;
use crate::socket;
const SESSION_START_TIMEOUT: Duration = Duration::from_secs(300);
const SESSION_STOP_TIMEOUT: Duration = Duration::from_secs(10);
const HOST_COPY_ATTEMPTS: u32 = 8;
/// Where the session host can be reached, and the secret every connection to it must open with.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionRecord {
pub process_id: u32,
/// Names the host's socket, unique to this session so a stale record cannot reach another one.
pub session_id: String,
pub url: String,
pub token: String,
}
enum OpenFailure {
/// Nothing answered as the recorded session.
Unreachable,
/// The session answered but turned the connection away for the given reason.
Refused(String),
}
pub struct Connection {
receiver: BufReader<RecvHalf>,
sender: SendHalf,
next_id: u64,
}
impl Connection {
fn open(record: &SessionRecord) -> Result<Self, OpenFailure> {
let name = socket::name(&record.session_id).map_err(|_| OpenFailure::Unreachable)?;
let stream = Stream::connect(name).map_err(|_| OpenFailure::Unreachable)?;
let (receiver, sender) = stream.split();
let mut connection = Self {
receiver: BufReader::new(receiver),
sender,
next_id: 1,
};
let attach = ClientMessage::Attach {
version: PROTOCOL_VERSION,
token: record.token.clone(),
};
connection.send(&attach).map_err(|_| OpenFailure::Unreachable)?;
match connection.receive() {
Ok(Some(HostMessage::Attached { process_id, .. })) if process_id == record.process_id => Ok(connection),
Ok(Some(HostMessage::Refused { reason })) => Err(OpenFailure::Refused(reason)),
_ => Err(OpenFailure::Unreachable),
}
}
pub fn perform(&mut self, commands: Vec<Command>) -> Result<Vec<CommandResult>, String> {
let id = self.next_id;
self.next_id += 1;
self.send(&ClientMessage::Perform { id, commands })?;
match self.receive()? {
Some(HostMessage::Results { id: answered, results }) if answered == id => Ok(results),
Some(_) => Err("The session sent an unexpected reply".to_string()),
None => Err(format!(
"The session closed the connection before answering, and its log may say why: {}",
paths::session_log_file().display()
)),
}
}
// Asks the session to end, returning whether it exited in time, which its end of the connection closing shows
fn shut_down(mut self) -> bool {
if self.send(&ClientMessage::Shutdown).is_err() {
return false;
}
let (sender, receiver) = mpsc::channel();
std::thread::spawn(move || {
while let Ok(Some(_)) = self.receive() {}
let _ = sender.send(());
});
receiver.recv_timeout(SESSION_STOP_TIMEOUT).is_ok()
}
fn send(&mut self, message: &ClientMessage) -> Result<(), String> {
socket::write_message(&mut self.sender, message)
}
fn receive(&mut self) -> Result<Option<HostMessage>, String> {
socket::read_message(&mut self.receiver)
}
}
pub enum SessionState {
NotRunning,
Running(SessionRecord, Connection),
/// A session answered but turned the connection away, such as one started by a build that speaks another protocol version.
Refused(SessionRecord, String),
/// A session's socket exists but the session did not answer in time.
Unresponsive(SessionRecord),
}
/// Finds the running session, removing a stale record left by one that is gone.
pub fn session_state() -> SessionState {
let Some(record) = read_record::<SessionRecord>(&paths::session_file()) else {
return SessionState::NotRunning;
};
// A session that has stopped answering cannot hold up every later invocation
let (sender, receiver) = mpsc::channel();
let probe_record = record.clone();
std::thread::spawn(move || sender.send(Connection::open(&probe_record)));
match receiver.recv_timeout(PROBE_TIMEOUT) {
Ok(Ok(connection)) => SessionState::Running(record, connection),
Ok(Err(OpenFailure::Refused(reason))) => SessionState::Refused(record, reason),
Ok(Err(OpenFailure::Unreachable)) => {
let _ = std::fs::remove_file(paths::session_file());
SessionState::NotRunning
}
Err(_) => SessionState::Unresponsive(record),
}
}
pub fn perform(commands: Vec<Command>) -> Result<Vec<CommandResult>, String> {
match session_state() {
SessionState::Running(_, mut connection) => connection.perform(commands),
SessionState::Refused(_, reason) => Err(reason),
SessionState::Unresponsive(_) => Err("The session is not answering, so stop it and start a new one".to_string()),
SessionState::NotRunning => Err("No session is running, so start one first".to_string()),
}
}
pub fn start_session(options: &SessionOptions) -> Result<(), String> {
let _lock = StartLock::take()?;
if !matches!(session_state(), SessionState::NotRunning) {
return Err("A session is already running, so stop it first".to_string());
}
let mut arguments = vec![
"host".to_string(),
"--url".into(),
options.url.clone(),
"--width".into(),
options.size.x.to_string(),
"--height".into(),
options.size.y.to_string(),
"--scale".into(),
options.scale.to_string(),
];
if options.headed {
arguments.push("--headed".into());
}
let mut process = spawn_detached(&host_executable()?, &arguments, &paths::tool_directory(), &paths::session_log_file())?;
let deadline = Instant::now() + SESSION_START_TIMEOUT;
while Instant::now() < deadline {
if read_record::<SessionRecord>(&paths::session_file()).is_some_and(|record| record.process_id == process.id) {
return Ok(());
}
if !process.is_running() {
return Err(format!("The session failed to start:\n{}", read_log(&paths::session_log_file())));
}
std::thread::sleep(POLL_INTERVAL);
}
terminate(process.id);
Err(format!("The editor did not finish loading in time:\n{}", read_log(&paths::session_log_file())))
}
pub fn stop_session() {
match session_state() {
SessionState::Running(record, connection) => {
// The process answered as itself just above, so ending it by its ID is safe if it does not exit in time
if !connection.shut_down() {
terminate(record.process_id);
}
}
// Only the session's own process listens on the socket named for it, so ending that process is safe
SessionState::Refused(record, _) | SessionState::Unresponsive(record) => terminate(record.process_id),
SessionState::NotRunning => {}
}
let _ = std::fs::remove_file(paths::session_file());
}
// On Windows a running program's file cannot be replaced, so the session runs from a copy to leave the build free to update the original
fn host_executable() -> Result<PathBuf, String> {
let current = std::env::current_exe().map_err(|error| format!("Failed to find this program's file: {error}"))?;
if !cfg!(windows) {
return Ok(current);
}
let copy = paths::session_directory().join(format!("host{}", std::env::consts::EXE_SUFFIX));
paths::create_session_directory()?;
// The previous session's copy can stay locked for a moment after that session exits
for _ in 0..HOST_COPY_ATTEMPTS {
if std::fs::copy(&current, &copy).is_ok() {
return Ok(copy);
}
std::thread::sleep(POLL_INTERVAL);
}
eprintln!("Failed to copy this program for the session to run from, so rebuilding it will fail until the session stops");
Ok(current)
}
// A lock file held while starting keeps two `start` commands from both launching a session
struct StartLock;
impl StartLock {
fn take() -> Result<Self, String> {
let path = paths::session_lock_file();
let age = std::fs::metadata(&path).and_then(|metadata| metadata.modified()).ok().and_then(|modified| modified.elapsed().ok());
if age.is_some_and(|age| age > SESSION_START_TIMEOUT) {
let _ = std::fs::remove_file(&path);
}
paths::create_session_directory()?;
match std::fs::File::create_new(&path) {
Ok(_) => Ok(Self),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => Err("Another `start` is already in progress".to_string()),
Err(error) => Err(format!("Failed to create {}: {error}", path.display())),
}
}
}
impl Drop for StartLock {
fn drop(&mut self) {
let _ = std::fs::remove_file(paths::session_lock_file());
}
}
@@ -0,0 +1,83 @@
use glam::DVec2;
use image::{ImageFormat, Rgba, RgbaImage};
use std::io::Cursor;
use std::path::Path;
use crate::session::write_file;
const COLUMNS: usize = 2;
const GAP: f64 = 4.;
const CROSSHAIR_HALF_SIZE: f64 = 10.;
/// A capture of the page, or an area of it, with where the pointer was.
pub struct Frame {
/// The capture as a PNG.
pub image: Vec<u8>,
/// The pointer's position measured from the capture's top left corner, in CSS pixels.
pub pointer: DVec2,
/// The pointer's position on the page, in CSS pixels.
pub page_pointer: DVec2,
}
/// Lays captures out in a grid, read left to right then top to bottom, each with a crosshair where the pointer was, and writes it as a PNG.
pub fn write_contact_sheet(path: &Path, frames: &[Frame], scale: f64) -> Result<(), String> {
let images = frames
.iter()
.map(|frame| {
let mut image = image::load_from_memory_with_format(&frame.image, ImageFormat::Png)
.map_err(|error| format!("A capture could not be read as a PNG: {error}"))?
.to_rgba8();
draw_crosshair(&mut image, frame.pointer, scale);
Ok(image)
})
.collect::<Result<Vec<_>, String>>()?;
if images.is_empty() {
return Err("There are no captures to lay out".to_string());
}
let columns = COLUMNS.min(images.len()) as u32;
let rows = images.len().div_ceil(COLUMNS) as u32;
let gap = (GAP * scale).round() as u32;
let cell_width = images.iter().map(RgbaImage::width).max().unwrap_or_default();
let cell_height = images.iter().map(RgbaImage::height).max().unwrap_or_default();
let sheet_width = columns * cell_width + (columns - 1) * gap;
let sheet_height = rows * cell_height + (rows - 1) * gap;
let mut sheet = RgbaImage::from_pixel(sheet_width, sheet_height, Rgba([0, 0, 0, 255]));
for (index, image) in images.iter().enumerate() {
let column = index as u32 % columns;
let row = index as u32 / columns;
image::imageops::replace(&mut sheet, image, (column * (cell_width + gap)) as i64, (row * (cell_height + gap)) as i64);
}
let mut encoded = Cursor::new(Vec::new());
sheet.write_to(&mut encoded, ImageFormat::Png).map_err(|error| format!("Failed to encode the image: {error}"))?;
write_file(path, encoded.get_ref())
}
// Inverts the colors under a crosshair one CSS pixel thick, keeping it visible against light and dark backgrounds alike
fn draw_crosshair(image: &mut RgbaImage, pointer: DVec2, scale: f64) {
let to_device_pixels = |css: DVec2| (css * scale).round().as_i64vec2();
// Half-open ranges of device pixels for each line's thickness and its reach to either side of the pointer
let line_start = to_device_pixels(pointer);
let line_end = to_device_pixels(pointer + 1.);
let reach_start = to_device_pixels(pointer - CROSSHAIR_HALF_SIZE);
let reach_end = to_device_pixels(pointer + CROSSHAIR_HALF_SIZE + 1.);
for y in reach_start.y.max(0)..reach_end.y.min(image.height() as i64) {
for x in reach_start.x.max(0)..reach_end.x.min(image.width() as i64) {
let on_vertical_line = (line_start.x..line_end.x).contains(&x);
let on_horizontal_line = (line_start.y..line_end.y).contains(&y);
if !on_vertical_line && !on_horizontal_line {
continue;
}
let pixel = image.get_pixel_mut(x as u32, y as u32);
for channel in &mut pixel.0[..3] {
*channel = 255 - *channel;
}
}
}
}
+150
View File
@@ -0,0 +1,150 @@
//! The long-lived process that owns the browser, which `start` runs in the background and every later invocation connects to.
use graphite_editor_control_protocol::{ClientMessage, Command, CommandResult, HostMessage, PROTOCOL_VERSION};
use interprocess::local_socket::{ListenerOptions, Stream, prelude::*};
use std::io::BufReader;
use std::sync::{Arc, Mutex, PoisonError};
use crate::browser::Browser;
use crate::client::SessionRecord;
use crate::paths;
use crate::processes::write_record;
use crate::session::{EditorSession, SessionOptions};
use crate::socket;
const TOKEN_BYTES: usize = 32;
const SESSION_ID_BYTES: usize = 8;
struct HostState {
// Commands are performed one batch at a time so the commands of overlapping invocations cannot interleave
session: Mutex<EditorSession>,
browser: Arc<Browser>,
token: String,
}
fn random_hex(byte_count: usize) -> Result<String, String> {
let mut bytes = vec![0; byte_count];
getrandom::fill(&mut bytes).map_err(|error| format!("Failed to generate random bytes: {error}"))?;
Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect())
}
pub fn run(options: SessionOptions) -> Result<(), String> {
// Only someone who can read the record file knows the token, which keeps other programs from driving the session
let token = random_hex(TOKEN_BYTES)?;
let session_id = random_hex(SESSION_ID_BYTES)?;
let browser = Arc::new(Browser::start()?);
let session = EditorSession::launch(browser.clone(), options.clone())?;
let listener = ListenerOptions::new()
.name(socket::name(&session_id)?)
.try_overwrite(true)
.create_sync()
.map_err(|error| format!("Failed to listen on the session's socket: {error}"))?;
let record = SessionRecord {
process_id: std::process::id(),
session_id,
url: options.url,
token: token.clone(),
};
write_record(&paths::session_file(), &record)?;
let state = Arc::new(HostState {
session: Mutex::new(session),
browser,
token,
});
for connection in listener.incoming() {
match connection {
Ok(stream) => {
let state = state.clone();
std::thread::spawn(move || serve(stream, &state));
}
Err(error) => eprintln!("Failed to accept a connection: {error}"),
}
}
Ok(())
}
fn serve(stream: Stream, state: &HostState) {
let (receiver, mut sender) = stream.split();
let mut receiver = BufReader::new(receiver);
let refusal = match socket::read_message(&mut receiver) {
Ok(Some(ClientMessage::Attach { version, .. })) if version != PROTOCOL_VERSION => Some(format!(
"The session speaks version {PROTOCOL_VERSION} of the protocol rather than version {version}, so stop it and start a new one"
)),
Ok(Some(ClientMessage::Attach { token, .. })) if token != state.token => Some("The token does not match the session's".to_string()),
Ok(Some(ClientMessage::Attach { .. })) => None,
_ => Some("A connection must begin by attaching".to_string()),
};
if let Some(reason) = refusal {
let _ = socket::write_message(&mut sender, &HostMessage::Refused { reason });
return;
}
let attached = HostMessage::Attached {
version: PROTOCOL_VERSION,
process_id: std::process::id(),
};
if socket::write_message(&mut sender, &attached).is_err() {
return;
}
loop {
let message = match socket::read_message(&mut receiver) {
Ok(Some(message)) => message,
Ok(None) => return,
Err(error) => {
eprintln!("{error}");
return;
}
};
let reply = match message {
ClientMessage::Perform { id, commands } => {
let mut session = state.session.lock().unwrap_or_else(PoisonError::into_inner);
HostMessage::Results {
id,
results: perform_all(&mut session, &commands),
}
}
ClientMessage::Shutdown => {
let _ = socket::write_message(&mut sender, &HostMessage::ShuttingDown);
shut_down(state);
}
ClientMessage::Attach { .. } => {
let reason = "The connection is already attached".to_string();
let _ = socket::write_message(&mut sender, &HostMessage::Refused { reason });
return;
}
};
if socket::write_message(&mut sender, &reply).is_err() {
return;
}
}
}
fn perform_all(session: &mut EditorSession, commands: &[Command]) -> Vec<CommandResult> {
let mut results = Vec::new();
for command in commands {
let result = session.perform(command);
let failed = !result.ok;
results.push(result);
// The remaining commands are skipped after a failure, since they were written assuming the earlier ones succeeded
if failed {
break;
}
}
results
}
// Exits even if closing the browser fails, so a shutdown always ends the process, which closes the connection that asked for it
fn shut_down(state: &HostState) -> ! {
let _ = std::fs::remove_file(paths::session_file());
state.browser.close();
std::process::exit(0);
}
+659
View File
@@ -0,0 +1,659 @@
//! Drives the Graphite web editor the way a person does, with real mouse and keyboard input delivered to its own isolated browser,
//! for scripts, QA, and agents. Run it with `cargo run drive <command>`.
mod browser;
mod client;
mod contact_sheet;
mod host;
mod paths;
mod processes;
mod session;
mod socket;
use clap::{Args, Parser, Subcommand, ValueEnum};
use glam::{DVec2, UVec2};
use graphite_editor_control_protocol::{Command, CommandResult, Filmstrip, MouseButton, Rectangle, Space, parse_scenario};
use serde::Serialize;
use std::num::NonZeroU32;
use std::path::PathBuf;
use std::process::ExitCode;
use crate::session::SessionOptions;
#[derive(Parser)]
#[command(
name = "cargo run drive",
bin_name = "cargo run drive",
about = "Drive the Graphite web editor with real mouse and keyboard input in an isolated browser"
)]
struct Arguments {
#[command(subcommand)]
command: CliCommand,
}
#[derive(Subcommand)]
enum CliCommand {
/// Download the driver's own isolated browser and the Playwright package that drives it.
Install,
/// Serve the editor with the Vite dev server, building its Wasm first when run through `cargo run drive`.
Serve {
/// The port to serve on, which `start` then opens.
#[arg(long, default_value_t = 8080, value_parser = clap::value_parser!(u16).range(1..))]
port: u16,
},
/// Open the editor in a new session.
Start {
/// The editor's address, by default the dev server that `serve` started, or else http://localhost:8080/.
#[arg(long)]
url: Option<String>,
/// The page's size in CSS pixels, as <width>x<height>.
#[arg(long, value_parser = parse_size)]
size: Option<UVec2>,
/// How many device pixels make one CSS pixel, for a closer look at small details.
#[arg(long, default_value_t = 1., value_parser = parse_scale)]
scale: f64,
/// Show the browser's window.
#[arg(long)]
headed: bool,
},
/// Change the size of the page.
Resize {
/// The page's width in CSS pixels.
width: u32,
/// The page's height in CSS pixels.
height: u32,
#[command(flatten)]
shot: Shot,
},
/// Report the state of the session.
Status,
/// Close the session.
Stop,
/// Close the session and the dev server that `serve` started.
Shutdown,
/// Move the pointer.
#[command(allow_negative_numbers = true)]
Move {
/// The horizontal position in CSS pixels.
#[arg(value_parser = parse_coordinate)]
x: f64,
/// The vertical position in CSS pixels.
#[arg(value_parser = parse_coordinate)]
y: f64,
#[command(flatten)]
space: InSpace,
#[command(flatten)]
shot: Shot,
},
/// Press a mouse button: left (the default), middle, or right.
Down {
#[arg(value_parser = parse_button)]
button: Option<MouseButton>,
#[command(flatten)]
shot: Shot,
},
/// Release a mouse button: left (the default), middle, or right.
Up {
#[arg(value_parser = parse_button)]
button: Option<MouseButton>,
#[command(flatten)]
shot: Shot,
},
/// Click at a point, with any keys held from before the first press.
#[command(allow_negative_numbers = true)]
Click {
/// The horizontal position in CSS pixels.
#[arg(value_parser = parse_coordinate)]
x: f64,
/// The vertical position in CSS pixels.
#[arg(value_parser = parse_coordinate)]
y: f64,
#[command(flatten)]
space: InSpace,
#[command(flatten)]
button: ButtonOption,
/// How many clicks to make, such as 2 for a double click.
#[arg(long)]
count: Option<NonZeroU32>,
#[command(flatten)]
keys: Keys,
#[command(flatten)]
shot: Shot,
},
/// Drag between two points, with any keys held from before the press.
///
/// To press a key partway through a drag, use `drag --hold`, then `key down`, then `move`, then `up`.
#[command(allow_negative_numbers = true)]
Drag {
/// The starting horizontal position in CSS pixels.
#[arg(value_parser = parse_coordinate)]
x1: f64,
/// The starting vertical position in CSS pixels.
#[arg(value_parser = parse_coordinate)]
y1: f64,
/// The ending horizontal position in CSS pixels.
#[arg(value_parser = parse_coordinate)]
x2: f64,
/// The ending vertical position in CSS pixels.
#[arg(value_parser = parse_coordinate)]
y2: f64,
#[command(flatten)]
space: InSpace,
#[command(flatten)]
button: ButtonOption,
#[command(flatten)]
keys: Keys,
/// How many steps to move in, instead of one for every 8 pixels.
#[arg(long)]
steps: Option<NonZeroU32>,
/// Keep the button and keys held once the drag is done.
#[arg(long)]
hold: bool,
/// Capture frames along the drag and lay them out in this image, each with a crosshair where the pointer was.
#[arg(long)]
filmstrip: Option<PathBuf>,
/// How many frames the filmstrip captures.
#[arg(long, requires = "filmstrip")]
frames: Option<NonZeroU32>,
#[command(flatten)]
area: CaptureArea,
#[command(flatten)]
shot: Shot,
},
/// Hold, release, or tap a key such as Shift, Control, Alt, Enter, or KeyP, where only `press` also takes a combination such as Control+KeyZ.
Key {
/// Whether to hold, release, or tap the key.
action: KeyAction,
/// The key, named as in `KeyboardEvent.key` or `KeyboardEvent.code`.
key: String,
#[command(flatten)]
shot: Shot,
},
/// Type text into the focused field.
Type {
/// The text to type, which may be given as several arguments joined by spaces.
#[arg(required = true)]
text: Vec<String>,
#[command(flatten)]
shot: Shot,
},
/// Turn the mouse wheel, in notches of up to 100 pixels.
#[command(allow_negative_numbers = true)]
Scroll {
/// How far to scroll horizontally, in pixels.
#[arg(value_parser = parse_coordinate)]
delta_x: f64,
/// How far to scroll vertically, in pixels.
#[arg(value_parser = parse_coordinate)]
delta_y: f64,
/// Move the pointer here first, as <x>,<y>.
#[arg(long, value_parser = parse_point)]
at: Option<DVec2>,
#[command(flatten)]
space: InSpace,
#[command(flatten)]
shot: Shot,
},
/// Capture the page.
Screenshot {
/// The image to write, with a relative path landing in the output folder.
file: PathBuf,
/// Mark where the pointer is with a crosshair.
#[arg(long)]
cursor: bool,
#[command(flatten)]
area: CaptureArea,
},
/// Find elements by a `data-*` attribute name, the visible text they contain, or both.
Locate {
/// The name of a `data-*` attribute the elements have, without the `data-` prefix.
#[arg(long)]
data: Option<String>,
/// Text the elements contain.
#[arg(long)]
text: Option<String>,
},
/// Pause for a number of milliseconds, or with `idle`, wait until the editor stops redrawing.
Wait {
/// A number of milliseconds, or `idle`.
duration: String,
#[command(flatten)]
shot: Shot,
},
/// Perform a JSON array of commands.
Act {
/// The commands, as a JSON array.
json: String,
#[command(flatten)]
shot: Shot,
},
/// Perform the steps of a scenario file.
Run {
/// The scenario file, which holds one command per line written as JSON, along with any blank lines and `//` comments.
file: PathBuf,
#[command(flatten)]
shot: Shot,
},
/// Host a session, which `start` runs in the background.
#[command(hide = true)]
Host {
#[arg(long)]
url: String,
#[arg(long)]
width: u32,
#[arg(long)]
height: u32,
#[arg(long)]
scale: f64,
#[arg(long)]
headed: bool,
},
}
#[derive(Args)]
struct Shot {
/// Once the command is done and the editor is idle, capture a screenshot to this file.
#[arg(long = "shot", id = "shot")]
path: Option<PathBuf>,
}
#[derive(Args)]
struct InSpace {
/// Measure points from the document viewport's top left corner (`viewport`) instead of the page's (`page`).
#[arg(long = "in", value_parser = parse_space)]
space: Option<Space>,
}
#[derive(Args)]
struct ButtonOption {
/// The mouse button: left (the default), middle, or right.
#[arg(long, value_parser = parse_button)]
button: Option<MouseButton>,
}
#[derive(Args)]
struct Keys {
/// Keys to hold, separated by commas, such as Shift,Alt.
#[arg(long, value_delimiter = ',')]
keys: Option<Vec<String>>,
}
#[derive(Args)]
struct CaptureArea {
/// Limit the capture to the document viewport (`viewport`) or the first element matching a CSS selector.
#[arg(long)]
region: Option<String>,
/// Limit the capture to an exact area of the page, as <x>,<y>,<width>,<height>.
#[arg(long, value_parser = parse_clip)]
clip: Option<Rectangle>,
}
#[derive(Clone, Copy, ValueEnum)]
enum KeyAction {
Down,
Up,
Press,
}
// A number that a position or distance can be, which rules out infinities and NaN
fn parse_coordinate(value: &str) -> Result<f64, String> {
value
.trim()
.parse::<f64>()
.ok()
.filter(|number| number.is_finite())
.ok_or_else(|| format!("Expected a finite number, not \"{value}\""))
}
fn parse_scale(value: &str) -> Result<f64, String> {
parse_coordinate(value)
.ok()
.filter(|scale| *scale > 0.)
.ok_or_else(|| format!("Expected a positive number, not \"{value}\""))
}
fn parse_numbers<const COUNT: usize>(value: &str, separator: char) -> Result<[f64; COUNT], String> {
let numbers = value
.split(separator)
.map(|part| parse_coordinate(part).ok())
.collect::<Option<Vec<_>>>()
.and_then(|numbers| <[f64; COUNT]>::try_from(numbers).ok());
numbers.ok_or_else(|| format!("Expected {COUNT} numbers separated by \"{separator}\""))
}
fn parse_point(value: &str) -> Result<DVec2, String> {
parse_numbers::<2>(value, ',').map(DVec2::from)
}
fn parse_size(value: &str) -> Result<UVec2, String> {
let lengths = value
.split('x')
.map(|part| part.trim().parse::<NonZeroU32>().ok().map(NonZeroU32::get))
.collect::<Option<Vec<_>>>()
.and_then(|lengths| <[u32; 2]>::try_from(lengths).ok());
lengths
.map(UVec2::from)
.ok_or_else(|| "Expected a width and height that are positive integers, as <width>x<height>".to_string())
}
fn parse_clip(value: &str) -> Result<Rectangle, String> {
let [x, y, width, height] = parse_numbers::<4>(value, ',')?;
Ok(Rectangle { x, y, width, height })
}
fn parse_space(value: &str) -> Result<Space, String> {
match value {
"page" => Ok(Space::Page),
"viewport" => Ok(Space::Viewport),
_ => Err(format!("Expected \"page\" or \"viewport\", not \"{value}\"")),
}
}
fn parse_button(value: &str) -> Result<MouseButton, String> {
match value {
"left" => Ok(MouseButton::Left),
"middle" => Ok(MouseButton::Middle),
"right" => Ok(MouseButton::Right),
_ => Err(format!("Unknown mouse button \"{value}\"")),
}
}
// The commands a command line invocation performs, and where it captures a screenshot afterward if asked to
fn commands_for(command: CliCommand) -> Result<(Vec<Command>, Option<PathBuf>), String> {
let no_shot = Shot { path: None };
let (commands, shot) = match command {
CliCommand::Resize { width, height, shot } => (vec![Command::Resize { size: UVec2::new(width, height) }], shot),
CliCommand::Status => (vec![Command::Status {}], no_shot),
CliCommand::Move { x, y, space, shot } => (
vec![Command::Move {
to: DVec2::new(x, y),
space: space.space,
steps: None,
}],
shot,
),
CliCommand::Down { button, shot } => (vec![Command::Down { button }], shot),
CliCommand::Up { button, shot } => (vec![Command::Up { button }], shot),
CliCommand::Click {
x,
y,
space,
button,
count,
keys,
shot,
} => (
vec![Command::Click {
at: DVec2::new(x, y),
space: space.space,
button: button.button,
count,
keys: keys.keys,
}],
shot,
),
CliCommand::Drag {
x1,
y1,
x2,
y2,
space,
button,
keys,
steps,
hold,
filmstrip,
frames,
area,
shot,
} => {
let filmstrip = filmstrip.map(|path| Filmstrip {
path,
frames,
region: area.region,
clip: area.clip,
});
let drag = Command::Drag {
from: DVec2::new(x1, y1),
to: DVec2::new(x2, y2),
space: space.space,
button: button.button,
keys: keys.keys,
steps,
release: Some(!hold),
filmstrip,
};
(vec![drag], shot)
}
CliCommand::Key { action, key, shot } => {
let command = match action {
KeyAction::Down => Command::KeyDown { key },
KeyAction::Up => Command::KeyUp { key },
KeyAction::Press => Command::Press { key },
};
(vec![command], shot)
}
CliCommand::Type { text, shot } => (vec![Command::Type { text: text.join(" ") }], shot),
CliCommand::Scroll { delta_x, delta_y, at, space, shot } => (
vec![Command::Scroll {
delta: DVec2::new(delta_x, delta_y),
at,
space: space.space,
}],
shot,
),
CliCommand::Screenshot { file, cursor, area } => (
vec![Command::Screenshot {
path: file,
cursor: Some(cursor),
region: area.region,
clip: area.clip,
}],
no_shot,
),
CliCommand::Locate { data, text } => (vec![Command::Locate { data, text }], no_shot),
CliCommand::Wait { duration, shot } => {
let command = if duration == "idle" {
Command::WaitIdle { timeout: None }
} else {
let milliseconds = duration.parse().map_err(|_| format!("Expected a number of milliseconds or \"idle\", not \"{duration}\""))?;
Command::Wait { milliseconds }
};
(vec![command], shot)
}
CliCommand::Act { json, shot } => {
let commands = serde_json::from_str(&json).map_err(|error| format!("Expected a JSON array of commands: {error}"))?;
(commands, shot)
}
CliCommand::Run { file, shot } => {
let contents = std::fs::read_to_string(&file).map_err(|error| format!("Failed to read {}: {error}", file.display()))?;
let steps = parse_scenario(&contents).map_err(|error| format!("The scenario in {} could not be read. {error}", file.display()))?;
(steps, shot)
}
CliCommand::Install | CliCommand::Serve { .. } | CliCommand::Start { .. } | CliCommand::Stop | CliCommand::Shutdown | CliCommand::Host { .. } => {
return Err("This command does not act on the editor".to_string());
}
};
Ok((commands, shot.path))
}
fn print_json(value: &impl Serialize) {
let mut output = Vec::new();
let mut serializer = serde_json::Serializer::with_formatter(&mut output, serde_json::ser::PrettyFormatter::with_indent(b"\t"));
match value.serialize(&mut serializer) {
Ok(()) => println!("{}", String::from_utf8_lossy(&output)),
Err(error) => eprintln!("Failed to print the results: {error}"),
}
}
fn run_program(program: &mut std::process::Command, failure: &str) -> Result<(), String> {
let status = program.status().map_err(|error| format!("{failure}: {error}"))?;
if status.success() { Ok(()) } else { Err(failure.to_string()) }
}
fn install() -> Result<(), String> {
let directory = paths::playwright_directory();
let npm = if cfg!(windows) { "npm.cmd" } else { "npm" };
run_program(
std::process::Command::new(npm).args(["ci", "--no-audit", "--no-fund"]).current_dir(&directory),
"Failed to install Playwright",
)?;
// The full browser runs headless too, so the lighter headless shell is left out
let playwright = directory.join("node_modules").join("playwright-core").join("cli.js");
run_program(
std::process::Command::new("node")
.arg(playwright)
.args(["install", "--no-shell", "chromium"])
.env("PLAYWRIGHT_BROWSERS_PATH", paths::browsers_directory()),
"The browser failed to download",
)
}
// Returns whether every command succeeded
fn run(command: CliCommand) -> Result<bool, String> {
match command {
CliCommand::Install => install()?,
CliCommand::Serve { port } => {
let record = processes::start_dev_server(port)?;
println!("Serving the editor at http://127.0.0.1:{}/", record.port);
}
CliCommand::Start { url, size, scale, headed } => {
let url = url
.or_else(|| processes::dev_server_record().map(|record| format!("http://127.0.0.1:{}/", record.port)))
.unwrap_or_else(|| paths::DEFAULT_EDITOR_URL.to_string());
let size = size.unwrap_or(paths::DEFAULT_WINDOW_SIZE);
client::start_session(&SessionOptions {
url: url.clone(),
size,
scale,
headed,
})?;
println!("The editor is open at {url}");
}
CliCommand::Stop => client::stop_session(),
CliCommand::Shutdown => {
client::stop_session();
processes::stop_dev_server();
}
CliCommand::Host { url, width, height, scale, headed } => {
let size = UVec2::new(width, height);
host::run(SessionOptions { url, size, scale, headed })?;
}
command => {
let (mut commands, shot) = commands_for(command)?;
if let Some(path) = shot {
commands.push(Command::WaitIdle { timeout: None });
commands.push(Command::Screenshot {
path,
cursor: None,
region: None,
clip: None,
});
}
let results: Vec<CommandResult> = client::perform(commands)?;
print_json(&results);
return Ok(results.iter().all(|result| result.ok));
}
}
Ok(true)
}
fn main() -> ExitCode {
match run(Arguments::parse().command) {
Ok(true) => ExitCode::SUCCESS,
Ok(false) => ExitCode::FAILURE,
Err(error) => {
eprintln!("{error}");
ExitCode::FAILURE
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::Path;
#[test]
fn arguments_parse() {
assert_eq!(parse_point("10,-20.5").unwrap(), DVec2::new(10., -20.5));
assert_eq!(parse_size("1600x1000").unwrap(), UVec2::new(1600, 1000));
assert!(parse_size("1600x0").is_err());
assert!(parse_size("1600.5x1000").is_err());
assert!(parse_size("5000000000x1000").is_err());
assert!(parse_clip("1,2,3").is_err());
assert!(parse_space("document").is_err());
assert!(parse_scale("0").is_err());
}
#[test]
fn command_line_is_well_formed() {
<Arguments as clap::CommandFactory>::command().debug_assert();
}
#[test]
fn command_lines_parse() {
Arguments::try_parse_from([
"driver",
"drag",
"10",
"-20",
"30",
"40",
"--in",
"viewport",
"--keys",
"Shift,Alt",
"--filmstrip",
"drag.png",
"--frames",
"4",
])
.unwrap();
Arguments::try_parse_from(["driver", "scroll", "0", "-300", "--at", "100,200"]).unwrap();
Arguments::try_parse_from(["driver", "key", "press", "Control+KeyZ", "--shot", "undo.png"]).unwrap();
assert!(Arguments::try_parse_from(["driver", "screenshot", "a.png", "--shot", "b.png"]).is_err());
}
#[test]
fn non_finite_numbers_are_refused() {
assert!(Arguments::try_parse_from(["driver", "move", "inf", "0"]).is_err());
assert!(Arguments::try_parse_from(["driver", "move", "0", "NaN"]).is_err());
assert!(Arguments::try_parse_from(["driver", "scroll", "0", "-infinity"]).is_err());
assert!(Arguments::try_parse_from(["driver", "start", "--scale", "inf"]).is_err());
}
#[test]
fn relative_paths_land_in_the_output_directory() {
assert_eq!(paths::output_path(Path::new("shot.png")), paths::output_directory().join("shot.png"));
let nested = paths::output_path(Path::new("folder/shot.png"));
assert_eq!(nested.as_os_str(), paths::output_directory().join("folder").join("shot.png").as_os_str());
}
}
+71
View File
@@ -0,0 +1,71 @@
use glam::UVec2;
use std::path::{Path, PathBuf};
pub const DEFAULT_EDITOR_URL: &str = "http://localhost:8080/";
pub const DEFAULT_WINDOW_SIZE: UVec2 = UVec2::new(1600, 1000);
pub fn tool_directory() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
}
pub fn frontend_directory() -> PathBuf {
tool_directory().join("..").join("..").join("frontend")
}
pub fn playwright_directory() -> PathBuf {
tool_directory().join("playwright")
}
// The browser is downloaded here so the driver is isolated from any browser, profile, or history already on the machine
pub fn browsers_directory() -> PathBuf {
tool_directory().join(".browsers")
}
pub fn session_directory() -> PathBuf {
tool_directory().join(".session")
}
/// Creates the session folder, which holds the session's token, so on Unix only its owner may read it.
pub fn create_session_directory() -> Result<(), String> {
let directory = session_directory();
std::fs::create_dir_all(&directory).map_err(|error| format!("Failed to create the session folder: {error}"))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o700)).map_err(|error| format!("Failed to restrict the session folder: {error}"))?;
}
Ok(())
}
pub fn session_file() -> PathBuf {
session_directory().join("session.json")
}
pub fn session_lock_file() -> PathBuf {
session_directory().join("session.lock")
}
pub fn session_log_file() -> PathBuf {
session_directory().join("session.log")
}
pub fn dev_server_file() -> PathBuf {
session_directory().join("dev-server.json")
}
pub fn dev_server_log_file() -> PathBuf {
session_directory().join("dev-server.log")
}
pub fn output_directory() -> PathBuf {
tool_directory().join("output")
}
/// Resolves a path given on the command line or in a scenario, where relative paths land in the output directory.
pub fn output_path(path: &Path) -> PathBuf {
// Rebuilding the path from its components gives it the platform's own separators
let path = path.components().collect::<PathBuf>();
if path.is_absolute() { path } else { output_directory().join(path) }
}
+352
View File
@@ -0,0 +1,352 @@
//! Starting and stopping background processes, and the records they leave so later invocations can find them.
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpStream};
use std::path::{Path, PathBuf};
use std::process::Command;
#[cfg(unix)]
use std::process::Stdio;
use std::time::{Duration, Instant};
use crate::paths;
pub const POLL_INTERVAL: Duration = Duration::from_millis(250);
pub const PROBE_TIMEOUT: Duration = Duration::from_secs(5);
const DEV_SERVER_START_TIMEOUT: Duration = Duration::from_secs(120);
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DevServerRecord {
pub port: u16,
pub process_id: u32,
}
pub fn read_record<T: DeserializeOwned>(path: &Path) -> Option<T> {
serde_json::from_slice(&std::fs::read(path).ok()?).ok()
}
// Writes beside the file, then renames it into place, so a reader never sees it half written
pub fn write_record(path: &Path, record: &impl Serialize) -> Result<(), String> {
let temporary = path.with_extension(format!("{}.tmp", std::process::id()));
let contents = serde_json::to_vec(record).map_err(|error| error.to_string())?;
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|error| format!("Failed to create the folder {}: {error}", parent.display()))?;
}
std::fs::write(&temporary, contents).map_err(|error| format!("Failed to write {}: {error}", temporary.display()))?;
std::fs::rename(&temporary, path).map_err(|error| format!("Failed to write {}: {error}", path.display()))
}
pub fn read_log(path: &Path) -> String {
std::fs::read_to_string(path).unwrap_or_default()
}
/// A process started detached from this one, which keeps running after this one exits.
pub struct DetachedProcess {
pub id: u32,
#[cfg(windows)]
handle: std::os::windows::io::OwnedHandle,
#[cfg(unix)]
child: std::process::Child,
}
impl DetachedProcess {
#[cfg(windows)]
pub fn is_running(&mut self) -> bool {
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Foundation::WAIT_TIMEOUT;
use windows_sys::Win32::System::Threading::WaitForSingleObject;
// SAFETY: The handle is owned by this struct, so it stays open for the call
unsafe { WaitForSingleObject(self.handle.as_raw_handle(), 0) == WAIT_TIMEOUT }
}
#[cfg(unix)]
pub fn is_running(&mut self) -> bool {
matches!(self.child.try_wait(), Ok(None))
}
}
// Runs a program detached from this process, with its output written to a fresh log file
pub fn spawn_detached(program: &Path, arguments: &[String], working_directory: &Path, log_path: &Path) -> Result<DetachedProcess, String> {
paths::create_session_directory()?;
let log = File::create(log_path).map_err(|error| format!("Failed to create {}: {error}", log_path.display()))?;
spawn_with_log(program, arguments, working_directory, log).map_err(|error| format!("Failed to start {}: {error}", program.display()))
}
// In a process group of its own, so Ctrl+C in the terminal does not reach it
#[cfg(unix)]
fn spawn_with_log(program: &Path, arguments: &[String], working_directory: &Path, log: File) -> std::io::Result<DetachedProcess> {
use std::os::unix::process::CommandExt;
let child = Command::new(program)
.args(arguments)
.current_dir(working_directory)
.stdin(Stdio::null())
.stdout(log.try_clone()?)
.stderr(log)
.process_group(0)
.spawn()?;
Ok(DetachedProcess { id: child.id(), child })
}
// Passes only the handles it needs, since Windows otherwise hands over stray copies of the terminal's output that would keep a caller reading it waiting.
// It also gets a hidden console that its children share instead of opening windows, and a process group out of reach of Ctrl+C in the terminal.
#[cfg(windows)]
fn spawn_with_log(program: &Path, arguments: &[String], working_directory: &Path, log: File) -> std::io::Result<DetachedProcess> {
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE_FLAG_INHERIT, SetHandleInformation};
use windows_sys::Win32::System::Threading::{
CREATE_NEW_PROCESS_GROUP, CREATE_NO_WINDOW, CreateProcessW, DeleteProcThreadAttributeList, EXTENDED_STARTUPINFO_PRESENT, InitializeProcThreadAttributeList, LPPROC_THREAD_ATTRIBUTE_LIST,
PROC_THREAD_ATTRIBUTE_HANDLE_LIST, PROCESS_INFORMATION, STARTF_USESTDHANDLES, STARTUPINFOEXW, STARTUPINFOW, UpdateProcThreadAttribute,
};
let input = File::open("NUL")?;
let handles = [input.as_raw_handle(), log.as_raw_handle()];
let mut command_line = windows_command_line(program, arguments);
let directory = working_directory.as_os_str().encode_wide().chain([0]).collect::<Vec<u16>>();
// SAFETY: Every pointer passed points into a local that outlives the call, and the attribute list is deleted before its buffer is freed
unsafe {
for handle in handles {
if SetHandleInformation(handle, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT) == 0 {
return Err(std::io::Error::last_os_error());
}
}
// The first call only reports the size the list needs, which is allocated as pointer-sized words to keep it aligned
let mut list_size = 0;
InitializeProcThreadAttributeList(std::ptr::null_mut(), 1, 0, &mut list_size);
let mut list_buffer = vec![0_usize; list_size.div_ceil(size_of::<usize>())];
let list = list_buffer.as_mut_ptr() as LPPROC_THREAD_ATTRIBUTE_LIST;
if InitializeProcThreadAttributeList(list, 1, 0, &mut list_size) == 0 {
return Err(std::io::Error::last_os_error());
}
let attribute = PROC_THREAD_ATTRIBUTE_HANDLE_LIST as usize;
let created = if UpdateProcThreadAttribute(list, 0, attribute, handles.as_ptr().cast(), size_of_val(&handles), std::ptr::null_mut(), std::ptr::null()) == 0 {
Err(std::io::Error::last_os_error())
} else {
let mut startup_information = STARTUPINFOEXW::default();
startup_information.StartupInfo.cb = size_of::<STARTUPINFOEXW>() as u32;
startup_information.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
startup_information.StartupInfo.hStdInput = handles[0];
startup_information.StartupInfo.hStdOutput = handles[1];
startup_information.StartupInfo.hStdError = handles[1];
startup_information.lpAttributeList = list;
let mut process_information = PROCESS_INFORMATION::default();
let flags = EXTENDED_STARTUPINFO_PRESENT | CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW;
// The extended structure is read whole, so the pointer covers all of it
let startup = (&raw const startup_information).cast::<STARTUPINFOW>();
let (application, environment, security) = (std::ptr::null(), std::ptr::null(), std::ptr::null());
if CreateProcessW(
application,
command_line.as_mut_ptr(),
security,
security,
1,
flags,
environment,
directory.as_ptr(),
startup,
&mut process_information,
) == 0
{
Err(std::io::Error::last_os_error())
} else {
CloseHandle(process_information.hThread);
Ok(DetachedProcess {
id: process_information.dwProcessId,
handle: OwnedHandle::from_raw_handle(process_information.hProcess),
})
}
};
DeleteProcThreadAttributeList(list);
created
}
}
// Quotes each argument the way the Microsoft C runtime splits a command line, which Rust and Node.js programs both follow
#[cfg(windows)]
fn windows_command_line(program: &Path, arguments: &[String]) -> Vec<u16> {
use std::os::windows::ffi::OsStrExt;
let mut line = Vec::new();
let quote = u16::from(b'"');
let backslash = u16::from(b'\\');
for (index, argument) in std::iter::once(program.as_os_str()).chain(arguments.iter().map(std::ffi::OsStr::new)).enumerate() {
if index > 0 {
line.push(u16::from(b' '));
}
line.push(quote);
// Backslashes are literal unless they come before a quote, where each must be doubled, including before the closing quote
let mut backslashes = 0;
for character in argument.encode_wide() {
if character == backslash {
backslashes += 1;
continue;
}
let escaped_backslashes = if character == quote { backslashes * 2 + 1 } else { backslashes };
line.extend(std::iter::repeat_n(backslash, escaped_backslashes));
line.push(character);
backslashes = 0;
}
line.extend(std::iter::repeat_n(backslash, backslashes * 2));
line.push(quote);
}
line.push(0);
line
}
pub fn terminate(process_id: u32) {
let process_id = process_id.to_string();
// On Windows only `taskkill` also ends the process's children, which would otherwise keep holding the port or the browser
let ended = if cfg!(windows) {
Command::new("taskkill").args(["/pid", &process_id, "/T", "/F"]).output()
} else {
Command::new("kill").arg(&process_id).output()
};
if let Err(error) = ended {
eprintln!("Failed to end process {process_id}: {error}");
}
}
// Whether anything answers HTTP requests on a local port
fn port_answers(port: u16) -> bool {
let address = SocketAddr::from(([127, 0, 0, 1], port));
let Ok(mut stream) = TcpStream::connect_timeout(&address, PROBE_TIMEOUT) else { return false };
let request = format!("GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n");
if stream.set_read_timeout(Some(PROBE_TIMEOUT)).is_err() || stream.write_all(request.as_bytes()).is_err() {
return false;
}
let mut first_byte = [0];
matches!(stream.read(&mut first_byte), Ok(1))
}
// The ID of the process listening on a local port, if the operating system's own tools can tell
fn listening_process_id(port: u16) -> Option<u32> {
let listing = if cfg!(windows) {
Command::new("netstat").args(["-ano", "-p", "TCP"]).output()
} else {
Command::new("lsof").args(["-nP", &format!("-iTCP:{port}"), "-sTCP:LISTEN", "-t"]).output()
}
.ok()?;
let listing = String::from_utf8_lossy(&listing.stdout);
// On Windows the process ID ends the port's listening line, found by its lack of a foreign address since the state's name is translated
let line = if cfg!(windows) {
let local_address_suffix = format!(":{port}");
listing.lines().find(|line| {
let columns = line.split_whitespace().collect::<Vec<_>>();
columns.get(1).is_some_and(|local_address| local_address.ends_with(&local_address_suffix)) && columns.get(2) == Some(&"0.0.0.0:0")
})?
} else {
listing.lines().next()?
};
line.split_whitespace().last()?.parse().ok().filter(|process_id| *process_id > 0)
}
// The real Node.js program rather than a shim that runs it as a child, so the process started is the one that listens on the port
fn node_executable() -> Result<PathBuf, String> {
let output = Command::new("node")
.args(["--print", "process.execPath"])
.output()
.map_err(|error| format!("Failed to run Node.js: {error}"))?;
let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
if !output.status.success() || path.is_empty() {
return Err("Node.js did not say where it is installed".to_string());
}
Ok(PathBuf::from(path))
}
/// The dev server that `serve` started, if its port still answers and is still held by the process that was recorded.
pub fn dev_server_record() -> Option<DevServerRecord> {
let record: DevServerRecord = read_record(&paths::dev_server_file())?;
(port_answers(record.port) && listening_process_id(record.port) == Some(record.process_id)).then_some(record)
}
pub fn start_dev_server(port: u16) -> Result<DevServerRecord, String> {
if dev_server_record().is_some() {
return Err("The dev server is already running, so stop it first".to_string());
}
if port_answers(port) {
return Err(format!("Something already answers on port {port}, so use it without `serve` or choose another --port"));
}
let vite = paths::frontend_directory().join("node_modules").join("vite").join("bin").join("vite.js");
if !vite.exists() {
return Err("The frontend's packages are not installed, which `cargo run` does on its first launch".to_string());
}
let arguments = [
vite.display().to_string(),
"--port".into(),
port.to_string(),
"--strictPort".into(),
"--host".into(),
"127.0.0.1".into(),
];
let mut process = spawn_detached(&node_executable()?, &arguments, &paths::frontend_directory(), &paths::dev_server_log_file())?;
let record = DevServerRecord { port, process_id: process.id };
let deadline = Instant::now() + DEV_SERVER_START_TIMEOUT;
while Instant::now() < deadline {
// Vite exits when it cannot take the port, so an answer only counts while the process started here is still running
let running = process.is_running();
if running && port_answers(port) {
if let Err(error) = write_record(&paths::dev_server_file(), &record) {
terminate(record.process_id);
return Err(error);
}
return Ok(record);
}
if !running {
return Err(format!("The dev server failed to start:\n{}", read_log(&paths::dev_server_log_file())));
}
std::thread::sleep(POLL_INTERVAL);
}
terminate(record.process_id);
Err(format!("The dev server did not respond in time:\n{}", read_log(&paths::dev_server_log_file())))
}
// A record that is no longer live may name a process ID since reused by another program, so it is only removed
pub fn stop_dev_server() {
if let Some(record) = dev_server_record() {
terminate(record.process_id);
}
let _ = std::fs::remove_file(paths::dev_server_file());
}
#[cfg(all(test, windows))]
mod tests {
use super::*;
#[test]
fn command_line_arguments_are_quoted() {
let arguments = ["plain", "with space", "quote\"inside", "backslash\\\"quote", "trailing\\", ""].map(String::from);
let line = windows_command_line(Path::new(r"C:\Program Files\host.exe"), &arguments);
let expected = r#""C:\Program Files\host.exe" "plain" "with space" "quote\"inside" "backslash\\\"quote" "trailing\\" """#;
assert_eq!(String::from_utf16(&line[..line.len() - 1]).unwrap(), expected);
assert_eq!(line.last(), Some(&0));
}
}
+530
View File
@@ -0,0 +1,530 @@
use glam::{DVec2, UVec2};
use graphite_editor_control_protocol::{Command, CommandResult, Filmstrip, Located, MouseButton, Rectangle, SessionStatus, Space};
use std::num::NonZeroU32;
use std::path::Path;
use std::sync::Arc;
use std::time::{Duration, Instant};
use crate::browser::Browser;
use crate::contact_sheet::{Frame, write_contact_sheet};
use crate::paths::output_path;
const VIEWPORT_SELECTOR: &str = "[data-viewport]";
const EDITOR_READY_SELECTOR: &str = "[data-workspace]";
const EDITOR_READY_TIMEOUT: Duration = Duration::from_secs(120);
const POINTER_STEP_DISTANCE: f64 = 8.;
const WHEEL_NOTCH: f64 = 100.;
// Bounds on how many frames a move or scroll takes, however far it goes
const MAX_POINTER_STEPS: u32 = 1000;
const MAX_WHEEL_NOTCHES: f64 = 100.;
const FRAME_TIMEOUT: Duration = Duration::from_secs(1);
const IDLE_TIMEOUT: Duration = Duration::from_secs(5);
const IDLE_POLL_INTERVAL: Duration = Duration::from_millis(50);
const IDLE_CAPTURE_COUNT: u32 = 3;
const IDLE_MINIMUM_SPAN: Duration = Duration::from_millis(200);
const DEFAULT_FILMSTRIP_FRAMES: u32 = 8;
const LOCATED_TEXT_LENGTH: usize = 80;
#[derive(Debug, Clone)]
pub struct SessionOptions {
pub url: String,
pub size: UVec2,
pub scale: f64,
pub headed: bool,
}
struct HeldKey {
/// The key as `held_key_name` gives it.
name: String,
/// The key as it was pressed, which must also release it.
pressed_as: String,
}
// A modifier counts as one held key whichever side is named, since the page sees the same modifier state either way
fn held_key_name(key: &str) -> &str {
for modifier in ["Shift", "Control", "Alt", "Meta"] {
if let Some(side) = key.strip_prefix(modifier)
&& (side == "Left" || side == "Right")
{
return modifier;
}
}
key
}
// Splits a combination such as `Control+KeyZ` into its keys, where a final `+` is the plus key itself rather than a separator
fn split_key_combination(combination: &str) -> Vec<&str> {
let mut keys = Vec::new();
let mut start = 0;
for (index, character) in combination.char_indices() {
if character == '+' && index + 1 < combination.len() {
keys.push(&combination[start..index]);
start = index + 1;
}
}
keys.push(&combination[start..]);
keys
}
// Trims an area to the page as the screenshot will, so the crosshair is measured from the corner actually captured
fn clamp_to_page(area: Rectangle, page_size: UVec2) -> Result<Rectangle, String> {
let page_size = page_size.as_dvec2();
let top_left = DVec2::new(area.x, area.y).clamp(DVec2::ZERO, page_size);
let bottom_right = DVec2::new(area.x + area.width, area.y + area.height).clamp(DVec2::ZERO, page_size);
if bottom_right.x <= top_left.x || bottom_right.y <= top_left.y {
return Err("The area to capture lies outside the page".to_string());
}
let size = bottom_right - top_left;
Ok(Rectangle {
x: top_left.x,
y: top_left.y,
width: size.x,
height: size.y,
})
}
/// One browser page holding the editor, driven only through the input a person could give it.
pub struct EditorSession {
browser: Arc<Browser>,
url: String,
scale: f64,
size: UVec2,
pointer: DVec2,
held_keys: Vec<HeldKey>,
held_buttons: Vec<MouseButton>,
crashed: bool,
}
impl EditorSession {
pub fn launch(browser: Arc<Browser>, options: SessionOptions) -> Result<Self, String> {
browser.launch(&options.url, options.size, options.scale, options.headed, EDITOR_READY_SELECTOR, EDITOR_READY_TIMEOUT)?;
let session = Self {
browser,
url: options.url,
scale: options.scale,
size: options.size,
pointer: DVec2::ZERO,
held_keys: Vec::new(),
held_buttons: Vec::new(),
crashed: false,
};
session.wait_idle(IDLE_TIMEOUT)?;
Ok(session)
}
pub fn perform(&mut self, command: &Command) -> CommandResult {
self.dispatch(command).unwrap_or_else(|error| CommandResult::failed(command, error))
}
fn dispatch(&mut self, command: &Command) -> Result<CommandResult, String> {
let mut result = CommandResult::succeeded(command);
match command {
Command::Move { to, space, steps } => {
let steps = explicit_step_count(*steps)?;
let to = self.to_page(*to, *space)?;
self.move_pointer(to, steps, None)?;
}
Command::Down { button } => self.press_button(button.unwrap_or_default(), 1)?,
Command::Up { button } => self.release_button(button.unwrap_or_default(), 1)?,
Command::Click { at, space, button, count, keys } => {
let button = button.unwrap_or_default();
self.require_button_not_held(button)?;
let at = self.to_page(*at, *space)?;
self.move_pointer(at, None, None)?;
let mut pressed_keys = Vec::new();
let clicked = self.hold_keys(keys.as_deref().unwrap_or_default(), &mut pressed_keys).and_then(|()| {
for click_count in 1..=count.map_or(1, |count| count.get()) {
self.press_button(button, click_count)?;
self.release_button(button, click_count)?;
}
Ok(())
});
let released = self.release_pressed(button, &pressed_keys);
clicked.and(released)?;
}
Command::Drag {
from,
to,
space,
button,
keys,
steps,
release,
filmstrip,
} => {
let button = button.unwrap_or_default();
self.require_button_not_held(button)?;
let steps = explicit_step_count(*steps)?;
let from = self.to_page(*from, *space)?;
let to = self.to_page(*to, *space)?;
self.move_pointer(from, None, None)?;
let mut pressed_keys = Vec::new();
let dragged = self
.hold_keys(keys.as_deref().unwrap_or_default(), &mut pressed_keys)
.and_then(|()| self.press_button(button, 1))
.and_then(|()| self.move_pointer(to, steps, filmstrip.as_ref()));
// Whatever the drag pressed is released at the end or on failure, but stays held with `release: false` once the drag succeeds
let released = if dragged.is_err() || *release != Some(false) {
self.release_pressed(button, &pressed_keys)
} else {
Ok(())
};
let frames = dragged?;
released?;
if let Some(filmstrip) = filmstrip {
let path = output_path(&filmstrip.path);
write_contact_sheet(&path, &frames, self.scale)?;
result.path = Some(path);
result.frames = Some(frames.iter().map(|frame| frame.page_pointer).collect());
}
}
Command::KeyDown { key } => self.hold_keys(std::slice::from_ref(key), &mut Vec::new())?,
Command::KeyUp { key } => self.release_keys(std::slice::from_ref(key))?,
Command::Press { key } => {
let keys = split_key_combination(key);
let Some((final_key, modifiers)) = keys.split_last() else { return Ok(result) };
let modifiers = modifiers.iter().map(|modifier| modifier.to_string()).collect::<Vec<_>>();
let mut pressed_keys = Vec::new();
let pressed = self.hold_keys(&modifiers, &mut pressed_keys).and_then(|()| {
self.browser.key_down(final_key)?;
self.browser.key_up(final_key)?;
// Tapping a key leaves it up, even one that was held before
let name = held_key_name(final_key);
self.held_keys.retain(|held| held.name != name);
Ok(())
});
let released = self.release_keys(&pressed_keys);
pressed.and(released)?;
}
Command::Type { text } => self.browser.type_text(text)?,
Command::Scroll { delta, at, space } => {
if let Some(at) = at {
let at = self.to_page(*at, *space)?;
self.move_pointer(at, None, None)?;
}
// A wheel turns in notches, so a large delta is spread over several, one per frame
let notches = (delta.abs().max_element() / WHEEL_NOTCH).ceil().clamp(1., MAX_WHEEL_NOTCHES);
for _ in 0..notches as u32 {
self.browser.wheel(*delta / notches)?;
self.next_frame()?;
}
}
Command::Wait { milliseconds } => std::thread::sleep(Duration::from_millis(*milliseconds)),
Command::WaitIdle { timeout } => {
let timeout = timeout.map_or(IDLE_TIMEOUT, Duration::from_millis);
result.stable = Some(self.wait_idle(timeout)?);
}
Command::Screenshot { path, cursor, region, clip } => {
let path = output_path(path);
let frame = self.capture_frame(region.as_deref(), *clip)?;
if *cursor == Some(true) {
write_contact_sheet(&path, &[frame], self.scale)?;
} else {
write_file(&path, &frame.image)?;
}
result.path = Some(path);
}
Command::Locate { data, text } => result.located = Some(self.locate(data.as_deref(), text.as_deref())?),
Command::Resize { size } => {
if size.min_element() == 0 {
return Err("The page's width and height must be at least one pixel".to_string());
}
self.browser.resize(*size)?;
self.size = *size;
}
Command::Status {} => result.status = Some(self.status()?),
}
Ok(result)
}
fn status(&mut self) -> Result<SessionStatus, String> {
let events = self.browser.take_events()?;
self.crashed |= events.crashed;
// A crashed page answers no queries
let viewport = if self.crashed { None } else { self.region_box(Some("viewport"))? };
Ok(SessionStatus {
url: self.url.clone(),
size: self.size,
pointer: self.pointer,
viewport,
held_keys: self.held_keys.iter().map(|held| held.pressed_as.clone()).collect(),
held_buttons: self.held_buttons.clone(),
crashed: self.crashed,
console_errors: events.console_errors,
})
}
fn to_page(&self, point: DVec2, space: Option<Space>) -> Result<DVec2, String> {
if space != Some(Space::Viewport) {
return Ok(point);
}
let viewport = self.region_box(Some("viewport"))?.ok_or("No document viewport is on screen to measure the point from")?;
Ok(point + DVec2::new(viewport.x, viewport.y))
}
fn region_box(&self, region: Option<&str>) -> Result<Option<Rectangle>, String> {
let Some(region) = region.filter(|region| *region != "page") else { return Ok(None) };
let selector = if region == "viewport" { VIEWPORT_SELECTOR } else { region };
let bounds = self.browser.bounding_box(selector)?;
if bounds.is_none() && region != "viewport" {
return Err(format!("No element matches the region \"{region}\""));
}
Ok(bounds)
}
// Captures an area of the page along with where the pointer sits within it
fn capture_frame(&self, region: Option<&str>, clip: Option<Rectangle>) -> Result<Frame, String> {
let area = match clip {
Some(clip) => Some(clip),
None if region == Some("viewport") => Some(self.region_box(region)?.ok_or("No document viewport is on screen to capture")?),
None => self.region_box(region)?,
};
let clip = area.map(|area| clamp_to_page(area, self.size)).transpose()?;
let origin = clip.map_or(DVec2::ZERO, |clip| DVec2::new(clip.x, clip.y));
Ok(Frame {
image: self.browser.screenshot(clip)?,
pointer: self.pointer - origin,
page_pointer: self.pointer,
})
}
fn next_frame(&self) -> Result<(), String> {
self.browser.next_frame(FRAME_TIMEOUT)
}
// A real pointer only lands on whole device pixels
fn snap_to_device_pixels(&self, point: DVec2) -> DVec2 {
(point * self.scale).round() / self.scale
}
// Moves one small step per rendered frame, as a real pointer does, optionally capturing frames spread evenly along the path
fn move_pointer(&mut self, to: DVec2, steps: Option<u32>, filmstrip: Option<&Filmstrip>) -> Result<Vec<Frame>, String> {
let from = self.pointer;
let step_count = steps.unwrap_or_else(|| ((from.distance(to) / POINTER_STEP_DISTANCE).ceil() as u32).clamp(1, MAX_POINTER_STEPS));
let frame_count = filmstrip.map_or(0, |filmstrip| filmstrip.frames.map_or(DEFAULT_FILMSTRIP_FRAMES, |frames| frames.get()).min(step_count));
let mut frames = Vec::new();
for step in 1..=step_count {
let next = self.snap_to_device_pixels(from.lerp(to, step as f64 / step_count as f64));
self.browser.mouse_move(next)?;
self.pointer = next;
self.next_frame()?;
let Some(filmstrip) = filmstrip else { continue };
let frames_due = (step as u64 * frame_count as u64 / step_count as u64) as usize;
if frames_due <= frames.len() {
continue;
}
self.wait_idle(IDLE_TIMEOUT)?;
frames.push(self.capture_frame(filmstrip.region.as_deref(), filmstrip.clip)?);
}
Ok(frames)
}
fn require_button_not_held(&self, button: MouseButton) -> Result<(), String> {
if self.held_buttons.contains(&button) {
return Err(format!("The {} button is already held, so release it with `up` first", button_name(button)));
}
Ok(())
}
fn press_button(&mut self, button: MouseButton, click_count: u32) -> Result<(), String> {
self.browser.mouse_down(button, click_count)?;
if !self.held_buttons.contains(&button) {
self.held_buttons.push(button);
}
self.next_frame()
}
fn release_button(&mut self, button: MouseButton, click_count: u32) -> Result<(), String> {
self.browser.mouse_up(button, click_count)?;
self.held_buttons.retain(|held| *held != button);
self.next_frame()
}
// Releases the button if it is still held, then the keys, attempting both even if the first fails
fn release_pressed(&mut self, button: MouseButton, pressed_keys: &[String]) -> Result<(), String> {
let button_released = if self.held_buttons.contains(&button) { self.release_button(button, 1) } else { Ok(()) };
let keys_released = self.release_keys(pressed_keys);
button_released.and(keys_released)
}
// Holds each key not already held, adding each one it presses to `pressed_keys` right away so a caller can release exactly those
fn hold_keys(&mut self, keys: &[String], pressed_keys: &mut Vec<String>) -> Result<(), String> {
let mut pressed_any = false;
for key in keys {
let name = held_key_name(key);
if self.held_keys.iter().any(|held| held.name == name) {
continue;
}
self.browser.key_down(key)?;
self.held_keys.push(HeldKey {
name: name.to_string(),
pressed_as: key.clone(),
});
pressed_keys.push(key.clone());
pressed_any = true;
}
if pressed_any { self.next_frame() } else { Ok(()) }
}
fn release_keys(&mut self, keys: &[String]) -> Result<(), String> {
for key in keys.iter().rev() {
let name = held_key_name(key);
let pressed_as = self.held_keys.iter().find(|held| held.name == name).map_or(key.as_str(), |held| held.pressed_as.as_str());
self.browser.key_up(pressed_as)?;
self.held_keys.retain(|held| held.name != name);
}
if keys.is_empty() { Ok(()) } else { self.next_frame() }
}
// Waits until three consecutive captures of the page are identical and span at least 200 milliseconds, or returns false on timeout
fn wait_idle(&self, timeout: Duration) -> Result<bool, String> {
let deadline = Instant::now() + timeout;
let mut previous: Option<Vec<u8>> = None;
let mut identical_captures = 0;
let mut identical_since = Instant::now();
while Instant::now() < deadline {
self.next_frame()?;
let current = self.browser.screenshot(None)?;
if previous.as_ref() == Some(&current) {
identical_captures += 1;
} else {
previous = Some(current);
identical_captures = 1;
identical_since = Instant::now();
}
if identical_captures >= IDLE_CAPTURE_COUNT && identical_since.elapsed() >= IDLE_MINIMUM_SPAN {
return Ok(true);
}
std::thread::sleep(IDLE_POLL_INTERVAL);
}
Ok(false)
}
fn locate(&self, data: Option<&str>, text: Option<&str>) -> Result<Vec<Located>, String> {
if data.is_none() && text.is_none() {
return Err("Locating needs a `data` attribute name or some visible `text`".to_string());
}
let located = self.browser.locate(data, text)?.into_iter().map(|element| {
let bounds = element.bounds;
let text = element.text.split_whitespace().collect::<Vec<_>>().join(" ").chars().take(LOCATED_TEXT_LENGTH).collect();
let center = DVec2::new(bounds.x + bounds.width / 2., bounds.y + bounds.height / 2.);
Located { bounds, center, text }
});
Ok(located.collect())
}
}
fn button_name(button: MouseButton) -> &'static str {
match button {
MouseButton::Left => "left",
MouseButton::Middle => "middle",
MouseButton::Right => "right",
}
}
// Refused rather than lowered, since taking fewer steps than asked would change the motion the caller described
fn explicit_step_count(steps: Option<NonZeroU32>) -> Result<Option<u32>, String> {
match steps.map(NonZeroU32::get) {
Some(steps) if steps > MAX_POINTER_STEPS => Err(format!("A move takes at most {MAX_POINTER_STEPS} steps")),
steps => Ok(steps),
}
}
pub fn write_file(path: &Path, contents: &[u8]) -> Result<(), String> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|error| format!("Failed to create the folder {}: {error}", parent.display()))?;
}
std::fs::write(path, contents).map_err(|error| format!("Failed to write {}: {error}", path.display()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn key_combinations_split_on_plus() {
assert_eq!(split_key_combination("Control+KeyZ"), ["Control", "KeyZ"]);
assert_eq!(split_key_combination("Control+Shift+KeyZ"), ["Control", "Shift", "KeyZ"]);
assert_eq!(split_key_combination("Control++"), ["Control", "+"]);
assert_eq!(split_key_combination("+"), ["+"]);
assert_eq!(split_key_combination("KeyP"), ["KeyP"]);
}
#[test]
fn sided_modifiers_are_held_as_one() {
assert_eq!(held_key_name("ShiftLeft"), "Shift");
assert_eq!(held_key_name("ControlRight"), "Control");
assert_eq!(held_key_name("Shift"), "Shift");
assert_eq!(held_key_name("KeyS"), "KeyS");
assert_eq!(held_key_name("AltGraph"), "AltGraph");
}
#[test]
fn captures_are_trimmed_to_the_page() {
let page = UVec2::new(100, 50);
let trimmed = clamp_to_page(
Rectangle {
x: -10.,
y: 40.,
width: 30.,
height: 30.,
},
page,
)
.unwrap();
assert_eq!(
trimmed,
Rectangle {
x: 0.,
y: 40.,
width: 20.,
height: 10.
}
);
let outside = Rectangle {
x: 200.,
y: 0.,
width: 10.,
height: 10.,
};
assert!(clamp_to_page(outside, page).is_err());
}
}
+46
View File
@@ -0,0 +1,46 @@
use interprocess::local_socket::{GenericFilePath, GenericNamespaced, Name, prelude::*};
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::io::{BufRead, Read, Write};
// Room for any batch of commands or results, while a connection that never ends its line cannot make the reader buffer without end
const MAX_MESSAGE_LENGTH: u64 = 16 * 1024 * 1024;
/// The name of the local socket a session's host listens on, which is unique to the session.
pub fn name(session_id: &str) -> Result<Name<'static>, String> {
let file_name = format!("graphite-web-editor-driver-{session_id}.sock");
let name = if GenericNamespaced::is_supported() {
file_name.to_ns_name::<GenericNamespaced>()
} else {
std::env::temp_dir().join(file_name).to_fs_name::<GenericFilePath>()
};
name.map_err(|error| format!("Failed to name the session's socket: {error}"))
}
/// Sends a message as one line of JSON.
pub fn write_message(writer: &mut impl Write, message: &impl Serialize) -> Result<(), String> {
let mut line = serde_json::to_string(message).map_err(|error| format!("Failed to encode a message: {error}"))?;
line.push('\n');
writer
.write_all(line.as_bytes())
.and_then(|()| writer.flush())
.map_err(|error| format!("Failed to send a message: {error}"))
}
/// Receives a message sent as one line of JSON, or `None` once the other end has closed the connection.
pub fn read_message<T: DeserializeOwned>(reader: &mut impl BufRead) -> Result<Option<T>, String> {
let mut line = String::new();
let length = reader
.by_ref()
.take(MAX_MESSAGE_LENGTH)
.read_line(&mut line)
.map_err(|error| format!("Failed to receive a message: {error}"))?;
if length == 0 {
return Ok(None);
}
if !line.ends_with('\n') && length as u64 == MAX_MESSAGE_LENGTH {
return Err("Received a message longer than 16 MiB".to_string());
}
serde_json::from_str(&line).map(Some).map_err(|error| format!("Received a message that could not be read: {error}"))
}