From b0fab0b7e48da7dbb20b2dc2ea17cd7da2bddfce Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 28 Nov 2026 13:52:39 -0500 Subject: [PATCH] panels-w4: net change of 3 commits - panels-w4: written from its sheet - panels-w4: repair 1 - panels-w4: review fixes (review-1) --- crates/ui-egui/src/explorer.rs | 246 ++++---- crates/ui-egui/src/explorer/actions.rs | 64 +- crates/ui-egui/src/explorer/explorer_state.rs | 5 - crates/ui-egui/src/explorer/explorer_tree.rs | 551 +++++++++++------- crates/ui-egui/src/explorer/tree_row.rs | 35 -- 5 files changed, 510 insertions(+), 391 deletions(-) delete mode 100644 crates/ui-egui/src/explorer/tree_row.rs diff --git a/crates/ui-egui/src/explorer.rs b/crates/ui-egui/src/explorer.rs index 486a2a45..2e45501b 100644 --- a/crates/ui-egui/src/explorer.rs +++ b/crates/ui-egui/src/explorer.rs @@ -1,16 +1,21 @@ //! The package tree, its graphs, inputs, outputs and resources +use craft_behavior::IconId; +use craft_theme::ControlSize; +use craft_ui::{ + buttons::IconButton, + contract::{Gap, Props as _, Show as _, ShowContainer as _}, + layout_components::Row, + primitives::IconSpec, +}; use egui::Ui; mod actions; mod context_menu; mod explorer_menu_state; -pub(crate) mod explorer_row; mod explorer_state; mod explorer_target; mod explorer_tree; -mod tree_row; -use egui_phosphor::regular as icon; pub use explorer_state::ExplorerState; pub use explorer_target::ExplorerTarget; use serde_json::json; @@ -18,86 +23,83 @@ use serde_json::json; use crate::MaterialCraftApp; use crate::i18n::tr; +/// Inspects the graph in the Properties panel. +fn inspect_graph(app: &mut MaterialCraftApp, target: materialcraft_engine::GraphTarget) { + app.inspected_graph = Some(target); + app.inspected_folder = None; + app.ui.dock.focus(crate::docking::Panel::Properties); +} + +/// Inspects the folder in the Properties panel. +fn inspect_folder(app: &mut MaterialCraftApp, target: (u64, String)) { + app.inspected_folder = Some(target); + app.inspected_graph = None; + app.ui.dock.focus(crate::docking::Panel::Properties); +} + /// Selects the row as a click does. -#[allow(dead_code)] // P3(panels-w4): pn.A38 pub(crate) fn select(app: &mut MaterialCraftApp, target: ExplorerTarget) { - let _ = (app, target); - todo!("pn.A38") + match &target { + ExplorerTarget::Graph { document, index } => inspect_graph(app, materialcraft_engine::GraphTarget { document: *document, graph: *index }), + ExplorerTarget::Folder { document, path } => inspect_folder(app, (*document, path.clone())), + _ => {} + } + app.ui.explorer.selected = Some(target); } /// True when the target is in the open package. -#[allow(dead_code)] // P3(panels-w4): pn.A39 pub(crate) fn exists(app: &MaterialCraftApp, target: &ExplorerTarget) -> bool { - let _ = (app, target); - todo!("pn.A39") + app.session.package(target.document()).is_ok_and(|package| match target { + ExplorerTarget::Folder { path, .. } => package.folder_paths().contains(path), + _ => target.name(package).is_some(), + }) } /// Runs a row-menu command on the target, refusing one the row does not offer; no `egui::Context`. It refuses /// `graph.rename` and `folder.rename` with a message that points to `ui.explorer.rename`. -#[allow(dead_code)] // P3(panels-w4): pn.A40 pub(crate) fn invoke(app: &mut MaterialCraftApp, target: ExplorerTarget, command: &str) -> Result<(), String> { - let _ = (app, target, command); - todo!("pn.A40") + if matches!(command, "graph.rename" | "folder.rename") { + return Err("rename is typed in place: use ui.explorer.rename".to_string()); + } + if !context_menu::offers(&target, command) { + return Err(format!("the row does not offer {command}")); + } + actions::invoke(app, target, command); + Ok(()) +} + +/// The toolbar: each button fires the registered command the menus run. +fn toolbar(app: &MaterialCraftApp, ui: &mut Ui) { + let has_package = app.session.has_package(); + Row::new().gap(Gap::Tight).show(ui, |ui, _| { + for (icon, command, tip, needs_package) in [ + ("new_file", "ui.newGraph", "New graph...", false), + ("folder_open", "file.open", "Open package...", false), + ("save", "file.save", "Save package", true), + ("export", "ui.export", "Export outputs...", true), + ("image", "file.importBitmap", "Import bitmap...", true), + ] { + IconButton::command(IconSpec::svg(IconId::new(icon)), command) + + .tooltip(tr(tip)) + .size(ControlSize::Sm) + .enabled(!needs_package || has_package) + .show(ui); + } + }); } /// Draw open packages and dispatch selection, resource and context-menu actions. pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 2.0; - if crate::widgets::icon_button(ui, icon::FILE_PLUS, tr("New graph..."), false, 22.0).clicked() { - crate::menus::invoke(app, ui.ctx(), "ui.newGraph"); - } - if crate::widgets::icon_button(ui, icon::FOLDER_OPEN, tr("Open package..."), false, 22.0).clicked() { - crate::menus::invoke(app, ui.ctx(), "file.open"); - } - ui.add_enabled_ui(app.session.has_package(), |ui| { - if crate::widgets::icon_button(ui, icon::FLOPPY_DISK, tr("Save package"), false, 22.0).clicked() { - crate::menus::invoke(app, ui.ctx(), "file.save"); - } - if crate::widgets::icon_button(ui, icon::EXPORT, tr("Export outputs..."), false, 22.0).clicked() { - crate::export::open(app, crate::export::ExportTab::FromGraph); - } - if crate::widgets::icon_button(ui, icon::IMAGE, tr("Import bitmap..."), false, 22.0).clicked() { - crate::windows::import_resource(app, false); - } - }); - }); - ui.add_space(2.0); - let context = ui.ctx().clone(); - let mut tree = explorer_tree::ExplorerTree { - session: &app.session, - state: &mut app.ui.explorer, - action: None, - opened_node: None, - assignment: None, - movement: None, - inspected_graph: None, - inspected_folder: None, - }; - let scroll = egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { - for (document, package, path, modified) in tree.session.open_packages() { - ui.push_id(document, |ui| tree.package(ui, document, package, path, modified)); - } - }); - tree.state.hovered = ui.rect_contains_pointer(scroll.inner_rect); - let action = tree.action; - let opened_node = tree.opened_node; - let assignment = tree.assignment; - let movement = tree.movement; - let inspected_folder = tree.inspected_folder; - if let Some(target) = tree.inspected_graph { - crate::properties::GraphPropertyDraft::commit(app); - app.inspected_graph = Some(target); - app.inspected_folder = None; - app.ui.dock.focus(crate::docking::Panel::Properties); + toolbar(app, ui); + let output = explorer_tree::show(app, ui); + if let Some(target) = output.inspected_graph { + inspect_graph(app, target); } - if let Some(target) = inspected_folder { - crate::properties::GraphPropertyDraft::commit(app); - app.inspected_folder = Some(target); - app.inspected_graph = None; - app.ui.dock.focus(crate::docking::Panel::Properties); + if let Some(target) = output.inspected_folder { + inspect_folder(app, target); } - if let Some((document, index, node)) = opened_node { + if let Some((document, index, node)) = output.opened_node { if !actions::activate(app, document) { return; } @@ -107,7 +109,6 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { } app.pattern_editor = None; - crate::properties::GraphPropertyDraft::commit(app); app.inspected_graph = None; app.inspected_folder = None; app.function_editor = None; @@ -118,54 +119,101 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { app.run("view.2d", json!({"node": node.0})); app.ui.dock.focus(crate::docking::Panel::View2d); } - if let Some(parameters) = assignment { - app.run("view.3d.assign", parameters); - } - if let Some((target, parent)) = movement + if let Some((target, parent)) = output.movement && actions::activate(app, target.document()) { let mut parameters = target.parameters(); parameters["parent"] = json!(parent); app.run("explorer.move", parameters); } - if let Some((target, command)) = action { + if let Some((target, name)) = output.renamed { + actions::rename(app, &target, &name); + } + if let Some((target, command)) = output.action { if command == "activate" { actions::activate(app, target.document()); } else { - actions::invoke(app, &context, target, command); + actions::invoke(app, target, command); } } } -/// Enter opens, F2 renames and Delete removes the selected graph or folder while the pointer is -/// over the Explorer; elsewhere those keys keep their graph shortcuts. True when a key was used -pub(crate) fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) -> bool { - if !app.ui.dock.is_visible(crate::docking::Panel::Explorer) || !app.ui.explorer.hovered || app.ui.explorer.rename.is_some() { - return false; +#[cfg(test)] +mod tests { + use crate::{MaterialCraftApp, UiState}; + use egui::accesskit::Role; + use egui_kittest::kittest::{By, Queryable as _}; + use serde_json::json; + + /// The Explorer's row of the graph named `name`. + fn row(name: &str) -> By<'_> { + By::new().role(Role::TreeItem).label(name) } - let Some(target) = app.ui.explorer.selected.clone() else { return false }; - let command = match &target { - ExplorerTarget::Graph { .. } => [(egui::Key::Enter, "graph.open"), (egui::Key::F2, "graph.rename"), (egui::Key::Delete, "graph.delete")] - .into_iter() - .find(|(key, _)| pressed(ctx, *key)), - ExplorerTarget::Folder { .. } if !target.is_resources_root() => { - [(egui::Key::F2, "folder.rename"), (egui::Key::Delete, "folder.remove")].into_iter().find(|(key, _)| pressed(ctx, *key)) + /// Enter, F2 and Delete act on the selected graph once the Explorer's list has focus, through the whole app's key routing. + #[test] + fn explorer_keys_act_on_its_selection_while_the_list_has_focus() { + let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default()); + app.run("file.new", json!({"folder": "", "kind": "material", "name": "Second", "template": "empty"})).unwrap(); + let first = app.session.pkg.graphs[0].name.clone(); + let count = app.session.pkg.graphs.len(); + assert_ne!(app.session.graph, 0, "the new graph is the open one"); + let mut harness = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(|cc| { + MaterialCraftApp::install_runtime(&cc.egui_ctx, None).unwrap(); + app + }); + harness.run(); + let fields = |harness: &egui_kittest::Harness<'_, MaterialCraftApp>| harness.query_all(By::new().role(Role::TextInput)).count(); + + harness.get(row(&first)).click(); + harness.run(); + harness.key_press(egui::Key::Enter); + harness.run(); + assert_eq!(harness.state().session.graph, 0, "Enter opens the selected graph"); + + let before = fields(&harness); + harness.key_press(egui::Key::F2); + harness.run(); + assert!(fields(&harness) > before, "F2 opens the in-place rename editor"); + harness.key_press(egui::Key::Escape); + harness.run(); + assert_eq!(fields(&harness), before, "Escape cancels it"); + assert_eq!(harness.state().session.pkg.graphs[0].name, first); + + harness.key_press(egui::Key::Delete); + harness.run(); + assert_eq!(harness.state().session.pkg.graphs.len(), count - 1, "Delete removes the selected graph"); + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Z); + harness.run(); + assert_eq!(harness.state().session.pkg.graphs.len(), count, "Ctrl+Z restores it"); + + // A press away from the Explorer takes the list's focus; the keys then belong to the rest of the app. + let pos = egui::pos2(1150.0, 700.0); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); } - _ => None, - }; - let Some((key, command)) = command else { return false }; - ctx.input_mut(|input| input.consume_key(egui::Modifiers::NONE, key)); - actions::invoke(app, ctx, target, command); - true -} + harness.run(); + let before = fields(&harness); + harness.key_press(egui::Key::F2); + harness.run(); + assert_eq!(fields(&harness), before, "F2 away from the Explorer does not rename its row"); + harness.key_press(egui::Key::Delete); + harness.run(); + assert_eq!(harness.state().session.pkg.graphs.len(), count, "Delete away from the Explorer keeps its graph"); -/// Match an unmodified Explorer shortcut key. -fn pressed(ctx: &egui::Context, key: egui::Key) -> bool { - ctx.input(|input| input.modifiers.is_none() && input.key_pressed(key)) -} + harness.get(row(&first)).hover(); + harness.run(); + harness.key_press(egui::Key::Delete); + harness.run(); + assert_eq!(harness.state().session.pkg.graphs.len(), count - 1, "Delete over the Explorer removes the selection without focus"); + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Z); + harness.run(); + assert_eq!(harness.state().session.pkg.graphs.len(), count, "Ctrl+Z restores it again"); -/// Draw the pending Explorer rename dialog. -pub(crate) fn dialogs(app: &mut MaterialCraftApp, ctx: &egui::Context) { - actions::rename_dialog(app, ctx); + harness.state_mut().ui.dock.close(crate::docking::Panel::Explorer); + harness.run(); + harness.key_press(egui::Key::Delete); + harness.run(); + assert_eq!(harness.state().session.pkg.graphs.len(), count, "a closed Explorer deletes nothing"); + } } diff --git a/crates/ui-egui/src/explorer/actions.rs b/crates/ui-egui/src/explorer/actions.rs index 332b1987..09041f1b 100644 --- a/crates/ui-egui/src/explorer/actions.rs +++ b/crates/ui-egui/src/explorer/actions.rs @@ -1,5 +1,5 @@ use super::ExplorerTarget; -use crate::{MaterialCraftApp, i18n::tr}; +use crate::MaterialCraftApp; use serde_json::json; /// Activate the target package before dispatching its Explorer action. @@ -8,11 +8,10 @@ pub(super) fn activate(app: &mut MaterialCraftApp, document: u64) -> bool { } /// Dispatch an Explorer action using the selected item and its owning package. -pub(super) fn invoke(app: &mut MaterialCraftApp, ctx: &egui::Context, target: ExplorerTarget, command: &str) { +pub(super) fn invoke(app: &mut MaterialCraftApp, target: ExplorerTarget, command: &str) { if command == "graph.resource.add" { let mut parameters = target.parameters(); parameters["document"] = json!(target.document()); - crate::properties::GraphPropertyDraft::commit(app); if app.run(command, parameters).is_some() { app.inspected_folder = None; app.inspected_graph = None; @@ -46,11 +45,6 @@ pub(super) fn invoke(app: &mut MaterialCraftApp, ctx: &egui::Context, target: Ex app.ui.explorer.selected = Some(ExplorerTarget::Folder { document: target.document(), path }); } } - "graph.rename" | "folder.rename" => { - if let Some(name) = target.name(&app.session.pkg) { - app.ui.explorer.rename = Some((target, name)); - } - } "explorer.paste" => { app.run(command, json!({"folder": folder})); } @@ -120,7 +114,7 @@ fn package_path(app: &MaterialCraftApp) -> Option { fn show_in_folder(app: &mut MaterialCraftApp) { let Some(path) = package_path(app) else { return }; if let Err(error) = craft_update::process::reveal(std::path::Path::new(&path)) { - app.toast(format!("{}: {error}", tr("Could not show the package file")), true); + app.toast(format!("{}: {error}", crate::i18n::tr("Could not show the package file")), true); } } @@ -143,43 +137,19 @@ fn open_dependencies(app: &mut MaterialCraftApp) { #[cfg(target_arch = "wasm32")] fn open_dependencies(_: &mut MaterialCraftApp) {} -/// Apply a validated graph or folder rename through the engine. -pub(super) fn rename_dialog(app: &mut MaterialCraftApp, ctx: &egui::Context) { - let Some((target, mut name)) = app.ui.explorer.rename.clone() else { return }; - let mut open = true; - let mut accept = false; - let mut cancel = false; - egui::Window::new(tr("Rename")) - .id(egui::Id::unique("explorer-rename")) - .collapsible(false) - .resizable(false) - .open(&mut open) - .anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO) - .show(ctx, |ui| { - let response = ui.text_edit_singleline(&mut name); - crate::widgets::name(&response, egui::Role::TextInput, "Name"); - if !ctx.memory(|memory| memory.has_focus(response.id)) && !ctx.egui_wants_keyboard_input() { - response.request_focus(); - } - accept |= response.lost_focus() && ui.input(|input| input.key_pressed(egui::Key::Enter)); - ui.horizontal(|ui| { - accept |= ui.button(tr("Rename")).clicked(); - cancel |= ui.button(tr("Cancel")).clicked(); - }); - }); - cancel |= ctx.input(|input| input.key_pressed(egui::Key::Escape)); - app.ui.explorer.rename = if open && !cancel { Some((target.clone(), name.clone())) } else { None }; - if accept && activate(app, target.document()) { - let mut parameters = target.parameters(); - parameters["name"] = json!(name); - let command = if matches!(target, ExplorerTarget::Folder { .. }) { "folder.rename" } else { "graph.rename" }; - if let Some(result) = app.run(command, parameters) { - app.ui.explorer.rename = None; - app.ui.explorer.selected = if let Some(path) = result.get("folder").and_then(|path| path.as_str()) { - Some(ExplorerTarget::Folder { document: target.document(), path: path.into() }) - } else { - Some(target) - }; - } +/// Apply a graph or folder rename the in-place editor committed, then select the renamed row. +pub(super) fn rename(app: &mut MaterialCraftApp, target: &ExplorerTarget, name: &str) { + if !activate(app, target.document()) { + return; + } + let mut parameters = target.parameters(); + parameters["name"] = json!(name); + let command = if matches!(target, ExplorerTarget::Folder { .. }) { "folder.rename" } else { "graph.rename" }; + if let Some(result) = app.run(command, parameters) { + app.ui.explorer.selected = if let Some(path) = result.get("folder").and_then(|path| path.as_str()) { + Some(ExplorerTarget::Folder { document: target.document(), path: path.into() }) + } else { + Some(target.clone()) + }; } } diff --git a/crates/ui-egui/src/explorer/explorer_state.rs b/crates/ui-egui/src/explorer/explorer_state.rs index 3f7d36bd..ffdacd07 100644 --- a/crates/ui-egui/src/explorer/explorer_state.rs +++ b/crates/ui-egui/src/explorer/explorer_state.rs @@ -8,10 +8,5 @@ pub struct ExplorerState { pub selected: Option, /// The rows whose children are hidden; session only #[serde(skip)] - #[allow(dead_code)] // P3(panels-w4): pn.A32 pub closed: HashSet, - pub rename: Option<(ExplorerTarget, String)>, - /// The pointer was over the Explorer last frame, so Enter, F2 and Delete act on its selection - #[serde(skip)] - pub hovered: bool, } diff --git a/crates/ui-egui/src/explorer/explorer_tree.rs b/crates/ui-egui/src/explorer/explorer_tree.rs index 91bca9fc..a8c4270d 100644 --- a/crates/ui-egui/src/explorer/explorer_tree.rs +++ b/crates/ui-egui/src/explorer/explorer_tree.rs @@ -1,243 +1,384 @@ -use super::{ExplorerState, ExplorerTarget, context_menu, tree_row}; -use crate::graph_drag_payload::GraphDragPayload; +use super::{ExplorerState, ExplorerTarget, actions, context_menu, explorer_menu_state::ExplorerMenuState}; +use crate::{MaterialCraftApp, graph_drag_payload::GraphDragPayload, i18n::tr}; +use craft_behavior::{DisplayOrder, EditEvent, IconId, ItemSource, Selection, SelectionChange}; +use craft_theme::variant::Tone; +use craft_ui::{ + contract::{ + Bind, CollectionEvent, DeleteTarget, DropAt, DropKind, DropPlace, LeadSource, ListDrag, Props as _, SelectMode, ShowCollection as _, + ShowContainer as _, + }, + list::{List, ListRow}, + menu::Menu, + primitives::IconSpec, +}; use egui::Ui; -use egui_phosphor::regular as icon; use materialcraft_engine::{ - Session, + GraphTarget, Session, core::{NodeId, Package}, }; -use serde_json::Value; -use std::collections::BTreeSet; +use std::{ + collections::{BTreeSet, HashMap, HashSet}, + sync::Arc, +}; -pub(super) struct ExplorerTree<'a> { - pub session: &'a Session, - pub state: &'a mut ExplorerState, +/// What one pass of the tree asks the Explorer to do once the list has been shown. +#[derive(Default)] +pub(super) struct Output { + /// A row command to run on its target: a menu pick, a double click or Enter, or Delete. pub action: Option<(ExplorerTarget, &'static str)>, + /// A port row was activated: its document, graph and node. pub opened_node: Option<(u64, usize, NodeId)>, - pub assignment: Option, + /// A drop onto a package or folder row: the target moved and the folder it moves to. pub movement: Option<(ExplorerTarget, String)>, - pub inspected_graph: Option, + /// A graph row was picked. + pub inspected_graph: Option, + /// A folder row was picked: its document and path. pub inspected_folder: Option<(u64, String)>, + /// A rename the in-place editor committed. + pub renamed: Option<(ExplorerTarget, String)>, } -impl ExplorerTree<'_> { - pub fn package(&mut self, ui: &mut Ui, document: u64, package: &Package, path: Option<&str>, modified: bool) { - let warnings: Vec<_> = package - .graphs - .iter() - .map(|graph| { - materialcraft_engine::function_inspection::warnings(graph).into_iter().flat_map(|(_, messages)| messages).collect::>().join("\n") - }) - .collect(); - let package_warning = warnings.iter().filter(|warning| !warning.is_empty()).cloned().collect::>().join("\n"); - let target = ExplorerTarget::Package { document }; - let name = path.and_then(|path| path.rsplit(['/', '\\']).next()).unwrap_or(&package.name); - let name = format!("{name}{}", if modified { "*" } else { "" }); - let folders = package.folder_paths(); +/// One row of the tree. +struct Row { + target: ExplorerTarget, + name: String, + icon: &'static str, + depth: usize, + has_children: bool, + open: bool, + warning: String, + /// The package's saved path, shown as the row's hover text. + path: Option, +} - // The implicit Resources group is hidden until it contains assets or subfolders - let has_children = - !package.graphs.is_empty() || !package.resources.is_empty() || folders.iter().any(|folder| !folder.eq_ignore_ascii_case("Resources")); - let mut header = |ui: &mut Ui| { - let response = self.row(ui, &target, package, &name, icon::PACKAGE, &package_warning, path.is_some()); - if let Some(path) = path { - response.on_hover_text(path); +/// The rows of every open package, in display order; rebuilt each pass from the session. +struct ExplorerRows { + rows: Vec, + /// The `.sbs` path of each graph row, which a graph drag carries. + graph_paths: Arc>, +} + +/// One package's walk: what its folders and graphs need to build rows. +struct Walk<'a> { + document: u64, + package: &'a Package, + folders: BTreeSet, + warnings: Vec, + closed: &'a HashSet, +} + +impl ExplorerRows { + fn new(session: &Session, closed: &HashSet) -> Self { + let mut rows = Vec::new(); + let mut graph_paths = HashMap::new(); + for (document, package, path, modified) in session.open_packages() { + for (index, graph) in package.graphs.iter().enumerate() { + graph_paths.insert(ExplorerTarget::Graph { document, index }, graph.sbs_path()); } - }; - if !has_children { - ui.horizontal(|ui| { - ui.add_space(ui.spacing().indent); - header(ui); + let warnings: Vec = package + .graphs + .iter() + .map(|graph| { + materialcraft_engine::function_inspection::warnings(graph).into_iter().flat_map(|(_, messages)| messages).collect::>().join("\n") + }) + .collect(); + let package_warning = warnings.iter().filter(|warning| !warning.is_empty()).cloned().collect::>().join("\n"); + let name = path.and_then(|path| path.rsplit(['/', '\\']).next()).unwrap_or(&package.name); + let name = format!("{name}{}", if modified { "*" } else { "" }); + let walk = Walk { document, package, folders: package.folder_paths(), warnings, closed }; + let target = ExplorerTarget::Package { document }; + let mut children = Vec::new(); + walk.level(&mut children, "", 1); + let open = !closed.contains(&target); + rows.push(Row { + target, + name, + icon: "package", + depth: 0, + has_children: !children.is_empty(), + open, + warning: package_warning, + path: path.map(str::to_string), }); - return; + if open { + rows.append(&mut children); + } } - - let id = ui.make_persistent_id((document, "package")); - egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true).show_header(ui, header).body(|ui| { - self.level(ui, document, package, &folders, "", &warnings, 0); - }); + ExplorerRows { rows, graph_paths: Arc::new(graph_paths) } } - fn level(&mut self, ui: &mut Ui, document: u64, package: &Package, folders: &BTreeSet, parent: &str, warnings: &[String], depth: usize) { + fn row(&self, key: &ExplorerTarget) -> ListRow<'static> { + let Some(row) = self.rows.iter().find(|row| row.target == *key) else { return ListRow::spacer() }; + let line = ListRow::new(row.name.clone()).depth(row.depth).icon(IconSpec::svg(IconId::new(row.icon))); + let line = if row.has_children { line.group(row.open) } else { line }; + let line = match &row.path { + Some(path) => line.tooltip(path.clone()), + None => line, + }; + if row.warning.is_empty() { + line + } else { + line.trailing_icon(IconSpec::svg(IconId::new("warning")), row.warning.clone()).trailing_tone(Tone::Warn) + } + } +} + +impl Walk<'_> { + /// The rows under `parent` (a folder path, "" for the package), at row depth `depth`. + fn level(&self, rows: &mut Vec, parent: &str, depth: usize) { // Imported paths are bounded too, but UI inspection can supply arbitrary state - if depth > 64 { + if depth > 65 { return; } - - for folder in folders.iter().filter(|path| path.rsplit_once('/').map_or("", |(parent, _)| parent) == parent) { + let (document, package) = (self.document, self.package); + for folder in self.folders.iter().filter(|path| path.rsplit_once('/').map_or("", |(parent, _)| parent) == parent) { + // The implicit Resources group is hidden until it contains assets or subfolders if folder.eq_ignore_ascii_case("Resources") && !package.resources.iter().any(|resource| resource.folder == *folder || resource.folder.starts_with(&format!("{folder}/"))) - && !folders.iter().any(|path| path.starts_with(&format!("{folder}/"))) + && !self.folders.iter().any(|path| path.starts_with(&format!("{folder}/"))) { continue; } - let target = ExplorerTarget::Folder { document, path: folder.clone() }; - let name = folder.rsplit('/').next().unwrap_or(folder); - let id = ui.make_persistent_id((document, "folder", folder)); - egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true) - .show_header(ui, |ui| { - self.row(ui, &target, package, name, icon::FOLDER, "", false); - }) - .body(|ui| self.level(ui, document, package, folders, folder, warnings, depth + 1)); + let mut children = Vec::new(); + self.level(&mut children, folder, depth + 1); + let open = !self.closed.contains(&target); + rows.push(Row { + name: folder.rsplit('/').next().unwrap_or(folder).to_string(), + target, + icon: "folder", + depth, + has_children: !children.is_empty(), + open, + warning: String::new(), + path: None, + }); + if open { + rows.append(&mut children); + } } for resource in package.resources.iter().filter(|resource| resource.folder == parent) { - ui.horizontal(|ui| { - ui.add_space(ui.spacing().indent); - let target = ExplorerTarget::Resource { document, name: resource.name.clone() }; - self.row(ui, &target, package, &resource.name, icon::IMAGE, if resource.bytes.is_empty() { "Missing resource" } else { "" }, false); + rows.push(Row { + target: ExplorerTarget::Resource { document, name: resource.name.clone() }, + name: resource.name.clone(), + icon: "image", + depth, + has_children: false, + open: false, + warning: if resource.bytes.is_empty() { tr("Missing resource").to_string() } else { String::new() }, + path: None, }); } for (index, graph) in package.graphs.iter().enumerate().filter(|(_, graph)| graph.folder == parent) { let target = ExplorerTarget::Graph { document, index }; - let symbol = if graph.function.is_some() { icon::FUNCTION } else { icon::TREE_STRUCTURE }; - let warning = warnings.get(index).map(String::as_str).unwrap_or(""); - let mut ports = - graph.nodes.iter().filter(|node| matches!(node.def.as_str(), "output" | "input_color" | "input_grayscale" | "input_value")).peekable(); - if graph.function.is_some() || ports.peek().is_none() { - ui.horizontal(|ui| { - ui.add_space(ui.spacing().indent); - self.row(ui, &target, package, &graph.name, symbol, warning, false); - }); - continue; - } - - let id = ui.make_persistent_id((document, "graph", index)); - egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true) - .show_header(ui, |ui| { - self.row(ui, &target, package, &graph.name, symbol, warning, false); - }) - .body(|ui| { - ui.indent("graph-ports", |ui| { - for node in ports { - ui.push_id(node.id, |ui| { - let name = crate::graph::node_label(node); - let target = ExplorerTarget::Node { document, graph: index, node: node.id }; - let selected = self.state.selected.as_ref() == Some(&target); - let symbol = if node.def == "input_value" { icon::FUNCTION } else { icon::IMAGE }; - let response = tree_row::show(ui, &name, symbol, selected, None); - response.context_menu(|ui| { - if document == self.session.document_id - && let Some(parameters) = preview_menu(ui, self.session, index, node.id) - { - self.assignment = Some(parameters); - } - }); - if response.clicked() || response.secondary_clicked() { - self.state.selected = Some(target); - } - if response.double_clicked() { - self.opened_node = Some((document, index, node.id)); - } - }); - } + let mut children = Vec::new(); + if graph.function.is_none() { + for node in graph.nodes.iter().filter(|node| matches!(node.def.as_str(), "output" | "input_color" | "input_grayscale" | "input_value")) { + children.push(Row { + target: ExplorerTarget::Node { document, graph: index, node: node.id }, + name: crate::graph::node_label(node), + icon: if node.def == "input_value" { "function" } else { "image" }, + depth: depth + 1, + has_children: false, + open: false, + warning: String::new(), + path: None, }); - }); - } - } - - fn row(&mut self, ui: &mut Ui, target: &ExplorerTarget, package: &Package, name: &str, symbol: &str, warning: &str, reload: bool) -> egui::Response { - let selected = self.state.selected.as_ref().map_or_else( - || matches!(target, ExplorerTarget::Graph { document, index } if *document == self.session.document_id && *index == self.session.graph), - |selected| selected == target, - ); - let response = tree_row::show(ui, name, symbol, selected, (!warning.is_empty()).then_some(warning)); - if response.clicked() || response.secondary_clicked() { - self.state.selected = Some(target.clone()); - if let ExplorerTarget::Graph { document, index } = target { - self.inspected_graph = Some(materialcraft_engine::GraphTarget { document: *document, graph: *index }); - } - if let ExplorerTarget::Folder { document, path } = target { - self.inspected_folder = Some((*document, path.clone())); - } - } - if response.double_clicked() && matches!(target, ExplorerTarget::Graph { .. }) { - self.action = Some((target.clone(), "graph.open")); - } - if response.double_clicked() && matches!(target, ExplorerTarget::Package { .. } | ExplorerTarget::Folder { .. }) { - self.action = Some((target.clone(), "activate")); - } - response.context_menu(|ui| { - let outputs = match target { - ExplorerTarget::Graph { index, .. } => package.graphs.get(*index).is_some_and(|graph| graph.function.is_none()), - _ => package.graphs.iter().any(|graph| graph.function.is_none()), - }; - let dependencies = package.dependencies.keys().any(|path| super::actions::is_package_file(path)); - let state = - super::explorer_menu_state::ExplorerMenuState { paste: self.session.explorer_clipboard.is_some(), saved: reload, dependencies, outputs }; - if let Some(command) = context_menu::show(ui, &response, target, &state) { - // P3(panels-w4): pn.A34: the opener - self.action = Some((target.clone(), command)); - } - }); - if response.drag_started() { - match target { - ExplorerTarget::Graph { document, index } => { - if let Some(graph) = package.graphs.get(*index) { - egui::DragAndDrop::set_payload(ui.ctx(), GraphDragPayload { document: *document, name: graph.sbs_path() }); - } } - ExplorerTarget::Folder { .. } if !target.is_resources_root() => egui::DragAndDrop::set_payload(ui.ctx(), target.clone()), - ExplorerTarget::Resource { .. } => egui::DragAndDrop::set_payload(ui.ctx(), target.clone()), - _ => {} } - } - if !matches!(target, ExplorerTarget::Resource { .. }) - && let Some(parent) = target.folder(package) - { - if !target.is_resources() - && let Some(payload) = crate::widgets::dnd_release::(&response) - && payload.document == target.document() - && let Some((index, _)) = package.graph_by_name(&payload.name) - { - self.movement = Some((ExplorerTarget::Graph { document: payload.document, index }, parent.clone())); - } - if let Some(payload) = crate::widgets::dnd_release::(&response) - && payload.document() == target.document() - { - self.movement = Some((payload.as_ref().clone(), parent)); - } - } - response - } -} - -/// The 3D view assignment menu of an output node of graph `graph_index`, which need not be the open graph: the -/// `view.3d.assign` parameters of the picked channel. -fn preview_menu(ui: &mut Ui, session: &Session, graph_index: usize, node_id: NodeId) -> Option { - use crate::i18n::tr; - use materialcraft_engine::{MaterialSource, core::MaterialChannel}; - let graph = session.pkg.graphs.get(graph_index)?; - let node = graph.node(node_id).ok()?; - let ports = if node.def == "output" { - vec![("output".to_string(), materialcraft_engine::eval::identifier(node))] - } else { - materialcraft_engine::eval::ports(&session.pkg, graph, node).1.into_iter().map(|port| (port.id, port.label)).collect() - }; - let ports: Vec<_> = - ports.into_iter().filter(|(port, _)| MaterialSource { graph: graph_index, node: node_id, port: port.clone() }.is_image(&session.pkg)).collect(); - let mut action = None; - ui.add_enabled_ui(!ports.is_empty(), |ui| { - for (label, reset) in [("View in 3D view", false), ("Reset and view in 3D view", true)] { - ui.menu_button(tr(label), |ui| { - for (port, label) in &ports { - let mut channels = |ui: &mut Ui| { - for channel in MaterialChannel::ALL { - if ui.button(tr(channel.label())).clicked() { - action = - Some(serde_json::json!({"graph": graph_index, "node": node_id.0, "port": port, "channel": channel.id(), "reset": reset})); - ui.close(); - } - } - }; - if ports.len() == 1 { - channels(ui); - } else { - ui.menu_button(label, channels); - } - } + let open = !self.closed.contains(&target); + rows.push(Row { + name: graph.name.clone(), + icon: if graph.function.is_some() { "function" } else { "tree-structure" }, + depth, + has_children: !children.is_empty(), + open, + warning: self.warnings.get(index).cloned().unwrap_or_default(), + path: None, + target, }); + if open { + rows.append(&mut children); + } } - }); - action + } +} + +impl DisplayOrder for ExplorerRows { + fn len(&self) -> usize { + self.rows.len() + } + + fn key(&self, at: usize) -> ExplorerTarget { + self.rows[at].target.clone() + } + + fn depth(&self, at: usize) -> usize { + self.rows[at].depth + } + + fn has_children(&self, at: usize) -> bool { + self.rows[at].has_children + } + + fn open(&self, at: usize) -> bool { + self.rows[at].open + } +} + +impl ItemSource for ExplorerRows {} + +/// Records a click on a row: it is selected, and a graph or folder row is inspected. +fn pick(state: &mut ExplorerState, out: &mut Output, target: ExplorerTarget) { + match &target { + ExplorerTarget::Graph { document, index } => out.inspected_graph = Some(GraphTarget { document: *document, graph: *index }), + ExplorerTarget::Folder { document, path } => out.inspected_folder = Some((*document, path.clone())), + _ => {} + } + state.selected = Some(target); +} + +/// What the right-clicked row's menu allows right now. +fn menu_state(session: &Session, target: &ExplorerTarget) -> ExplorerMenuState { + let Ok(package) = session.package(target.document()) else { return ExplorerMenuState::default() }; + let outputs = match target { + ExplorerTarget::Graph { index, .. } => package.graphs.get(*index).is_some_and(|graph| graph.function.is_none()), + _ => package.graphs.iter().any(|graph| graph.function.is_none()), + }; + ExplorerMenuState { + paste: session.explorer_clipboard.is_some(), + saved: session.open_packages().into_iter().any(|(document, _, path, _)| document == target.document() && path.is_some()), + dependencies: package.dependencies.keys().any(|path| actions::is_package_file(path)), + outputs, + } +} + +/// Whether a drop can land on the row: packages and folders take drops. +fn takes_drops(target: &ExplorerTarget) -> bool { + matches!(target, ExplorerTarget::Package { .. } | ExplorerTarget::Folder { .. }) +} + +/// Shows the open packages as one tree list and reports what the user did. +pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) -> Output { + let mut out = Output::default(); + let list = { + let session = &app.session; + let state = &app.ui.explorer; + let rows = ExplorerRows::new(session, &state.closed); + // The shown selection is derived each pass: the picked row, else the open graph. + let selected = state.selected.clone().or_else(|| { + let open = ExplorerTarget::Graph { document: session.document_id, index: session.graph }; + rows.rows.iter().any(|row| row.target == open).then_some(open) + }); + let mut selection = selected.map_or_else(Selection::default, Selection::single); + let paths = Arc::clone(&rows.graph_paths); + List::::new(tr("Explorer")) + .select(SelectMode::Single) + .tree(true) + .rename(true) + .deletable(true) + .delete_target(DeleteTarget::FocusOrHover) + .can_rename(|key| match key { + ExplorerTarget::Graph { .. } => true, + ExplorerTarget::Folder { .. } => !key.is_resources_root(), + _ => false, + }) + .drag_payload(move |drag: &ListDrag| match &drag.grabbed { + ExplorerTarget::Graph { document, .. } => paths.get(&drag.grabbed).map(|name| GraphDragPayload { document: *document, name: name.clone() }), + _ => None, + }) + .drag_payload(|drag: &ListDrag| match &drag.grabbed { + ExplorerTarget::Folder { .. } if !drag.grabbed.is_resources_root() => Some(drag.grabbed.clone()), + ExplorerTarget::Resource { .. } => Some(drag.grabbed.clone()), + _ => None, + }) + .takes_drop(DropKind::new(DropPlace::Onto, |payload: &GraphDragPayload, at: &DropAt| { + matches!(at, DropAt::Onto(target) if takes_drops(target) && !target.is_resources() && target.document() == payload.document) + })) + .takes_drop(DropKind::new(DropPlace::Onto, |payload: &ExplorerTarget, at: &DropAt| { + matches!(at, DropAt::Onto(target) if takes_drops(target) && target.document() == payload.document()) + })) + .selection(Bind::bound(&mut selection)) + .show_items(ui, &rows, &mut |key, _| rows.row(key)) + }; + + let (session, state) = (&app.session, &mut app.ui.explorer); + for event in list.events { + match event { + CollectionEvent::Picked { key, .. } => pick(state, &mut out, key), + CollectionEvent::Selection { change, by, .. } => { + let key = match change { + SelectionChange::Set(keys) => keys.into_iter().last(), + SelectionChange::Toggle(key) => Some(key), + _ => None, + }; + if let Some(key) = key { + if matches!(by, LeadSource::Pointer) { + pick(state, &mut out, key); + } else { + state.selected = Some(key); + } + } + } + CollectionEvent::ContextMenu(request) => pick(state, &mut out, request.key), + CollectionEvent::Activate(target) => match target { + ExplorerTarget::Graph { .. } => out.action = Some((target, "graph.open")), + ExplorerTarget::Package { .. } | ExplorerTarget::Folder { .. } => out.action = Some((target, "activate")), + ExplorerTarget::Node { document, graph, node } => out.opened_node = Some((document, graph, node)), + ExplorerTarget::Resource { .. } => {} + }, + CollectionEvent::Open(change) => { + if change.open { + state.closed.remove(&change.key); + } else { + state.closed.insert(change.key); + } + } + CollectionEvent::Delete(keys) => { + let deletion = keys.into_iter().find_map(|key| match &key { + ExplorerTarget::Graph { .. } => Some((key, "graph.delete")), + ExplorerTarget::Folder { .. } if !key.is_resources_root() => Some((key, "folder.remove")), + _ => None, + }); + if deletion.is_some() { + out.action = deletion; + } + } + CollectionEvent::Rename(EditEvent::Commit { after, .. }) => out.renamed = Some((after.key, after.name)), + CollectionEvent::Dropped { at: DropAt::Onto(target), payload, .. } => { + let Ok(package) = session.package(target.document()) else { continue }; + let Some(parent) = target.folder(package) else { continue }; + if let Some(graph) = payload.get::() + && graph.document == target.document() + && let Some((index, _)) = package.graph_by_name(&graph.name) + { + out.movement = Some((ExplorerTarget::Graph { document: graph.document, index }, parent)); + } else if let Some(moved) = payload.get::() + && moved.document() == target.document() + { + out.movement = Some((moved.clone(), parent)); + } + } + _ => {} + } + } + + // The menu shows in every pass the list reports its request, as `Menu::context` asks. + if let Some(request) = &list.menu { + match &request.key { + ExplorerTarget::Node { document, graph, node } => { + if *document == app.session.document_id { + let rows = crate::material_preview_menu::rows(app, *graph, *node); + let _ = Menu::context(tr("Port menu"), &list.response).show(ui, |ui, _| craft_menu::context::rows(ui, &rows)); + } + } + target => { + let state = menu_state(&app.session, target); + // PLAN: assumed `context_menu::rows(&ExplorerTarget, &ExplorerMenuState) -> Vec` (panels-w5, q127); routing the Rename rows to the in-place editor is panels-w5's. + let rows = context_menu::rows(target, &state); + let _ = Menu::context(tr("Explorer menu"), &list.response).show(ui, |ui, _| craft_menu::context::rows(ui, &rows)); + } + } + } + out } diff --git a/crates/ui-egui/src/explorer/tree_row.rs b/crates/ui-egui/src/explorer/tree_row.rs deleted file mode 100644 index 3b175cc9..00000000 --- a/crates/ui-egui/src/explorer/tree_row.rs +++ /dev/null @@ -1,35 +0,0 @@ -use egui::{Align2, FontId, Rect, Response, Sense, Stroke, StrokeKind, Ui, vec2}; - -use crate::{theme::Tokens, widgets}; - -pub(super) fn show(ui: &mut Ui, name: &str, icon: &str, selected: bool, warning: Option<&str>) -> Response { - let theme = Tokens::get(ui.ctx()); - let (bounds, response) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click_and_drag()); - widgets::name(&response, egui::Role::TreeItem, name); - if selected { - ui.painter().rect_filled(bounds, 4.0, theme.row_selected); - ui.painter().rect_stroke(bounds, 4.0, Stroke::new(1.0, theme.accent), StrokeKind::Inside); - } else if response.hovered() { - ui.painter().rect_filled(bounds, 4.0, theme.row_hover); - } - - let mut text_bounds = bounds.intersect(ui.clip_rect()); - if let Some(warning) = warning { - let center = bounds.right_center() - vec2(12.0, 0.0); - let warning_response = ui.interact(Rect::from_center_size(center, vec2(20.0, 20.0)), response.id.with("warning"), Sense::hover()); - widgets::name(&warning_response, egui::Role::Label, &format!("Warnings for {name}")); - ui.ctx().accesskit_node_builder(warning_response.id, |node| node.set_description(warning)); - ui.painter().text(center, Align2::CENTER_CENTER, egui_phosphor::regular::WARNING, FontId::proportional(14.0), theme.warning); - warning_response.on_hover_text(warning); - text_bounds.max.x = text_bounds.max.x.min(bounds.right() - 24.0); - } - - ui.painter().with_clip_rect(text_bounds).text( - bounds.left_center() + vec2(4.0, 0.0), - Align2::LEFT_CENTER, - format!("{icon} {name}"), - FontId::proportional(12.0), - if selected { theme.text_strong } else { theme.text }, - ); - response -}