1use std::collections::BTreeMap;
38use std::sync::Mutex;
39
40use egui_pop_api::services::ServiceToken;
41use egui_pop_api::steps::{Outcome, StepSpec};
42use egui_pop_api::{AppHandle, Call, Ctx, CtxError};
43use egui_pop_model::commands::CommandSpec;
44use egui_pop_model::ids::{CommandId, StepId};
45use egui_pop_viewport::change::{Cause, Verdict};
46use egui_pop_viewport::graph::{
47 Edge, Edit, ExportOptions, GraphEditor, GraphEvent, GraphExport, GraphOutput, Level, Request,
48 WireStyle,
49};
50use serde_json::{Value as Json, json};
51
52pub const STEP_GRAPH_CONNECT: StepId = StepId::from_static("graph.connect");
53pub const STEP_GRAPH_DISCONNECT: StepId = StepId::from_static("graph.disconnect");
54pub const STEP_GRAPH_MOVE: StepId = StepId::from_static("graph.move");
55pub const STEP_GRAPH_DELETE: StepId = StepId::from_static("graph.delete");
56pub const STEP_GRAPH_ADD: StepId = StepId::from_static("graph.add");
57
58pub const EVENT_GRAPH_SELECTION: &str = "graph.selection_changed";
60pub const EVENT_GRAPH_WIRE_SELECTION: &str = "graph.wire_selection_changed";
61pub const EVENT_GRAPH_LEVEL: &str = "graph.level_changed";
62pub const EVENT_GRAPH_REFUSED: &str = "graph.refused";
63
64pub const CMD_GRAPH_READ: CommandId = CommandId::from_static("graph.read");
65pub const CMD_GRAPH_EDIT: CommandId = CommandId::from_static("graph.edit");
66pub const CMD_GRAPH_SELECT: CommandId = CommandId::from_static("graph.select");
67pub const CMD_GRAPH_VIEW: CommandId = CommandId::from_static("graph.view");
68pub const CMD_GRAPH_EXPORT: CommandId = CommandId::from_static("graph.export");
69
70#[derive(Debug, Default)]
73pub struct Graphs {
74 inner: Mutex<BTreeMap<String, Entry>>,
75}
76
77#[derive(Debug, Default)]
78struct Entry {
79 snapshot: Json,
80 queue: Vec<Request>,
81 export: Option<GraphExport>,
83}
84
85pub const GRAPHS: ServiceToken<Graphs> = ServiceToken::new("egui_pop.graphs");
87
88impl Graphs {
89 fn lock(&self) -> std::sync::MutexGuard<'_, BTreeMap<String, Entry>> {
90 self.inner.lock().unwrap_or_else(|e| e.into_inner())
91 }
92
93 pub fn names(&self) -> Vec<String> {
95 self.lock().keys().cloned().collect()
96 }
97
98 pub fn snapshot(&self, name: &str) -> Option<Json> {
100 self.lock().get(name).map(|e| e.snapshot.clone())
101 }
102
103 pub fn request(&self, name: &str, request: Request) {
105 self.lock()
106 .entry(name.to_string())
107 .or_default()
108 .queue
109 .push(request);
110 }
111
112 fn take(&self, name: &str) -> Vec<Request> {
113 self.lock()
114 .get_mut(name)
115 .map(|e| std::mem::take(&mut e.queue))
116 .unwrap_or_default()
117 }
118
119 pub fn export(&self, name: &str) -> Option<GraphExport> {
121 self.lock().get(name).and_then(|e| e.export.clone())
122 }
123
124 fn publish(&self, name: &str, snapshot: Json, export: Option<GraphExport>) {
125 let mut all = self.lock();
126 let e = all.entry(name.to_string()).or_default();
127 e.snapshot = snapshot;
128 if export.is_some() {
129 e.export = export;
130 }
131 }
132}
133
134pub fn step_of(edit: &Edit) -> Option<StepId> {
136 match edit {
137 Edit::Connect { .. } => Some(STEP_GRAPH_CONNECT),
138 Edit::Disconnect { .. } => Some(STEP_GRAPH_DISCONNECT),
139 Edit::Move { .. } => Some(STEP_GRAPH_MOVE),
140 Edit::Delete { .. } => Some(STEP_GRAPH_DELETE),
141 Edit::Add { .. } => Some(STEP_GRAPH_ADD),
142 Edit::Param { .. } => None,
143 _ => None,
144 }
145}
146
147pub fn graph<'a>(
150 app: &'a AppHandle,
151 name: &'a str,
152) -> impl FnMut(&Edit, Cause) -> Verdict<Edit> + 'a {
153 move |edit: &Edit, cause: Cause| {
154 let Some(step) = step_of(edit) else {
155 return Verdict::Allow;
156 };
157 let mut args = edit.to_json();
158 args["graph"] = json!(name);
159 args["cause"] = json!(cause.name());
160 match app.step(&step, args, |_, args| Ok(args.clone())) {
161 Outcome::Done(Ok(v)) => match Edit::from_json(edit.kind(), &v) {
162 Some(e) if e == *edit => Verdict::Allow,
163 Some(e) => Verdict::Redirect(e),
164 None => Verdict::Veto,
165 },
166 Outcome::Done(Err(_)) | Outcome::Vetoed { .. } => Verdict::Veto,
167 }
168 }
169}
170
171pub fn show_graph(
176 app: &AppHandle,
177 name: &str,
178 editor: GraphEditor<'_>,
179 ui: &mut egui::Ui,
180) -> GraphOutput {
181 let graphs = app.service(&GRAPHS);
182 let queued = graphs.as_ref().map(|g| g.take(name)).unwrap_or_default();
183 let out = editor
184 .requests(queued)
185 .on_edit(graph(app, name))
186 .describe(graphs.is_some())
187 .keep_export(graphs.is_some())
188 .show(ui);
189 for e in &out.events {
190 let (event, data) = match e {
191 GraphEvent::Selection(nodes) => (
192 EVENT_GRAPH_SELECTION,
193 json!({ "graph": name, "nodes": nodes }),
194 ),
195 GraphEvent::WireSelection(edges) => (
196 EVENT_GRAPH_WIRE_SELECTION,
197 json!({
198 "graph": name,
199 "edges": edges.iter().map(Edge::to_json).collect::<Vec<_>>(),
200 }),
201 ),
202 GraphEvent::Level(level) => (
203 EVENT_GRAPH_LEVEL,
204 json!({ "graph": name, "level": level.name() }),
205 ),
206 GraphEvent::Refused { from, to, reason } => (
207 EVENT_GRAPH_REFUSED,
208 json!({ "graph": name, "from": from.to_json(), "to": to.to_json(), "reason": reason }),
209 ),
210 _ => continue,
211 };
212 app.publish("graph", None, event, data);
213 }
214 if let (Some(g), Some(s)) = (graphs, out.snapshot.as_ref()) {
215 g.publish(name, s.clone(), out.export.clone());
216 }
217 out
218}
219
220pub fn specs() -> Vec<StepSpec> {
222 let p = |n: &str, q: &str| json!({ "node": n, "port": q });
223 vec![
224 StepSpec::new(
225 STEP_GRAPH_CONNECT,
226 "A node editor connects an output to an input (`graph`, `from`, `to`: {node, port}, `replaces`: the wires it takes the place of, `cause`); a veto drops it, a redirect or a run-hook gives another connection.",
227 )
228 .args(json!({
229 "graph": "main",
230 "from": p("load", "image"),
231 "to": p("blur", "image"),
232 "replaces": [],
233 "cause": "drag",
234 })),
235 StepSpec::new(
236 STEP_GRAPH_DISCONNECT,
237 "A node editor removes wires (`graph`, `edges`: [{from, to}], `cause`); a veto keeps them.",
238 )
239 .args(json!({
240 "graph": "main",
241 "edges": [{ "from": p("load", "image"), "to": p("blur", "image") }],
242 "cause": "drag",
243 })),
244 StepSpec::new(
245 STEP_GRAPH_MOVE,
246 "A node editor moves nodes at the end of a drag or a key (`graph`, `moves`: [{node, from, to}], `cause`); a veto leaves them, a redirect gives other places.",
247 )
248 .args(json!({
249 "graph": "main",
250 "moves": [{ "node": "blur", "from": [200.0, 40.0], "to": [240.0, 60.0] }],
251 "cause": "drag",
252 })),
253 StepSpec::new(
254 STEP_GRAPH_DELETE,
255 "A node editor deletes nodes and the wires touching them (`graph`, `nodes`, `edges`, `cause`); a veto keeps them.",
256 )
257 .args(json!({
258 "graph": "main",
259 "nodes": ["blur"],
260 "edges": [{ "from": p("load", "image"), "to": p("blur", "image") }],
261 "cause": "key",
262 })),
263 StepSpec::new(
264 STEP_GRAPH_ADD,
265 "A node editor adds nodes, from its menu, a command or a duplicate (`graph`, `nodes`: [{kind, at, copy_of}], `cause`); a veto adds nothing, a redirect gives other nodes.",
266 )
267 .args(json!({
268 "graph": "main",
269 "nodes": [{ "kind": "blur", "at": [400.0, 80.0], "copy_of": null }],
270 "cause": "command",
271 })),
272 ]
273}
274
275fn target(call: &Call<'_>) -> Result<(std::sync::Arc<Graphs>, String), String> {
277 let graphs = call
278 .app
279 .service(&GRAPHS)
280 .ok_or("the imaging plugin is not connected")?;
281 let name = match call.args.get("graph").and_then(Json::as_str) {
282 Some(n) => n.to_string(),
283 None => {
284 let names = graphs.names();
285 match names.as_slice() {
286 [one] => one.clone(),
287 [] => return Err("no node editor has been shown".into()),
288 _ => return Err(format!("name one with `graph`: {}", names.join(", "))),
289 }
290 }
291 };
292 if graphs.snapshot(&name).is_none() {
293 return Err(format!("no node editor `{name}`"));
294 }
295 Ok((graphs, name))
296}
297
298pub(crate) fn connect(ctx: &mut Ctx<'_>) -> Result<(), CtxError> {
300 const CAT: &str = "Node graph";
301 ctx.service(&GRAPHS, Graphs::default())?;
302 ctx.command(
303 CommandSpec::new(CMD_GRAPH_READ, "Read the graph", CAT)
304 .description("The graph a node editor drew last: nodes (place, ports, group, parameters), wires, groups, the kinds it can add, the selection (`selection`: nodes, `selected_edges`: wires), the level and the part in view.")
305 .hidden()
306 .read_only()
307 .args(json!({ "graph": "main" })),
308 |call| {
309 let (graphs, name) = target(call)?;
310 let mut out = graphs.snapshot(&name).unwrap_or_default();
311 out["graph"] = json!(name);
312 Ok(out)
313 },
314 )?;
315 ctx.command(
316 CommandSpec::new(CMD_GRAPH_EDIT, "Edit the graph", CAT)
317 .description("Asks a node editor for an edit, done at its next frame as the user's (a connection type-checked, then its graph.* step): `edit` is `connect` (`from`, `to`, and `replaces`: wires whose end it moves, one edit), `disconnect` (`edges`), `move` (`moves`), `delete` (`nodes`, `edges`) or `add` (`nodes`).")
318 .hidden()
319 .args(json!({
320 "graph": "main",
321 "edit": "connect",
322 "from": { "node": "load", "port": "image" },
323 "to": { "node": "blur", "port": "image" },
324 })),
325 |call| {
326 let (graphs, name) = target(call)?;
327 let kind = call
328 .args
329 .get("edit")
330 .and_then(Json::as_str)
331 .ok_or("`edit` is missing")?;
332 if kind == "param" {
333 return Err("parameters are the application's to set".into());
334 }
335 let edit = Edit::from_json(kind, call.args)
336 .ok_or_else(|| format!("not a `{kind}` edit: {}", call.args))?;
337 graphs.request(&name, Request::Edit(edit));
338 Ok(json!({ "graph": name, "queued": kind }))
339 },
340 )?;
341 ctx.command(
342 CommandSpec::new(CMD_GRAPH_SELECT, "Select nodes and wires", CAT)
343 .description("Selects nodes (`nodes`, their ids) and wires (`edges`: [{from, to}]) of a node editor at its next frame: what is named is the selection, nodes and wires; give one of them or both.")
344 .hidden()
345 .args(json!({
346 "graph": "main",
347 "nodes": ["blur"],
348 "edges": [{
349 "from": { "node": "load", "port": "image" },
350 "to": { "node": "blur", "port": "image" },
351 }],
352 })),
353 |call| {
354 let (graphs, name) = target(call)?;
355 let (nodes, edges) = (call.args.get("nodes"), call.args.get("edges"));
356 if nodes.is_none() && edges.is_none() {
357 return Err("give `nodes`, `edges` or both".into());
358 }
359 let nodes = match nodes {
360 Some(v) => v
361 .as_array()
362 .ok_or("`nodes` is not a list")?
363 .iter()
364 .filter_map(|n| n.as_str().map(str::to_string))
365 .collect(),
366 None => Vec::new(),
367 };
368 let edges = match edges {
369 Some(v) => v
370 .as_array()
371 .ok_or("`edges` is not a list")?
372 .iter()
373 .map(|e| Edge::from_json(e).ok_or_else(|| format!("not a wire: {e}")))
374 .collect::<Result<Vec<_>, _>>()?,
375 None => Vec::new(),
376 };
377 graphs.request(&name, Request::Select(nodes));
378 graphs.request(&name, Request::SelectWires(edges));
379 Ok(json!({ "graph": name, "queued": "select" }))
380 },
381 )?;
382 ctx.command(
383 CommandSpec::new(CMD_GRAPH_VIEW, "Change the graph's view", CAT)
384 .description("Fits a node editor's graph (`fit`: true), zooms to a level (`level`: overview, ports or detail) or focuses a node (`focus`), at its next frame.")
385 .hidden()
386 .args(json!({ "graph": "main", "level": "detail" })),
387 |call| {
388 let (graphs, name) = target(call)?;
389 let a = call.args;
390 let request = if a.get("fit").and_then(Json::as_bool) == Some(true) {
391 Request::Fit
392 } else if let Some(l) = a.get("level").and_then(Json::as_str) {
393 Request::Level(level_of(l)?)
394 } else if let Some(n) = a.get("focus").and_then(Json::as_str) {
395 Request::Focus(n.to_string())
396 } else {
397 return Err("give `fit`, `level` or `focus`".into());
398 };
399 graphs.request(&name, request);
400 Ok(json!({ "graph": name, "queued": "view" }))
401 },
402 )?;
403 ctx.command(
404 CommandSpec::new(CMD_GRAPH_EXPORT, "Export the graph", CAT)
405 .description("A node editor's graph as an image, drawn from the graph and its layout as the editor drew it last: `format` (svg by default; png or pdf when built with them), `selection` (true: only the selected nodes), `level` (overview, ports or detail; ports by default), `wires` (curves, orthogonal or straight; the editor's by default), `background` (false: transparent), `title`, `scale` (a PNG's pixels per point, 1 by default). Gives `svg` as text, or `png` or `pdf` base64-encoded.")
406 .hidden()
407 .args(json!({ "graph": "main", "format": "svg", "selection": false, "level": "ports" })),
408 |call| {
409 let (graphs, name) = target(call)?;
410 let format = call
411 .args
412 .get("format")
413 .and_then(Json::as_str)
414 .unwrap_or("svg")
415 .to_string();
416 if !EXPORT_FORMATS.contains(&format.as_str()) {
417 return Err(format!(
418 "no export format `{format}` (built with: {})",
419 EXPORT_FORMATS.join(", ")
420 ));
421 }
422 let export = graphs
423 .export(&name)
424 .ok_or_else(|| format!("no graph to export from `{name}` yet"))?;
425 let (export, options) = export_args(export, call.args)?;
426 let data = match format.as_str() {
427 #[cfg(feature = "graph-png")]
428 "png" => {
429 let scale = call.args.get("scale").and_then(Json::as_f64).unwrap_or(1.0);
430 base64(&export.png(&options, scale as f32).map_err(|e| e.to_string())?)
431 }
432 #[cfg(feature = "graph-pdf")]
433 "pdf" => base64(&export.pdf(&options).map_err(|e| e.to_string())?),
434 _ => export.svg(&options),
435 };
436 let mut out = json!({ "graph": name, "format": format });
437 out[format.as_str()] = Json::String(data);
438 Ok(out)
439 },
440 )?;
441 Ok(())
442}
443
444pub const EXPORT_FORMATS: &[&str] = &[
447 "svg",
448 #[cfg(feature = "graph-png")]
449 "png",
450 #[cfg(feature = "graph-pdf")]
451 "pdf",
452];
453
454#[cfg(any(feature = "graph-png", feature = "graph-pdf"))]
456fn base64(bytes: &[u8]) -> String {
457 use base64::Engine as _;
458 base64::engine::general_purpose::STANDARD.encode(bytes)
459}
460
461fn level_of(name: &str) -> Result<Level, String> {
463 match name {
464 "overview" => Ok(Level::Overview),
465 "ports" => Ok(Level::Ports),
466 "detail" => Ok(Level::Detail),
467 _ => Err(format!("no level `{name}`")),
468 }
469}
470
471fn export_args(export: GraphExport, a: &Json) -> Result<(GraphExport, ExportOptions), String> {
473 let mut options = ExportOptions::default();
474 if let Some(on) = a.get("selection").and_then(Json::as_bool) {
475 options = options.selection(on);
476 }
477 if let Some(l) = a.get("level").and_then(Json::as_str) {
478 options = options.level(level_of(l)?);
479 }
480 if let Some(on) = a.get("background").and_then(Json::as_bool) {
481 options = options.background(on);
482 }
483 if let Some(t) = a.get("title").and_then(Json::as_str) {
484 options = options.title(t);
485 }
486 let export = match a.get("wires").and_then(Json::as_str) {
487 Some(w) => {
488 export.wires(WireStyle::from_name(w).ok_or_else(|| format!("no wire style `{w}`"))?)
489 }
490 None => export,
491 };
492 Ok((export, options))
493}