diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 2f3d940b0..d370a85c1 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -14,7 +14,7 @@ craft-mime = { workspace = true } craft-ui = { workspace = true } craft-behavior = { workspace = true } craft-host = { workspace = true } -craft-keymap = { workspace = true } +craft-keymap = { workspace = true, features = ["egui"] } craft-theme = { workspace = true } craft-window = { workspace = true } effectcraft-time = { workspace = true } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 3fc3803ad..d4925756c 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -122,6 +122,7 @@ impl EffectcraftApp { native_viewports: vec![], unpublished_viewports: vec![], pending_panel_raise: None, + live_dock: Default::default(), home_thumbs: Default::default(), home_thumb_saved: None, window_title: String::new(), diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index cca733c7c..d93b5673b 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -309,7 +309,7 @@ impl EffectcraftApp { // A hidden window paints when work needs a UI pass: queued input and waits, a settled // screenshot, or playback into a child viewport. let focused = self.focused; - let child_viewports = !self.ui.dock.layout.floating.is_empty() || prefs_live::video_preview_active(self, focused); + let child_viewports = !self.ui.dock.layout().floating.is_empty() || prefs_live::video_preview_active(self, focused); let paint = self.want_paint || !self.synthetic.is_empty() || !self.input_waiters.is_empty() diff --git a/crates/ui-egui/src/app/window.rs b/crates/ui-egui/src/app/window.rs index e741932f4..4dabd6192 100644 --- a/crates/ui-egui/src/app/window.rs +++ b/crates/ui-egui/src/app/window.rs @@ -101,22 +101,23 @@ impl EffectcraftApp { } .filter(|q| self.ui.dock.is_open(*q)); let mut workspace = self.ui.dock.clone(); - let known = workspace.hidden.iter().any(|(q, _)| *q == p); + let known = workspace.hidden().iter().any(|(q, _)| *q == p); let opened = if p == PanelKind::Composition && near.is_none() && !known && self.ui.dock.is_docked(PanelKind::Timeline) { workspace .apply( - craft_behavior::dock::Action::OpenAt { - panel: p, - anchor: PanelKind::Timeline, - placement: craft_behavior::dock::DockPlacement::Split(craft_ui::docking::Zone::Top), - }, + craft_behavior::dock::Action::open_at( + p, + PanelKind::Timeline, + craft_behavior::dock::DockPlacement::Split(craft_behavior::DockSide::Top), + ), + self.ui.dock_locked, dock::permissions, ) .map(|_| ()) } else if known { - workspace.set_visible(p, true, near, dock::permissions) + workspace.set_visible(p, true, near, self.ui.dock_locked, dock::permissions) } else { - workspace.apply(craft_behavior::dock::Action::Open { panel: p, anchor: near }, dock::permissions).map(|_| ()) + workspace.apply(craft_behavior::dock::Action::open(p, near), self.ui.dock_locked, dock::permissions).map(|_| ()) }; match opened { Ok(()) => self.ui.dock = workspace, @@ -126,7 +127,7 @@ impl EffectcraftApp { } } } - let _ = self.ui.dock.apply(craft_behavior::dock::Action::Activate { panel: p }, dock::permissions); + let _ = self.ui.dock.apply(craft_behavior::dock::Action::activate(p), self.ui.dock_locked, dock::permissions); if self.ui.dock.is_floating(p) { self.pending_panel_raise = Some(p); } diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 1a4e59783..c9f7d7275 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1,15 +1,14 @@ //! EffectCraft's panels and built-in workspaces in craft-ui's shared docking model //! ([`craft_ui::docking`]): splits, tab groups, After Effects' stacked panels and floating //! windows. craft-ui owns the layout model, its validation and every transaction; EffectCraft -//! owns the panel ids, the built-in workspaces and the decorations of its tabs (the comp tabs of -//! the Timeline, label swatches and viewer locks). +//! owns the panel ids, the built-in workspaces and the viewer locks in its group headers. -use egui::{Align2, Rect, Sense, Stroke, pos2, vec2}; +use egui::{Align2, Rect, Sense, pos2, vec2}; use serde::{Deserialize, Serialize}; +pub use craft_behavior::dock::SplitSize; pub use craft_behavior::dock::{Floating, Node, PanelState, Permissions, StackEntry}; pub use craft_behavior::flow::Axis; -pub use craft_behavior::dock::SplitSize; use crate::icons::{self, Icon}; use crate::theme::Tokens; @@ -189,7 +188,7 @@ pub fn tabs(p: &[PanelKind], active: usize) -> Node { Node::tabs(p.to_vec(), active) } /// Stacked panels: (panel, open, height). Open entries share the stack's height in proportion to -/// their heights; an entry without one counts as craft-ui's `DockStyle::min_pane` (40). +/// their heights; an entry without one shares the stack's height with the others. pub fn stack(e: &[(PanelKind, bool, Option)]) -> Node { Node::stack( e.iter() @@ -243,9 +242,7 @@ pub const WORKSPACES: &[&str] = &[ /// id, so a built-in layout built again is the same set of windows. fn workspace_floating(name: &str) -> Vec> { use PanelKind::*; - let f = |id: u64, panels: &[PanelKind], [x, y, w, h]: [f32; 4]| { - Floating::single(id, panels.to_vec(), 0, Rect::from_min_size(pos2(x, y), vec2(w, h))) - }; + let f = |id: u64, panels: &[PanelKind], [x, y, w, h]: [f32; 4]| Floating::single(id, panels.to_vec(), 0, Rect::from_min_size(pos2(x, y), vec2(w, h))); match name { "Undocked Panels" => vec![ f(1, &[Project, EffectControls], [24.0, 110.0, 320.0, 420.0]), @@ -442,7 +439,7 @@ pub(crate) fn node_panels(node: &Node, out: &mut Vec) { node_panels(second, out); } Node::Tabs { panels, .. } => out.extend(panels.iter().copied()), - Node::Stack { entries } => out.extend(entries.iter().map(|e| e.panel)), + Node::Stack { entries, .. } => out.extend(entries.iter().map(|e| e.panel)), Node::Dock { columns, .. } => { for group in columns.iter().flat_map(|c| c.groups.iter()) { out.extend(group.panels.iter().copied()); @@ -456,7 +453,7 @@ fn node_group(node: &Node, p: PanelKind) -> Option> { match node { Node::Split { first, second, .. } => node_group(first, p).or_else(|| node_group(second, p)), Node::Tabs { panels, .. } => panels.contains(&p).then(|| panels.clone()), - Node::Stack { entries } => entries.iter().any(|e| e.panel == p).then(|| vec![p]), + Node::Stack { entries, .. } => entries.iter().any(|e| e.panel == p).then(|| vec![p]), Node::Dock { columns, .. } => columns.iter().flat_map(|c| c.groups.iter()).find(|g| g.panels.contains(&p)).map(|g| g.panels.clone()), _ => None, } @@ -521,176 +518,13 @@ pub fn stack_gutter_id(layout: &Layout, p: PanelKind) -> Option { path.pop(); found } - Node::Stack { entries } => entries.iter().position(|e| e.panel == p).map(|i| format!("dock.gutter.{path}s{i}")), + Node::Stack { entries, .. } => entries.iter().position(|e| e.panel == p).map(|i| format!("dock.gutter.{path}s{i}")), _ => None, } } rec(layout.root.as_ref()?, p, &mut String::new(), 0) } -/// One document a panel shows as a tab of its own (the Timeline: one tab per open comp, as in -/// After Effects). -#[derive(Debug, Clone, PartialEq)] -pub struct DocTab { - pub id: u64, - pub title: String, - /// The comp's label colour. - pub swatch: egui::Color32, - /// The document the panel shows now. - pub active: bool, -} - -/// What the Timeline's comp tabs did this frame. -#[derive(Debug, Clone, PartialEq)] -pub enum DocAction { - /// Show comp `id`. - Activate(u64), - /// Close comp `id`'s Timeline (its ×, or a middle click). - Close(u64), -} - -/// Room around a tab's label, as craft-ui gives its dock tabs. -const TAB_PADDING: f32 = 24.0; -/// Width of the » button that lists the comp tabs with no room in the strip. -const DOC_OVERFLOW: f32 = 22.0; -/// Room for the × after a comp's name. Every comp tab keeps it, so a tab keeps its width when it -/// is shown or hovered. -const DOC_CLOSE: f32 = 16.0; - -/// A comp tab's text: the label swatch, then the name, as the panel tabs with a swatch show it. -fn doc_job(doc: &DocTab, font: &egui::FontId, color: egui::Color32) -> egui::text::LayoutJob { - let mut job = egui::text::LayoutJob::default(); - job.append("\u{25a0} ", 0.0, egui::TextFormat::simple(font.clone(), doc.swatch)); - job.append(&doc.title, 0.0, egui::TextFormat::simple(font.clone(), color)); - job -} - -/// The width of one line of `job` at the fonts' current size. -fn text_width(ctx: &egui::Context, job: egui::text::LayoutJob) -> f32 { - ctx.fonts_mut(|f| f.layout_job(job)).size().x -} - -/// The width each comp tab asks for in the Timeline group's tab row. -pub fn doc_widths(ctx: &egui::Context, docs: &[DocTab], font: &egui::FontId) -> Vec { - docs.iter().map(|d| text_width(ctx, doc_job(d, font, egui::Color32::WHITE)) + TAB_PADDING + DOC_CLOSE).collect() -} - -/// The × of comp tab `doc` at `rect`, clipped to `clip`; true when clicked. `shown` is the comp -/// the Timeline shows while it is the group's shown panel. Automation: -/// `panel.tab.Timeline..close`, and `panel.tab.Timeline.close` for the shown comp's. -fn doc_close( - ui: &mut egui::Ui, - rect: Rect, - clip: Rect, - doc: &DocTab, - shown: bool, - style: &craft_ui::docking::DockStyle, - reg: &mut crate::automation::Registry, -) -> bool { - let timeline = PanelKind::Timeline.id(); - let hit = ui.interact(rect.expand(2.0), egui::Id::unique(("comp-tab-close", doc.id)), Sense::click()); - hit.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, hit.enabled(), "Close")); - let cc = if hit.hovered() { style.text } else { style.inactive_text }; - let k = 3.5; - let painter = ui.painter().with_clip_rect(clip); - painter.line_segment([rect.center() + vec2(-k, -k), rect.center() + vec2(k, k)], Stroke::new(1.2, cc)); - painter.line_segment([rect.center() + vec2(-k, k), rect.center() + vec2(k, -k)], Stroke::new(1.2, cc)); - reg.add_response(&format!("panel.tab.{timeline}.{}.close", doc.id), &hit, "Close"); - if shown { - reg.add_response(&format!("panel.tab.{timeline}.close"), &hit, "Close"); - } - hit.clicked() -} - -/// Draw the Timeline's comp tabs into `strip`, the part of the Timeline group's tab row after its -/// panel tabs. Each is a tab like the panel tabs: the comp's label swatch and name, then a × -/// that closes the comp's Timeline: always on the shown comp while the Timeline is the group's -/// shown panel (`selected`), on the other comp tabs while the pointer is over them. Tabs that do -/// not fit go to a » menu at the end; the shown comp's tab always stays in the row. Shift+, and -/// Shift+. step through every open comp. Automation: `panel.tab.Timeline.`, the ×s (see -/// [`doc_close`]), `panel.tab.Timeline.more` for », and `panel.tab.Timeline.more.` for its -/// items. -pub fn doc_tabs( - ui: &mut egui::Ui, - strip: Rect, - docs: &[DocTab], - selected: bool, - style: &craft_ui::docking::DockStyle, - reg: &mut crate::automation::Registry, -) -> Vec { - let mut out = Vec::new(); - let timeline = PanelKind::Timeline.id(); - let widths = doc_widths(ui.ctx(), docs, &style.font); - let active = docs.iter().position(|d| d.active).unwrap_or(0); - let fit = craft_ui::tabs::fit_whole(&widths, active, strip.width(), DOC_OVERFLOW); - let clip = strip.intersect(ui.clip_rect()); - let mid = strip.center().y; - let mut x = strip.min.x; - for (index, width) in &fit.shown { - let Some(doc) = docs.get(*index) else { continue }; - let tab = Rect::from_min_size(pos2(x, strip.min.y), vec2(*width, strip.height())); - x += width; - let on = selected && doc.active; - let color = if on { style.text } else { style.inactive_text }; - let mut job = doc_job(doc, &style.font, color); - job.wrap = egui::text::TextWrapping { - max_width: (tab.width() - TAB_PADDING - DOC_CLOSE).max(0.0), - max_rows: 1, - break_anywhere: true, - overflow_character: Some('\u{2026}'), - }; - let galley = ui.fonts_mut(|f| f.layout_job(job)); - let label_end = tab.min.x + TAB_PADDING * 0.5 + galley.size().x; - let resp = craft_ui::tabs::Tab::new(egui::Id::unique(("comp-tab", doc.id)), &doc.title, on).focus_stroke(Stroke::new(1.0, style.accent)).show_at( - ui, - tab, - |ui, response| { - let painter = ui.painter().with_clip_rect(tab.intersect(clip)); - painter.rect_filled(tab, 0.0, if on || response.hovered() { style.active_background } else { style.tab_background }); - painter.galley(pos2(tab.min.x + TAB_PADDING * 0.5, mid - galley.size().y * 0.5), galley.clone(), color); - }, - ); - let resp = if galley.elided { resp.on_hover_text(&doc.title) } else { resp }; - reg.add_response(&format!("panel.tab.{timeline}.{}", doc.id), &resp, &doc.title); - // After the tab, so the × takes the clicks over it. - if on || ui.rect_contains_pointer(tab.intersect(clip)) { - let cr = Rect::from_center_size(pos2(label_end + DOC_CLOSE / 2.0, mid), vec2(10.0, 10.0)); - if doc_close(ui, cr, tab.intersect(clip), doc, on, style, reg) { - out.push(DocAction::Close(doc.id)); - } - } - if resp.clicked() { - out.push(DocAction::Activate(doc.id)); - } - if resp.middle_clicked() { - out.push(DocAction::Close(doc.id)); - } - } - if !fit.overflow.is_empty() && fit.overflow_width > 0.0 { - let more = Rect::from_min_size(pos2(x, strip.min.y), vec2(fit.overflow_width, strip.height())); - let resp = ui.interact(more, egui::Id::unique("comp-tabs-more"), Sense::click()); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, resp.enabled(), "More compositions")); - reg.add_response(&format!("panel.tab.{timeline}.more"), &resp, "More compositions"); - let color = if resp.hovered() { style.text } else { style.inactive_text }; - ui.painter().with_clip_rect(more.intersect(clip)).text(more.center(), Align2::CENTER_CENTER, "\u{bb}", style.font.clone(), color); - egui::Popup::menu(&resp).show(|ui| { - egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| { - for index in &fit.overflow { - let Some(doc) = docs.get(*index) else { continue }; - let item = ui.button(doc_job(doc, &style.font, style.text)); - item.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, item.enabled(), &doc.title)); - reg.add_response(&format!("panel.tab.{timeline}.more.{}", doc.id), &item, &doc.title); - if item.clicked() { - out.push(DocAction::Activate(doc.id)); - ui.close(); - } - } - }); - }); - } - out -} - /// A panel lock button (Composition viewers and the Timeline keep their comp while locked, /// Effect Controls its layer): a closed padlock while locked, an open one while unlocked. /// Returns true when clicked. Automation: `panel.tab..lock`. @@ -718,11 +552,11 @@ pub fn placeholder(ui: &mut egui::Ui, rect: Rect, t: &Tokens, text: &str) { mod tests { use super::*; use PanelKind::*; + use craft_behavior::DockSide; use craft_behavior::dock::{Action, DockPlacement}; - use craft_ui::docking::Zone; fn apply(w: &mut Workspace, action: Action) { - w.apply(action, permissions).unwrap(); + w.apply(action, false, permissions).unwrap(); } /// Only the title changes: existing saved workspace layouts still deserialize. @@ -759,7 +593,7 @@ mod tests { } for name in WORKSPACES { let layout = workspace(name); - assert!(layout.root.iter().chain(layout.floating.iter().map(|f| &f.root)).all(no_stack), "{name}"); + assert!(layout.root.iter().all(no_stack), "{name}"); } } @@ -767,15 +601,13 @@ mod tests { fn default_right_column_is_a_short_preview_frame_over_the_properties_frame() { let default = workspace("Default"); let Some(Node::Split { second, size: SplitSize::FixedSecond(300.0), .. }) = &default.root else { panic!("{default:?}") }; - let Node::Split { axis: Axis::Y, size: SplitSize::FixedFirst(PREVIEW_FRAME), first, second } = second.as_ref() else { - panic!("{second:?}") - }; + let Node::Split { axis: Axis::Y, size: SplitSize::FixedFirst(PREVIEW_FRAME), first, second, .. } = second.as_ref() else { panic!("{second:?}") }; assert_eq!(**first, tabs(&[Preview], 0)); assert_eq!(**second, tabs(&[Properties, Align, Audio, EffectsPresets], 0)); let mut w = Workspace::new(default); assert!(w.is_visible(Preview) && w.is_visible(Properties) && !w.is_visible(Align)); // The Properties frame takes tabs; the Preview frame stays a frame of its own. - apply(&mut w, Action::Move { panel: Project, anchor: Properties, placement: DockPlacement::Tab { before: None } }); + apply(&mut w, Action::move_beside(Project, Properties, DockPlacement::tab(None))); assert_eq!(w.group_of(Project), vec![Properties, Align, Audio, EffectsPresets, Project]); assert_eq!(w.group_of(Preview), vec![Preview]); } @@ -783,35 +615,35 @@ mod tests { #[test] fn panels_split_off_and_join_tab_groups() { let mut w = docked(hsplit(SplitSize::FixedFirst(300.0), tabs(&[Project, EffectControls], 0), tabs(&[Composition, Layer], 0))); - apply(&mut w, Action::Move { panel: EffectControls, anchor: Composition, placement: DockPlacement::Split(Zone::Right) }); + apply(&mut w, Action::move_beside(EffectControls, Composition, DockPlacement::Split(DockSide::End))); assert_eq!(w.group_of(EffectControls), vec![EffectControls]); assert_eq!(w.group_of(Project), vec![Project]); - apply(&mut w, Action::Move { panel: EffectControls, anchor: Composition, placement: DockPlacement::Tab { before: Some(Layer) } }); + apply(&mut w, Action::move_beside(EffectControls, Composition, DockPlacement::tab(Some(Layer)))); assert_eq!(w.group_of(Composition), vec![Composition, EffectControls, Layer]); assert!(w.is_visible(EffectControls)); // A rejected move (onto itself, onto a closed panel) changes nothing. let before = w.clone(); - assert!(w.apply(Action::Move { panel: Project, anchor: Info, placement: DockPlacement::Split(Zone::Left) }, permissions).is_err()); + assert!(w.apply(Action::move_beside(Project, Info, DockPlacement::Split(DockSide::Start)), false, permissions).is_err()); assert_eq!(w, before); } #[test] fn closed_panels_reopen_where_they_were_docked_or_floating() { let mut w = Workspace::new(workspace("Standard")); - apply(&mut w, Action::Close { panel: Info }); + apply(&mut w, Action::close(Info)); assert!(!w.is_open(Info)); - w.set_visible(Info, true, None, permissions).unwrap(); + w.set_visible(Info, true, None, false, permissions).unwrap(); assert_eq!(w.group_of(Info), vec![Info, Audio]); - apply(&mut w, Action::Float { panel: Audio, rect: [40.0, 50.0, 300.0, 200.0] }); - apply(&mut w, Action::Close { panel: Audio }); - w.set_visible(Audio, true, None, permissions).unwrap(); + apply(&mut w, Action::float(Audio, Rect::from_min_size(pos2(40.0, 50.0), vec2(300.0, 200.0)))); + apply(&mut w, Action::close(Audio)); + w.set_visible(Audio, true, None, false, permissions).unwrap(); assert!(w.is_floating(Audio)); // Closing an earlier, inactive tab keeps the shown panel. let mut w = docked(tabs(&[Properties, Align, EffectsPresets], 2)); - apply(&mut w, Action::Close { panel: Properties }); + apply(&mut w, Action::close(Properties)); assert!(w.is_visible(EffectsPresets)); // A panel never laid out opens beside its anchor. - apply(&mut w, Action::Open { panel: History, anchor: Some(Align) }); + apply(&mut w, Action::open(History, Some(Align))); assert_eq!(w.group_of(History), vec![Align, EffectsPresets, History]); assert_eq!(referenced_panels(&w).iter().filter(|p| **p == Properties).count(), 1, "the closed panel is still known"); } diff --git a/crates/ui-egui/src/dock_command.rs b/crates/ui-egui/src/dock_command.rs new file mode 100644 index 000000000..35fd4fb7e --- /dev/null +++ b/crates/ui-egui/src/dock_command.rs @@ -0,0 +1,466 @@ +//! EffectCraft's docking command vocabulary: `window.panel.*` and `ui.dock`, as the control +//! channel, the menus and the dock area's own changes write them. Each command becomes the +//! craft-behavior layout actions it stands for on the current workspace. + +use craft_behavior::DockSide; +use craft_behavior::dock::{Action, DockEdge, DockError, DockPlacement, Layout, PanelPlace, SplitSize, Target, node_at}; +use craft_ui::docking::FloatSpace; +use egui::{Rect, pos2, vec2}; +use serde::{Deserialize, Deserializer}; + +use crate::dock::{Node, PanelKind, Workspace}; + +/// A drop zone by name. PascalCase names of the side zones also parse. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ZoneName { + Tab, + #[serde(alias = "Center")] + Center, + #[serde(alias = "Left")] + Left, + #[serde(alias = "Right")] + Right, + #[serde(alias = "Top")] + Top, + #[serde(alias = "Bottom")] + Bottom, + Above, + Below, +} + +/// A present field, `null` included: `Some(None)` for `null`, `None` when absent. +fn present<'de, D: Deserializer<'de>, T: Deserialize<'de>>(deserializer: D) -> Result, D::Error> { + T::deserialize(deserializer).map(Some) +} + +/// A required field that may be `null`. +fn required<'de, D: Deserializer<'de>, T: Deserialize<'de>>(deserializer: D) -> Result { + T::deserialize(deserializer) +} + +/// A `ui.dock` operation, tagged by `operation`. Rects are `[x, y, width, height]`. +#[derive(Clone, Debug, PartialEq, Deserialize)] +#[serde(tag = "operation", rename_all = "camelCase")] +pub enum DockOperation { + Open { + panel: PanelKind, + }, + Close { + panel: PanelKind, + }, + Activate { + panel: PanelKind, + }, + Float { + panel: PanelKind, + rect: [f32; 4], + }, + MoveFloating { + panel: PanelKind, + rect: [f32; 4], + }, + /// `zone` defaults to `center`; `before` only applies to a center or tab move. + Move { + panel: PanelKind, + target: PanelKind, + #[serde(default)] + zone: Option, + #[serde(default, deserialize_with = "present")] + before: Option>, + }, + SetStackOpen { + panel: PanelKind, + open: bool, + }, + /// `height` is required; `null` clears it. + ResizeStack { + panel: PanelKind, + #[serde(deserialize_with = "required")] + height: Option, + }, + ResizeSplit { + path: Vec, + size: SplitSize, + }, +} + +/// `ui.dock`: a raw layout action or an operation. +#[derive(Clone, Debug, PartialEq, Deserialize)] +#[serde(untagged)] +pub enum UiDock { + Action { action: Action }, + Operation(DockOperation), +} + +/// A docking command, tagged by `command` (its id). +#[derive(Clone, Debug, PartialEq, Deserialize)] +#[serde(tag = "command")] +pub enum DockCommand { + /// A raw layout action. + #[serde(rename = "window.panel.layout")] + Layout { action: Action }, + /// Move a panel (or its group, with `group`) next to `anchor`; `zone` defaults to `tab`. + #[serde(rename = "window.panel.move")] + Move { + panel: PanelKind, + anchor: PanelKind, + #[serde(default)] + zone: Option, + #[serde(default, deserialize_with = "present")] + before: Option>, + #[serde(default)] + group: bool, + #[serde(default)] + placement: Option>, + }, + /// Float a panel, its group or its column; given values replace the rect's. + #[serde(rename = "window.panel.float")] + Float { + panel: PanelKind, + #[serde(default)] + x: Option, + #[serde(default)] + y: Option, + #[serde(default)] + width: Option, + #[serde(default)] + height: Option, + #[serde(default)] + group: bool, + #[serde(default)] + column: bool, + }, + /// Dock a panel: beside `anchor` in `zone` (default `tab`), as the last column of the dock on + /// `side`, along an outer edge (a side `zone` alone), or back into the docked layout. + #[serde(rename = "window.panel.dock")] + Dock { + panel: PanelKind, + #[serde(default)] + anchor: Option, + #[serde(default)] + zone: Option, + #[serde(default, deserialize_with = "present")] + before: Option>, + #[serde(default)] + group: bool, + #[serde(default)] + column: bool, + #[serde(default)] + side: Option, + }, + #[serde(rename = "window.panel.activate")] + Activate { panel: PanelKind }, + #[serde(rename = "window.panel.close")] + Close { panel: PanelKind }, + #[serde(rename = "window.panel.closeGroup")] + CloseGroup { panel: PanelKind }, + #[serde(rename = "window.panel.closeOthers")] + CloseOthers { panel: PanelKind }, + /// Minimize or restore the panel's group; without `minimized` it toggles. + #[serde(rename = "window.panel.minimize")] + Minimize { + panel: PanelKind, + #[serde(default)] + minimized: Option, + }, + /// Collapse the panel's column to icons or expand it; without `iconic` it toggles. + #[serde(rename = "window.panel.iconic")] + Iconic { + panel: PanelKind, + #[serde(default)] + iconic: Option, + }, + /// The panel in a floating window of its own (`native` true, the default) or docked again. + #[serde(rename = "window.panel.window")] + Window { + panel: PanelKind, + #[serde(default)] + native: Option, + }, + #[serde(rename = "ui.dock")] + UiDock(UiDock), +} + +/// The size a command floats a panel at when the dock has drawn nothing yet. +const DEFAULT_FLOAT: egui::Vec2 = vec2(420.0, 320.0); + +/// `[x, y, width, height]` as a rect. +pub fn rect_of([x, y, width, height]: [f32; 4]) -> Rect { + Rect::from_min_size(pos2(x, y), vec2(width, height)) +} + +/// How much of the layout a command moves. +#[derive(Clone, Copy)] +enum Unit { + Panel, + Group, + Column, +} + +impl Unit { + fn of(group: bool, column: bool) -> Self { + if column { + Self::Column + } else if group { + Self::Group + } else { + Self::Panel + } + } + + /// The action that moves this unit of `panel` to `to`. A floating panel's column is its whole window. + fn to(self, layout: &Layout, panel: PanelKind, to: Target) -> Action { + let floating = matches!(layout.place(&panel), Some(PanelPlace::Floating { .. })); + match (self, to) { + (Self::Panel, Target::At { anchor, placement, .. }) => Action::move_beside(panel, anchor, placement), + (Self::Panel, to) => Action::move_panel(panel, to), + (Self::Group, to) => Action::move_group(panel, to), + (Self::Column, to) if floating => Action::move_window(panel, to), + (Self::Column, to) => Action::move_column(panel, to), + } + } + + /// The panels that move with `panel`. + fn members(self, layout: &Layout, panel: PanelKind) -> Vec { + let place = layout.place(&panel); + match self { + Self::Panel => vec![panel], + Self::Group => match place.as_ref() { + Some(PanelPlace::Node(_)) => match place.as_ref().and_then(|place| layout.node_of(place)) { + Some(Node::Tabs { panels, .. }) => panels.clone(), + _ => vec![panel], + }, + Some(place) => layout.group(place).map(|group| group.panels.clone()).unwrap_or_else(|| vec![panel]), + None => vec![panel], + }, + Self::Column => match place.as_ref() { + Some(place @ (PanelPlace::Dock { .. } | PanelPlace::Floating { .. })) => { + layout.column(place).map(|column| column.panels().copied().collect()).unwrap_or_else(|| vec![panel]) + } + _ => vec![panel], + }, + } + } +} + +/// Where a command puts what it moves relative to `anchor`: `zone` (default `default`) and +/// `before`, with side zones mapped onto the anchor's container by [`DockPlacement::for_zone`]. +fn placement( + layout: &Layout, + anchor: PanelKind, + zone: Option, + before: Option>, + default: ZoneName, +) -> Result, DockError> { + let side = |side| DockPlacement::for_zone(layout, &anchor, side); + Ok(match (zone.unwrap_or(default), before) { + (ZoneName::Tab | ZoneName::Center, Some(before)) => DockPlacement::tab(before), + (ZoneName::Tab, None) => DockPlacement::tab(None), + (ZoneName::Center, None) => DockPlacement::Split(DockSide::Center), + (_, Some(_)) => return Err(DockError::InvalidPlacement), + (ZoneName::Left, None) => side(DockSide::Start)?, + (ZoneName::Right, None) => side(DockSide::End)?, + (ZoneName::Top, None) => side(DockSide::Top)?, + (ZoneName::Bottom, None) => side(DockSide::Bottom)?, + (ZoneName::Above, None) => DockPlacement::group(false, None), + (ZoneName::Below, None) => DockPlacement::group(true, None), + }) +} + +/// The panels of the last column of the dock on `side`, or `None` without such a dock. +fn last_column(layout: &Layout, side: DockEdge) -> Option> { + let path = layout.dock_path(side)?; + match node_at(layout.root.as_ref()?, &path)? { + Node::Dock { columns, .. } => Some(columns.last()?.panels().copied().collect()), + _ => None, + } +} + +impl DockCommand { + /// Every `window.panel.*` command id. + pub const IDS: &'static [&'static str] = &[ + "window.panel.layout", + "window.panel.move", + "window.panel.float", + "window.panel.dock", + "window.panel.activate", + "window.panel.close", + "window.panel.closeGroup", + "window.panel.closeOthers", + "window.panel.minimize", + "window.panel.iconic", + "window.panel.window", + ]; + + /// The command `id` with `params`. Its own `command` key is set from `id`. + pub fn parse(id: &str, params: &serde_json::Value) -> Result { + let mut tagged = if params.is_object() { params.clone() } else { serde_json::json!({}) }; + if let Some(fields) = tagged.as_object_mut() { + fields.insert("command".into(), serde_json::json!(id)); + } + serde_json::from_value(tagged).map_err(|error| error.to_string()) + } + + /// The raw layout action the command carries, if it is one. + pub fn raw_action(&self) -> Option<&Action> { + match self { + Self::Layout { action } | Self::UiDock(UiDock::Action { action }) => Some(action), + _ => None, + } + } + + /// The panel the command shows: opening or activating it, or docking it back into the layout. + pub fn shown(&self) -> Option { + match self { + Self::Activate { panel } + | Self::Dock { panel, anchor: None, side: None, .. } + | Self::UiDock(UiDock::Operation(DockOperation::Open { panel } | DockOperation::Activate { panel })) => Some(*panel), + _ => None, + } + } + + /// The outer edge `window.panel.dock` goes to: a side zone without an anchor or side. + pub fn edge(&self) -> Option { + match self { + Self::Dock { anchor: None, side: None, zone: Some(zone), .. } => match zone { + ZoneName::Left => Some(DockSide::Start), + ZoneName::Right => Some(DockSide::End), + ZoneName::Top => Some(DockSide::Top), + ZoneName::Bottom => Some(DockSide::Bottom), + _ => None, + }, + _ => None, + } + } + + /// The layout actions this command makes on `workspace`, to apply all or none. A panel or + /// anchor that is not shown is [`DockError::MissingPanel`] or [`DockError::MissingTarget`]. + /// `space` is where a float without a rect goes: the dock's last [`FloatSpace`]. + pub fn to_actions(&self, workspace: &Workspace, space: Option<&FloatSpace>) -> Result>, DockError> { + let layout = workspace.layout(); + let shown = |panel: &PanelKind| if layout.contains(panel) { Ok(()) } else { Err(DockError::MissingPanel) }; + let one = |action: Action| Ok(vec![action]); + match self { + Self::Layout { action } | Self::UiDock(UiDock::Action { action }) => one(action.clone()), + Self::Move { panel, anchor, zone, before, group, placement: given } => { + shown(panel)?; + let placement = match given { + Some(placement) => placement.clone(), + None => placement(layout, *anchor, *zone, *before, ZoneName::Tab)?, + }; + one(Unit::of(*group, false).to(layout, *panel, Target::at(*anchor, placement))) + } + Self::Float { panel, x, y, width, height, group, column } => { + shown(panel)?; + let given = [*x, *y, *width, *height]; + let rect = |base: Rect| { + let mut values = [base.min.x, base.min.y, base.width(), base.height()]; + for (value, given) in values.iter_mut().zip(given) { + *value = given.unwrap_or(*value); + } + rect_of(values) + }; + let unit = Unit::of(*group, *column); + let window = layout.floating.iter().find(|window| window.contains(panel)); + let lone = window.is_some_and(|window| window.panels().count() == 1); + let whole = window.is_some_and(|window| window.groups().len() == 1); + let placed = || { + let size = space.and_then(|space| space.panel(panel)).or(space.map(|space| space.default_size)).unwrap_or(DEFAULT_FLOAT); + rect(space.map_or_else(|| Rect::from_center_size(pos2(840.0, 510.0), size), |space| space.place(size))) + }; + match (unit, window.map(|window| window.rect)) { + (Unit::Panel, Some(base)) if lone => one(Action::move_floating(*panel, rect(base))), + (Unit::Column, Some(base)) => one(Action::move_floating(*panel, rect(base))), + (Unit::Group, Some(base)) if whole => one(Action::move_floating(*panel, rect(base))), + (Unit::Panel, _) => one(Action::float(*panel, placed())), + (unit, _) => one(unit.to(layout, *panel, Target::float(placed()))), + } + } + Self::Dock { panel, anchor, zone, before, group, column, side } => { + shown(panel)?; + let unit = Unit::of(*group, *column); + if let Some(anchor) = anchor { + let placement = placement(layout, *anchor, *zone, *before, ZoneName::Tab)?; + return one(unit.to(layout, *panel, Target::at(*anchor, placement))); + } + let members = unit.members(layout, *panel); + if let Some(side) = side { + let to = match last_column(layout, *side) { + Some(column) => match column.into_iter().find(|p| !members.contains(p)) { + Some(anchor) => Target::at(anchor, DockPlacement::column(true)), + // What moves already is that dock's last column. + None => return Ok(Vec::new()), + }, + None => Target::new_dock(*side), + }; + let unit = match (unit, &to) { + (Unit::Panel, Target::NewDock { .. }) if Unit::Group.members(layout, *panel).len() == 1 => Unit::Group, + (unit, _) => unit, + }; + return one(unit.to(layout, *panel, to)); + } + if let Some(zone) = self.edge() { + if before.is_some() { + return Err(DockError::InvalidPlacement); + } + // Every EffectCraft panel moves and closes: no edge narrows to a protected canvas. + let anchor = layout.edge_anchor(false, &|_| false, &|p| members.contains(p)).ok_or(DockError::MissingTarget)?; + return one(unit.to(layout, *panel, Target::at(anchor, DockPlacement::Edge(zone)))); + } + if !matches!(layout.place(panel), Some(PanelPlace::Floating { .. })) { + return Ok(Vec::new()); + } + let anchor = layout + .panels() + .into_iter() + .copied() + .filter(|p| !members.contains(p)) + .find(|p| !matches!(layout.place(p), Some(PanelPlace::Floating { .. }))) + .ok_or(DockError::MissingTarget)?; + one(unit.to(layout, *panel, Target::at(anchor, DockPlacement::tab(None)))) + } + Self::Activate { panel } => { + shown(panel)?; + one(Action::activate(*panel)) + } + Self::Close { panel } => one(Action::close(*panel)), + Self::CloseGroup { panel } => one(Action::close_group(*panel)), + Self::CloseOthers { panel } => one(Action::close_others(*panel)), + Self::Minimize { panel, minimized } => { + let place = layout.place(panel).ok_or(DockError::MissingPanel)?; + // An accordion entry is minimized while it is closed. + let current = match &place { + PanelPlace::Node(path) => match layout.root.as_ref().and_then(|root| node_at(root, path)) { + Some(Node::Stack { entries, .. }) => entries.iter().any(|entry| entry.panel == *panel && !entry.open), + _ => false, + }, + place => layout.group(place).is_some_and(|group| group.minimized), + }; + one(Action::set_minimized(*panel, minimized.unwrap_or(!current))) + } + Self::Iconic { panel, iconic } => { + let place = layout.place(panel).ok_or(DockError::MissingPanel)?; + let current = layout.column(&place).is_some_and(|column| column.iconic); + one(Action::set_iconic(*panel, iconic.unwrap_or(!current))) + } + // A floating window of its own is the app's (`EffectcraftApp::set_panel_window`). + Self::Window { .. } => Err(DockError::NotAllowed), + Self::UiDock(UiDock::Operation(operation)) => match operation { + DockOperation::Open { panel } | DockOperation::Activate { panel } => { + shown(panel)?; + one(Action::activate(*panel)) + } + DockOperation::Close { panel } => one(Action::close(*panel)), + DockOperation::Float { panel, rect } => one(Action::float(*panel, rect_of(*rect))), + DockOperation::MoveFloating { panel, rect } => one(Action::move_floating(*panel, rect_of(*rect))), + DockOperation::Move { panel, target, zone, before } => { + one(Action::move_beside(*panel, *target, placement(layout, *target, *zone, *before, ZoneName::Center)?)) + } + DockOperation::SetStackOpen { panel, open } => one(Action::set_stack_open(*panel, *open)), + DockOperation::ResizeStack { panel, height } => one(Action::resize_stack(*panel, *height)), + DockOperation::ResizeSplit { path, size } => one(Action::resize_split(path.clone(), *size)), + }, + } + } +} diff --git a/crates/ui-egui/src/dock_ui.rs b/crates/ui-egui/src/dock_ui.rs index 6e98e11ee..4f7556728 100644 --- a/crates/ui-egui/src/dock_ui.rs +++ b/crates/ui-egui/src/dock_ui.rs @@ -1,79 +1,35 @@ -//! EffectCraft's panels in craft-ui's shared docking. craft-ui draws the frames, tab strips, -//! stacked panels, floating windows, dividers and drop previews and owns the gestures (drag a tab -//! onto a group to tab it there or split it off to a side; hold Cmd/Ctrl at the release, or drop -//! outside every group, to float it). EffectCraft draws the panel bodies, the ≡ panel menu, the -//! Timeline's comp tabs and the viewer locks in each group header, and runs every layout change -//! through its command path (`window.dockAction`), so pointer, menu and control-channel changes -//! share one route. +//! EffectCraft's panels in craft-ui's shared docking. craft-ui's `DockArea` draws the frames, +//! tab strips (the Timeline's comp tabs included, as its panel's documents), stacked panels, +//! floating windows, dividers and drop previews and owns the gestures (drag a tab onto a group to +//! tab it there or split it off to a side; hold Cmd/Ctrl at the release, or drop outside every +//! group, to float it). EffectCraft draws the panel bodies and the viewer lock and ≡ panel menu in +//! each group header, and runs every layout change through its command path +//! (`window.dockAction`), so pointer, menu and control-channel changes share one route. -use crate::state::UiState; -use craft_behavior::dock::{Action, DockError, Floating, Node}; -use craft_ui::docking::{Divider, DockArea, DockCommand, DockContent, DockEvent, DockStyle, FloatSpace, Hit, ResizeEdge, UiDock}; -use egui::{Rect, Sense, Stroke, StrokeKind, pos2, vec2}; +use std::sync::Arc; + +use craft_behavior::dock::{Action, Floating}; +use craft_ui::contract::{Bind, BodyCx, PlainData, Tracked}; +use craft_ui::docking::{DividerKind, DockConfig, DockEvent, DockPanels, DockSource, FloatSpace, PanelDocument, PanelSpec, PanelSpecs, SourceKind}; +use craft_ui::patterns::dock::{DockArea, DockAreaOutput, WindowFiles}; +use craft_ui::runtime::windows::ResizeEdge; +use egui::{Rect, Sense, Stroke, StrokeKind, Ui, vec2}; use serde_json::{Value, json}; -use crate::dock::{self, DocAction, DocTab, PanelKind, Workspace, WorkspaceExt as _}; +use crate::dock::{self, PanelKind, Permissions, Workspace, WorkspaceExt as _}; +use crate::dock_command::DockCommand; use crate::icons::{self, Icon}; use crate::theme::Tokens; use crate::{EffectcraftApp, panels}; -/// The dock area's egui id; `DockArea::hit_rects` and `float_space` read by it. -pub fn area_id() -> egui::Id { - egui::Id::unique("effectcraft-docking") -} - -/// Width of the ≡ panel menu button at the end of each tab strip. +/// Width of the ≡ panel menu button in each group header. const MENU_W: f32 = 26.0; /// Width of the viewer lock before it. const LOCK_W: f32 = 18.0; -/// The smallest and largest native panel window, in points. -pub const PANEL_WINDOW_MIN: [f32; 2] = [160.0, 100.0]; -pub const PANEL_WINDOW_MAX: f32 = 16_384.0; -/// The farthest a native panel window may sit from the desktop origin, in points. -pub const PANEL_WINDOW_MAX_POS: f32 = 100_000.0; - -/// A native panel window's desktop rect made safe to hand to the windowing system: finite, with -/// a size within [`PANEL_WINDOW_MIN`]..=[`PANEL_WINDOW_MAX`] and a position within -/// ±[`PANEL_WINDOW_MAX_POS`] (hostile workspace files and bad monitor reports included). -pub fn sanitized_window_rect(rect: [f32; 4]) -> [f32; 4] { - let finite = |v: f32, fallback: f32| if v.is_finite() { v } else { fallback }; - let [x, y, w, h] = rect; - [ - finite(x, 0.0).clamp(-PANEL_WINDOW_MAX_POS, PANEL_WINDOW_MAX_POS), - finite(y, 0.0).clamp(-PANEL_WINDOW_MAX_POS, PANEL_WINDOW_MAX_POS), - finite(w, 420.0).clamp(PANEL_WINDOW_MIN[0], PANEL_WINDOW_MAX), - finite(h, 320.0).clamp(PANEL_WINDOW_MIN[1], PANEL_WINDOW_MAX), - ] -} - -/// How long to wait for the main window to report its frame before migrated native windows -/// keep their places as they are, in seconds. -const FRAME_REPORT_WAIT: f64 = 2.0; - -/// Moves the native rects of [`UiState::native_outer`]'s windows from the OS window's outer -/// position to its content position, by the main window's frame offset (`inner` less `outer`, -/// the main window's desktop rects): the earlier version's windows had the same OS title bar. -/// Without a report by [`FRAME_REPORT_WAIT`] (a backend without window positions), the places -/// stay as they are. -pub(crate) fn native_outer_to_content(ui: &mut UiState, outer: Option, inner: Option, now: f64) { - let offset = match (outer, inner) { - (Some(outer), Some(inner)) if outer.min.is_finite() && inner.min.is_finite() => inner.min - outer.min, - _ if now < FRAME_REPORT_WAIT => return, - _ => egui::Vec2::ZERO, - }; - let ids = std::mem::take(&mut ui.native_outer); - for window in ui.dock.layout.floating.iter_mut().filter(|w| ids.contains(&w.id)) { - if let Some([x, y, w, h]) = window.native { - window.native = Some(sanitized_window_rect([x + offset.x, y + offset.y, w, h])); - } - } -} - /// A new floating group's default rect near the centre of `screen`. -pub fn default_float_rect(screen: Rect) -> [f32; 4] { - let c = screen.center(); - [c.x - 210.0, c.y - 160.0, 420.0, 320.0] +pub fn default_float_rect(screen: Rect) -> Rect { + Rect::from_center_size(screen.center(), vec2(420.0, 320.0)) } /// A panel named by its title or id ("Effect Controls", "EffectControls") or its serialized @@ -92,8 +48,8 @@ fn check_raw_action(action: &Action) -> Result<(), String> { Ok(()) } -/// The docking commands: `window.dockAction {action}`, craft-ui's `window.panel.*` commands, -/// `ui.dock` and `ui.dock.reset`. `None` for any other id. +/// The docking commands: `window.dockAction {action}`, the `window.panel.*` commands, `ui.dock` +/// and `ui.dock.reset`. `None` for any other id. pub(crate) fn route(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option> { match id { "window.dockAction" => Some((|| { @@ -109,19 +65,14 @@ pub(crate) fn route(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, par Some(Ok(json!({"docking": app.ui.dock}))) } "ui.dock" => Some((|| { - let mut tagged = if params.is_object() { params.clone() } else { json!({}) }; - if let Some(fields) = tagged.as_object_mut() { - fields.insert("command".into(), json!("ui.dock")); - } - let command: DockCommand = serde_json::from_value(tagged).map_err(|error| format!("invalid ui.dock params: {error}"))?; + let command = DockCommand::parse("ui.dock", params).map_err(|error| format!("invalid ui.dock params: {error}"))?; app.run_dock_command(ctx, command)?; Ok(json!({"docking": app.ui.dock})) })()), - _ if id.starts_with("window.panel.") && DockCommand::::IDS.contains(&id) => Some((|| { - let mut tagged = if params.is_object() { params.clone() } else { json!({}) }; - if let Some(fields) = tagged.as_object_mut() { - fields.insert("command".into(), json!(id)); - // EffectCraft's panel names ("Effect Controls") as well as craft-ui's ids. + _ if DockCommand::IDS.contains(&id) => Some((|| { + let mut params = if params.is_object() { params.clone() } else { json!({}) }; + if let Some(fields) = params.as_object_mut() { + // EffectCraft's panel names ("Effect Controls") as well as the serialized ids. for key in ["panel", "anchor", "before"] { if let Some(name) = fields.get(key).and_then(Value::as_str) { let panel = PanelKind::from_name(name).ok_or(format!("unknown panel `{name}`"))?; @@ -129,7 +80,7 @@ pub(crate) fn route(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, par } } } - let command: DockCommand = serde_json::from_value(tagged).map_err(|error| format!("invalid docking command: {error}"))?; + let command = DockCommand::parse(id, ¶ms).map_err(|error| format!("invalid docking command: {error}"))?; app.run_dock_command(ctx, command)?; Ok(Value::Null) })()), @@ -154,43 +105,25 @@ impl EffectcraftApp { crate::menus::invoke(self, ctx, "window.dockAction", json!({"action": value})).map(|_| ()) } - /// Run a craft-ui docking command on the current workspace, all or nothing. Named - /// workspaces and Reset are EffectCraft's own (`window.workspace`, `window.resetWorkspace`). - pub(crate) fn run_dock_command(&mut self, ctx: &egui::Context, command: DockCommand) -> Result<(), String> { - if let DockCommand::Layout { action } | DockCommand::UiDock(UiDock::Action { action }) = &command { + /// Run a docking command on the current workspace, all or nothing. Named workspaces and + /// Reset are EffectCraft's own (`window.workspace`, `window.resetWorkspace`). + pub(crate) fn run_dock_command(&mut self, ctx: &egui::Context, command: DockCommand) -> Result<(), String> { + if let Some(action) = command.raw_action() { check_raw_action(action)?; } - if command.is_app_owned() { - if matches!(command, DockCommand::ResetWorkspace {}) { - let name = self.ui.workspace.clone(); - self.set_workspace(&name); - return Ok(()); - } - return Err("use the window.workspace commands for named workspaces".into()); + if let DockCommand::Window { panel, native } = command { + return self.set_panel_window(ctx, panel, native.or(Some(true))).map(drop); } // A closed panel opens through EffectCraft's own path, which puts it in its usual place // and runs the viewer and ScriptUI lifecycles. - let shown = match &command { - DockCommand::Activate { panel } | DockCommand::UiDock(UiDock::Operation(craft_ui::docking::DockOperation::Open { panel })) => Some(*panel), - DockCommand::UiDock(UiDock::Operation(craft_ui::docking::DockOperation::Activate { panel })) => Some(*panel), - _ => None, - }; - if let Some(panel) = shown.filter(|panel| !self.ui.dock.is_open(*panel)) { + if let Some(panel) = command.shown().filter(|panel| !self.ui.dock.is_open(*panel)) { self.show_panel(panel); - return Ok(()); - } - let space = craft_ui::docking::float_space(ctx, area_id()).unwrap_or_else(|| FloatSpace::new(ctx.content_rect())); - match command.to_actions(&self.ui.dock, false, &space) { - Ok(actions) => self.apply_dock_all(actions), - // Showing a hidden panel at an edge, and Lock, change more than the layout. - Err(DockError::NotAllowed) => { - let mut workspace = self.ui.dock.clone(); - let closed = command.apply(&mut workspace, false, &space, dock::permissions).map_err(|error| error.to_string())?; - self.commit_workspace(workspace, &closed, true); - Ok(()) + if command.edge().is_none() { + return Ok(()); } - Err(error) => Err(error.to_string()), } + let actions = command.to_actions(&self.ui.dock, self.live_dock.float_space.as_ref()).map_err(|error| error.to_string())?; + self.apply_dock_all(actions) } pub fn apply_dock(&mut self, action: Action) -> Result<(), String> { @@ -214,9 +147,9 @@ impl EffectcraftApp { | Action::MoveColumn { .. } ); let closing = matches!(&action, Action::Close { .. } | Action::CloseGroup { .. } | Action::CloseWindow { .. } | Action::CloseOthers { .. }); - let docked = workspace.layout.root.is_some(); - closed.extend(workspace.apply(action, dock::permissions).map_err(|error| error.to_string())?); - if !closing && docked && workspace.layout.root.is_none() { + let docked = workspace.layout().root.is_some(); + closed.extend(workspace.apply(action, self.ui.dock_locked, dock::permissions).map_err(|error| error.to_string())?); + if !closing && docked && workspace.layout().root.is_none() { return Err("the last docked panel must remain in the workspace".into()); } } @@ -245,7 +178,7 @@ impl EffectcraftApp { /// Close a panel wherever it is (docked or floating). A rejected close changes nothing. pub fn close_panel(&mut self, p: PanelKind) { if self.ui.dock.is_open(p) { - let _ = self.apply_dock(Action::Close { panel: p }); + let _ = self.apply_dock(Action::close(p)); } } @@ -259,18 +192,16 @@ impl EffectcraftApp { pos.and_then(|p| self.dock_rects.iter().rev().find(|(_, r)| r.contains(p)).map(|(k, _)| *k)).unwrap_or(self.ui.focused) } - /// Whether panel `p` is in a floating window with a desktop place: its own OS window on - /// desktop (craft-ui `native-windows`); on the web and in embedded viewports the window - /// stays in the page and the place is kept for a desktop session. + /// Whether panel `p` is in a floating window: on desktop each is an OS window of its own + /// (`DockConfig::native_windows`), which can go on another monitor; on the web and in + /// embedded viewports it stays in the page. pub fn in_panel_window(&self, p: PanelKind) -> bool { - self.ui.dock.layout.floating.iter().any(|w| w.contains(&p) && w.native.is_some()) + self.ui.dock.is_floating(p) } - /// Move panel `p` into a floating window of its own, which on desktop is an OS window that - /// can go on another monitor, or back into the main window (`window` false), where it joins - /// the first docked group. `None` toggles. A docked panel is undocked first, and its window - /// opens over the panel's place in the main window. Returns whether `p` is now in a window - /// of its own. + /// Move panel `p` into a floating window of its own, or back into the main window + /// (`window` false), where it joins the first docked group. `None` toggles. A docked panel + /// floats over its place in the main window. Returns whether `p` is now in a window. pub fn set_panel_window(&mut self, ctx: &egui::Context, p: PanelKind, window: Option) -> Result { let current = self.in_panel_window(p); let window = window.unwrap_or(!current); @@ -278,36 +209,28 @@ impl EffectcraftApp { return Ok(current); } if !window { - // On desktop every floating window is an OS window, so the way back is docking. - let anchor = self.ui.dock.layout.root.as_ref().and_then(|root| { + let anchor = self.ui.dock.layout().root.as_ref().and_then(|root| { let mut panels = Vec::new(); dock::node_panels(root, &mut panels); panels.into_iter().find(|panel| *panel != p) }); let actions = match anchor { - Some(anchor) => vec![Action::Move { panel: p, anchor, placement: craft_behavior::dock::DockPlacement::Tab { before: None } }], + Some(anchor) => vec![Action::move_beside(p, anchor, craft_behavior::dock::DockPlacement::tab(None))], // Nothing is docked: the panel becomes the docked layout. - None => vec![Action::Close { panel: p }, Action::Open { panel: p, anchor: None }], + None => vec![Action::close(p), Action::open(p, None)], }; let mut workspace = self.ui.dock.clone(); // One transaction, so the panel is never reported closed and keeps its state. - let closed = workspace.apply_all(actions, dock::permissions).map_err(|_| format!("can't dock {}", p.title()))?; + let closed = workspace.apply_all(actions, self.ui.dock_locked, dock::permissions).map_err(|_| format!("can't dock {}", p.title()))?; self.commit_workspace(workspace, &closed, true); return Ok(false); } - if !self.ui.dock.is_floating(p) { - if !self.ui.dock.is_docked(p) { - return Err(format!("{} is not open", p.title())); - } - let rect = default_float_rect(ctx.input_for(egui::ViewportId::ROOT, |i| i.content_rect())); - self.apply_dock(Action::Float { panel: p, rect }).map_err(|_| format!("can't undock {}", p.title()))?; + if !self.ui.dock.is_docked(p) { + return Err(format!("{} is not open", p.title())); } - let Some([x, y, w, h]) = self.ui.dock.layout.floating.iter().find(|f| f.contains(&p)).map(|f| f.rect) else { - return Err(format!("can't undock {}", p.title())); - }; - let origin = ctx.input_for(egui::ViewportId::ROOT, |i| i.viewport().inner_rect.map(|r| r.min)).unwrap_or(pos2(0.0, 0.0)); - let rect = sanitized_window_rect([origin.x + x, origin.y + y, w, h]); - self.apply_dock(Action::SetNative { panel: p, rect: Some(rect) })?; + let place = self.dock_rects.iter().find(|(panel, _)| *panel == p).map(|(_, rect)| *rect); + let rect = place.unwrap_or_else(|| default_float_rect(ctx.input_for(egui::ViewportId::ROOT, |i| i.content_rect()))); + self.apply_dock(Action::float(p, rect)).map_err(|_| format!("can't undock {}", p.title()))?; if self.ui.maximized == Some(p) { self.ui.maximized = None; } @@ -342,46 +265,77 @@ impl EffectcraftApp { out } - /// A comp's label colour as a tab swatch (faint without a label). - fn comp_swatch(&self, cid: effectcraft_engine::project::ItemId) -> egui::Color32 { + /// A comp's label colour as a tab swatch; `None` without a label (the theme's empty swatch). + fn comp_swatch(&self, cid: effectcraft_engine::project::ItemId) -> Option { match self.session.project.item(cid).map(|i| i.label) { - Some(l) if l != effectcraft_engine::color::Label::None => self.tokens.label(l), - _ => self.tokens.text_faint, + Some(l) if l != effectcraft_engine::color::Label::None => Some(self.tokens.label(l)), + _ => None, } } /// The Timeline's comp tabs: one per open comp, as in After Effects (opening a precomp adds a /// tab next to its parent's instead of replacing it). - fn tab_docs(&self) -> Vec { + fn tab_docs(&self) -> Vec { let st = &self.session.state; st.open_comps .iter() .filter_map(|id| { let it = self.session.project.item(*id).filter(|i| i.as_comp().is_some())?; - Some(DocTab { id: id.0, title: it.name.clone(), swatch: self.comp_swatch(*id), active: st.active_comp == Some(*id) }) + Some(DocRow { id: id.0, label: it.name.clone(), swatch: self.comp_swatch(*id).map(rgba), shown: st.active_comp == Some(*id) }) }) .collect() } /// The label-colour swatch before a tab's name: each Composition viewer's comp, and Effect /// Controls' (and with Use Label Color for Related Tabs, Properties') selected layer. - fn tab_swatches(&self) -> Vec<(PanelKind, egui::Color32)> { + fn tab_swatches(&self) -> Vec<(PanelKind, Option)> { let mut v = Vec::new(); for id in std::iter::once(0).chain(self.ui.viewers.keys().copied().filter(|v| *v != 0)) { - let swatch = panels::viewers::comp_of(self, id).map_or(self.tokens.text_faint, |c| self.comp_swatch(c)); + let swatch = panels::viewers::comp_of(self, id).and_then(|c| self.comp_swatch(c)); v.push((panels::viewers::panel(id), swatch)); } if let Some(l) = self.session.active_comp().and_then(|c| self.session.state.selected_layers.first().and_then(|id| c.layer(*id))) && l.label != effectcraft_engine::color::Label::None { - v.push((PanelKind::EffectControls, self.tokens.label(l.label))); + v.push((PanelKind::EffectControls, Some(self.tokens.label(l.label)))); if self.session.prefs.appearance.use_label_color_for_tabs { - v.push((PanelKind::Properties, self.tokens.label(l.label))); + v.push((PanelKind::Properties, Some(self.tokens.label(l.label)))); } } v } + /// The panel name the Window menu uses; `Markers` is only in the panel catalog, and the two + /// panels in neither (`History`, `ScriptUI Panel`) keep their English names. + fn logical_label(panel: PanelKind) -> String { + let title = panel.title(); + let listed = crate::i18n::command_label("window.panel", title); + if listed == title { crate::i18n::tr(title).to_string() } else { listed.to_string() } + } + + /// Read the panels' tab names, swatches and the Timeline's comps into the dock's spec model, + /// moving its revision only when one changed. + fn refresh_dock_specs(&mut self) { + let titles = self.tab_titles(); + let swatches = self.tab_swatches(); + let docs = self.tab_docs(); + let rows: Vec = self + .ui + .dock + .panels() + .into_iter() + .map(|panel| SpecRow { + panel: panel.id(), + label: titles.iter().find(|(p, _)| *p == panel).map_or_else(|| Self::logical_label(panel), |(_, t)| t.clone()), + swatch: swatches.iter().find(|(p, _)| *p == panel).map(|(_, swatch)| swatch.map(rgba)), + documents: if panel == PanelKind::Timeline { docs.clone() } else { Vec::new() }, + }) + .collect(); + if self.live_dock.specs.rows != rows { + self.live_dock.specs.rows = rows; + } + } + /// Draw panel `p`'s body in `rect`: register its automation region, put the Composition Navigator above an active /// viewer when a nested-comp flow exists, then call the panel's `show` and (for a viewer) the sketch overlay. fn panel_body(&mut self, ui: &mut egui::Ui, p: PanelKind, rect: Rect) { @@ -424,16 +378,12 @@ impl EffectcraftApp { self.dialog.is_some() || panels::dialogs::modal_open(ctx) || file_dialog } - /// Draw the Home screen or workspace in `body`. Shared craft-ui docking owns the dock tree, - /// group chrome, tab dragging and floating native windows; this adapter draws panel bodies, - /// applies the returned events/actions and shows the panel menu. + /// Draw the Home screen or workspace in `body`. craft-ui's `DockArea` owns the dock tree, + /// group chrome, tab dragging and floating native windows; this adapter keeps the panels' + /// specs, draws their bodies and headers, and applies the returned actions and events. pub(crate) fn dock_area(&mut self, ui: &mut egui::Ui, body: Rect) { let t = self.tokens; let ctx = ui.ctx().clone(); - if !self.ui.native_outer.is_empty() { - let (outer, inner, now) = ctx.input_for(egui::ViewportId::ROOT, |i| (i.viewport().outer_rect, i.viewport().inner_rect, i.time)); - native_outer_to_content(&mut self.ui, outer, inner, now); - } if self.ui.start_screen { // Home covers the whole workspace, as in After Effects (the panels wait behind it). let mut child = ui.new_child(egui::UiBuilder::new().max_rect(body).id_salt("home")); @@ -441,33 +391,33 @@ impl EffectcraftApp { panels::home::show(self, &mut child, body); return; } - let style = dock_style(ui, &t); + self.refresh_dock_specs(); + let shown = self.live_dock.shown(&self.ui.dock); + // The specs leave the app while its panels borrow it, and come back with their revision. + let specs = std::mem::take(&mut self.live_dock.specs); let maximized = self.ui.maximized.filter(|m| self.ui.dock.is_docked(*m)); - let mut area = DockArea::new(area_id()).float_bounds(body).maximized(maximized).locked(self.ui.dock.locked).input_blocked(self.floats_blocked(&ctx)); - if let Some(panel) = self.pending_panel_raise.take() { - area = area.raise_panel(panel); - } - let layout = self.ui.dock.layout.clone(); + let locked = self.ui.dock_locked; + let raise = self.pending_panel_raise.take(); + let ime = NativeIme::new(&shown.layout().floating, &self.live_dock.windows, &self.unpublished_viewports); let mut child = ui.new_child(egui::UiBuilder::new().max_rect(body).id_salt("effectcraft-dock-area")); child.set_clip_rect(body.intersect(ui.clip_rect())); - let docs = self.tab_docs(); - let ime = NativeIme::new(&layout.floating, &self.unpublished_viewports); - let mut content = EffectContent { - titles: self.tab_titles(), - swatches: self.tab_swatches(), - docs, - ctx: ctx.clone(), - style: style.clone(), - app: self, - tokens: t, - doc_actions: Vec::new(), - locks: Vec::new(), - menu: None, - bodies: Vec::new(), - ime, + let mut panels = EffectPanels { app: &mut *self, tokens: t, locks: Vec::new(), menu: None, bodies: Vec::new(), ime }; + let output = { + let mut area = DockArea::new("Panels", Bind::given(Arc::clone(&shown)), &specs, &mut panels, dock_config()); + if let Some(panel) = maximized { + area = area.maximized(panel); + } + if locked { + area = area.locked(); + } + if let Some(panel) = raise { + area = area.raise(panel); + } + area.show(&mut child) }; - let mut output = area.show_content(&mut child, &layout, &style, &mut content); - let EffectContent { doc_actions, locks, menu, bodies, ime, .. } = content; + let EffectPanels { locks, menu, bodies, ime, .. } = panels; + self.live_dock.specs = specs; + let DockAreaOutput { actions, requested, events, focused, picked, error, float_space, windows, window_files, sources, .. } = output; self.dock_rects = bodies; self.unpublished_viewports = ime.unpublished(); // A window that closed or docked takes its composition with it. @@ -476,22 +426,49 @@ impl EffectcraftApp { for viewport in gone { panels::viewer_text::end_viewport(self, &ctx, viewport); } - self.forward_window_input(&ctx, std::mem::take(&mut output.forwarded_events), std::mem::take(&mut output.window_files)); - if let Some(panel) = output.focused { + if float_space.is_some() { + self.live_dock.float_space = float_space; + } + self.forward_window_input(&ctx, &windows, window_files); + self.live_dock.windows = windows; + // Key focus moving to a group, or a tab picked, focuses that panel. + let moved = focused != self.live_dock.focused; + self.live_dock.focused = focused; + if let Some(panel) = picked.or(focused.filter(|_| moved)) { self.focus_panel(&ctx, panel); } - if let Some(error) = output.error { - self.ui.status = error.to_string(); + if let Some(error) = error { + self.ui.status = error.error.to_string(); } - for event in output.events { - if let DockEvent::ToggleMaximize { panel } = event { - self.toggle_maximize(panel); + for event in events { + match event { + DockEvent::ToggleMaximize { panel, .. } => self.toggle_maximize(panel), + // The Timeline's comp tabs: show that comp / close its Timeline. + DockEvent::DocumentPicked { panel: PanelKind::Timeline, document, .. } => { + self.focus_panel(&ctx, PanelKind::Timeline); + if self.session.state.active_comp.map(|c| c.0) != Some(document) + && let Err(error) = crate::menus::invoke(self, &ctx, "comp.open", json!({"comp": document})) + { + self.ui.status = error; + } + } + DockEvent::DocumentClosed { panel: PanelKind::Timeline, document, .. } => { + if let Err(error) = crate::menus::invoke(self, &ctx, "comp.close", json!({"comp": document})) { + self.ui.status = error; + } + } + _ => {} } } - for action in output.actions { - if let Err(error) = self.dock_command(&ctx, action) { - self.ui.status = error; + // A layout a panel changed during the pass takes priority over the gestures of the one shown. + if self.ui.dock == *shown { + for action in actions.into_iter().chain(requested) { + if let Err(error) = self.dock_command(&ctx, action) { + self.ui.status = error; + } } + } else { + craft_ui::runtime::drag::cancel(&ctx, craft_behavior::CancelReason::HostChanged); } for p in locks { if p == PanelKind::EffectControls { @@ -504,108 +481,77 @@ impl EffectcraftApp { self.ui.locked_tabs.insert(p.id().to_string()); } } - for action in doc_actions { - let result = match action { - // The Timeline's comp tabs: show that comp / close its Timeline. - DocAction::Activate(id) => { - let _ = self.apply_dock(Action::Activate { panel: PanelKind::Timeline }); - self.focus_panel(&ctx, PanelKind::Timeline); - if self.session.state.active_comp.map(|c| c.0) == Some(id) { - Ok(Value::Null) - } else { - crate::menus::invoke(self, &ctx, "comp.open", json!({"comp": id})) - } - } - DocAction::Close(id) => crate::menus::invoke(self, &ctx, "comp.close", json!({"comp": id})), - }; - if let Err(error) = result { - self.ui.status = error; - } - } if let Some(open) = menu { ctx.data_mut(|d| d.insert_temp::(egui::Id::unique("panel-menu"), open)); // the owner window draws it on its next pass ctx.request_repaint(); } drop_menu_of_closed_window(&ctx, &self.native_viewports); - let hits = DockArea::::hit_rects(&ctx, area_id()); - self.register_dock_hits(&hits); + self.register_dock_hits(&sources); panels::panel_menu_popup(self, ui); } /// Keys and dropped files that reach a floating panel's own OS window go to the main /// window's next frame ([`crate::EffectcraftApp::raw_input_hook`]), so its shortcuts and - /// file import handle them. Text is not forwarded, and nothing is while a text field in - /// the main window has the keyboard. - fn forward_window_input(&mut self, ctx: &egui::Context, events: Vec, files: Vec>) { - let typing = ctx.egui_wants_keyboard_input(); - let events = events.into_iter().filter(|event| !typing && !matches!(event, egui::Event::Text(_) | egui::Event::Ime(_))); - self.forwarded.events.extend(events); - if handed_over_to_the_timeline(files.iter().map(|window| (window.panel, !window.dropped.is_empty()))) { + /// file import handle them. Text is not forwarded, and no key is while a text field has the + /// keyboard. + fn forward_window_input(&mut self, ctx: &egui::Context, windows: &[(PanelKind, egui::ViewportId)], files: Vec>) { + let typing = crate::native_menu::text_field_window(ctx).is_some(); + for (_, viewport) in windows { + let events = ctx.input_for(*viewport, |i| i.events.clone()); + self.forwarded.events.extend(events.into_iter().filter(|event| !typing && !matches!(event, egui::Event::Text(_) | egui::Event::Ime(_)))); + } + if handed_over_to_the_timeline(files.iter().map(|drop| (drop.panel, !drop.files.is_empty()))) { self.forwarded.dropped_on_timeline = true; } - self.forwarded.files.extend(files.into_iter().flat_map(|window| window.dropped)); + #[cfg(not(target_arch = "wasm32"))] + self.forwarded.files.extend(files.into_iter().flat_map(|drop| drop.files).map(|file| Arc::new(WindowFile(file)) as egui::DroppedFileHandle)); + #[cfg(target_arch = "wasm32")] + let _ = files; if !self.forwarded.events.is_empty() || !self.forwarded.files.is_empty() { ctx.request_repaint(); } } - /// Automation ids for craft-ui's gesture sources: `panel.tab.`, `panel.drag.` - /// (the group's drag bar), `panel.border.` (the top border above its tabs), - /// `panel.tabs.more.`, `panel.header.` (a stacked panel's open/close button), - /// `panel.float..move`, `.close`, `.resize` (bottom-right - /// corner) and `.resize.`, `dock.gutter.` (`a`/`b` per split level; a stack's gap - /// below entry `i` adds `s`), `dock.corner..` where two dividers meet, and - /// the same inside floating window `n` as `panel.float..gutter.…` and `.corner.…`. - fn register_dock_hits(&mut self, hits: &[(Hit, Rect)]) { - let window = |panel: &PanelKind| self.ui.dock.layout.floating.iter().position(|window| window.contains(panel)); + /// Automation ids for the dock's gesture sources: `panel.tab.`, `panel.drag.` + /// (the group's drag bar), `panel.float..move` and `.resize` (bottom-right corner) and + /// `.resize.` for floating window `n`, `dock.gutter.` (`a`/`b` per split level; a + /// stack's gap below entry `i` adds `s`), `dock.gutter.group.` under a dock + /// column's group and `dock.column.` at a dock column's inner edge. + fn register_dock_hits(&mut self, sources: &[DockSource]) { + let window = |panel: &PanelKind| self.ui.dock.layout().floating.iter().position(|window| window.contains(panel)); // Tabs are labelled as drawn: "Composition Intro", not "Composition". let titles = self.tab_titles(); let title = |panel: &PanelKind| titles.iter().find(|(p, _)| p == panel).map_or_else(|| panel.title().to_string(), |(_, t)| t.clone()); let mut found = Vec::new(); - for (hit, rect) in hits { - let entry = match hit { - Hit::Tab(panel) => (format!("panel.tab.{}", panel.id()), title(panel)), - Hit::DragBar(panel) => (format!("panel.drag.{}", panel.id()), "Move panel group".into()), - Hit::Border(panel) => (format!("panel.border.{}", panel.id()), "Move panel group".into()), - Hit::Overflow(panel) => (format!("panel.tabs.more.{}", panel.id()), "More tabs".into()), - Hit::StackToggle(panel) => (format!("panel.header.{}", panel.id()), title(panel)), - Hit::Title(panel) => match window(panel) { + for source in sources { + let entry = match &source.kind { + SourceKind::Tab(panel) => (format!("panel.tab.{}", panel.id()), title(panel)), + SourceKind::GroupBar(panel) => (format!("panel.drag.{}", panel.id()), "Move panel group".into()), + SourceKind::WindowGrip(panel) => match window(panel) { Some(index) => (format!("panel.float.{index}.move"), "Move floating panel".into()), None => continue, }, - Hit::Close(panel) => match window(panel) { - Some(index) => (format!("panel.float.{index}.close"), "Close floating panel".into()), - None => continue, - }, - Hit::Resize(panel, edge) => match window(panel) { + SourceKind::WindowResize(panel, edge) => match window(panel) { Some(index) if *edge == ResizeEdge::BottomRight => (format!("panel.float.{index}.resize"), "Resize floating panel".into()), Some(index) => (format!("panel.float.{index}.resize.{edge:?}"), "Resize floating panel".into()), None => continue, }, - Hit::Divider(Divider::Split(path)) => (format!("dock.gutter.{}", path_id(path)), "gutter".into()), - Hit::Divider(Divider::Stack(panel)) => match dock::stack_gutter_id(&self.ui.dock.layout, *panel) { - Some(id) => (id, "gutter".into()), - None => continue, - }, - Hit::Divider(Divider::Intersection(outer, inner)) => (format!("dock.corner.{}.{}", path_id(outer), path_id(inner)), "gutter corner".into()), - Hit::Divider(Divider::WindowSplit(panel, path)) => match window(panel) { - Some(index) => (format!("panel.float.{index}.gutter.{}", path_id(path)), "gutter".into()), - None => continue, - }, - Hit::Divider(Divider::WindowIntersection(panel, outer, inner)) => match window(panel) { - Some(index) => (format!("panel.float.{index}.corner.{}.{}", path_id(outer), path_id(inner)), "gutter corner".into()), - None => continue, - }, + SourceKind::Divider(DividerKind::Split(path)) => (format!("dock.gutter.{}", path_id(path)), "gutter".into()), + SourceKind::Divider(DividerKind::Groups(panel)) => { + let id = dock::stack_gutter_id(self.ui.dock.layout(), *panel).unwrap_or_else(|| format!("dock.gutter.group.{}", panel.id())); + (id, "gutter".into()) + } + SourceKind::Divider(DividerKind::ColumnEdge(panel)) => (format!("dock.column.{}", panel.id()), "gutter".into()), _ => continue, }; - found.push((entry, *rect, DockArea::hit_id(area_id(), hit))); + found.push((entry, source.rect, source.id)); } - // The widget id lets keyboard focus on a divider or grip map to its element. - for ((id, label), rect, widget) in found { + // The node id lets keyboard focus on a divider or grip map to its element. + for ((id, label), rect, node) in found { self.auto.add(&id, rect, &label); if let Some(element) = self.auto.elements.last_mut() { - element.response_id = Some(widget); + element.response_id = Some(node); } } } @@ -617,33 +563,107 @@ fn path_id(path: &[bool]) -> String { } /// After Effects' window is all frames: drops on all four window edges, Ctrl/Cmd-drag undocks, -/// a release over no target floats, and a floating window's title bar only moves it. -fn dock_style(ui: &egui::Ui, t: &Tokens) -> DockStyle { - let mut style = DockStyle::from_ui(ui); - style.side_edge_zones = true; - style.new_dock_zones = false; - style.maximize_item = true; - style.close_others_item = true; - style.command_press_floats = true; - style.float_on_empty_drop = true; - style.title_bar_docks = false; - style.float_hint = true; - style.wheel_selects_tabs = true; - style.middle_click_closes_tabs = true; - style.float_label = "Undock Panel".into(); - style.float_group_label = "Undock Frame".into(); - style.close_group_label = "Close Frame".into(); - style.tab_height = t.tab_h; - style.gap = t.gap; - style.background = t.panel_bg; - style.tab_background = t.panel_bg; - style.active_background = t.panel_bg; - style.floating_background = t.panel_bg; - style.text = t.tab_text_active; - style.inactive_text = t.tab_text; - style.accent = t.focus; - style.font = Tokens::ui(12.0); - style +/// a release over no target floats, a floating window's title bar only moves it, and the tabs +/// close with their ×, a middle click, or the group menu's Close Other Panels in Group. +fn dock_config() -> DockConfig { + DockConfig::default() + .side_edge_zones(true) + .new_dock_zones(false) + .maximize_item(true) + .close_others_item(true) + .float_on_empty_drop(true) + .title_bar_docks(false) + .wheel_selects_tabs(true) + .tab_close_buttons(true) + .native_windows(true) +} + +/// A colour as the spec model keeps it. +fn rgba(color: egui::Color32) -> [u8; 4] { + color.to_srgba_unmultiplied() +} + +/// A kept colour as a tab swatch. +fn srgba([r, g, b, a]: [u8; 4]) -> craft_theme::Srgba { + craft_theme::Srgba::from(egui::Color32::from_rgba_unmultiplied(r, g, b, a)) +} + +/// What the dock area keeps between frames: the workspace it shows, the panels' specs, and what +/// its last pass reported that the next one or a command needs. +#[derive(Default)] +pub(crate) struct LiveDock { + shown: Option>, + specs: Tracked, + /// Where a command floats a panel without a rect. + float_space: Option>, + /// The OS windows the floating windows showed in, named by their first panel. + windows: Vec<(PanelKind, egui::ViewportId)>, + /// The panel whose group held key focus. + focused: Option, +} + +impl LiveDock { + /// The `Arc` the dock shows for `workspace`: the last one while the arrangement is the same, + /// so an idle pass keeps the workspace's revision and the dock reads no spec. + fn shown(&mut self, workspace: &Workspace) -> Arc { + if let Some(shown) = self.shown.as_ref().filter(|shown| ***shown == *workspace) { + return Arc::clone(shown); + } + let shown = Arc::new(workspace.clone()); + self.shown = Some(Arc::clone(&shown)); + shown + } +} + +/// What the dock reads of the open panels: tab names, label swatches and the Timeline's comps. +#[derive(Clone, Debug, Default, PartialEq, PlainData)] +struct DockSpecs { + rows: Vec, +} + +/// One open panel's spec, by panel id. +#[derive(Clone, Debug, PartialEq, PlainData)] +struct SpecRow { + panel: String, + label: String, + /// The label swatch before the name; `Some(None)` is the theme's empty swatch. + swatch: Option>, + documents: Vec, +} + +/// One of the Timeline's comp tabs. +#[derive(Clone, Debug, PartialEq, PlainData)] +struct DocRow { + id: u64, + label: String, + swatch: Option<[u8; 4]>, + /// The comp the Timeline shows. + shown: bool, +} + +impl PanelSpecs for DockSpecs { + fn spec(&self, panel: &PanelKind) -> PanelSpec { + let id = panel.id(); + let Some(row) = self.rows.iter().find(|row| row.panel == id) else { return PanelSpec::new(panel.title()).host_body() }; + // Every panel body is EffectCraft's own egui code: the dock runs it with the window's style. + let mut spec = PanelSpec::new(row.label.clone()).host_body(); + if let Some(swatch) = row.swatch { + spec = spec.swatch(swatch.map(srgba)); + } + if !row.documents.is_empty() { + let documents = row + .documents + .iter() + .map(|doc| PanelDocument::new(doc.id, doc.label.clone()).swatch(doc.swatch.map(srgba)).closable(true).shown(doc.shown)) + .collect(); + spec = spec.documents(documents); + } + spec + } + + fn permissions(&self, panel: &PanelKind) -> Permissions { + dock::permissions(panel) + } } /// Panels with a lock: the Composition viewers and the Timeline keep their comp while locked, @@ -662,16 +682,9 @@ fn is_locked(app: &EffectcraftApp, panel: PanelKind) -> bool { } /// EffectCraft's side of the dock area for one frame. -struct EffectContent<'a> { +struct EffectPanels<'a> { app: &'a mut EffectcraftApp, tokens: Tokens, - titles: Vec<(PanelKind, String)>, - swatches: Vec<(PanelKind, egui::Color32)>, - docs: Vec, - /// Measures the comp tabs for their width in the tab row. - ctx: egui::Context, - style: DockStyle, - doc_actions: Vec, /// Viewer locks clicked. locks: Vec, /// The ≡ button clicked: its panel, where its menu opens and the viewport it was clicked in. @@ -682,6 +695,84 @@ struct EffectContent<'a> { ime: NativeIme, } +impl DockPanels for EffectPanels<'_> { + fn body(&mut self, panel: &PanelKind, ui: &mut Ui, _: &mut BodyCx<'_>) { + let t = self.tokens; + let rect = ui.max_rect(); + self.bodies.push((*panel, rect)); + // A floating panel's OS window is a pass of its own: its text IME descriptor is set up + // before its first body and published after its bodies (the main window does both in + // `draw`). + let viewport = ui.ctx().viewport_id(); + let native = viewport != egui::ViewportId::ROOT && !ui.ctx().embed_viewports(); + if native && self.ime.begin_body(viewport) { + panels::viewer_text::begin_ui(ui.ctx()); + } + self.app.panel_body(ui, *panel, rect); + if native && self.ime.publishes(viewport, panels::viewer_text::ime_recorded(ui.ctx())) { + panels::viewer_text::finish_ime(self.app, ui); + } + // The ≡ menu of a panel in its own OS window is drawn by that window's pass, after its + // last body, at that window's coordinates. + if native && self.ime.menu_turn(viewport) { + panels::panel_menu_area(self.app, ui); + } + // The body fills its frame; allocating it lets a floated panel keep its full size. + ui.allocate_rect(rect, Sense::hover()); + // Painted after the body so child backgrounds cannot hide the focus outline. + if self.app.ui.focused == *panel { + ui.painter().rect_stroke(rect, 0.0, Stroke::new(1.0, t.focus), StrokeKind::Inside); + } + } + + /// The viewer lock and the ≡ panel menu of the shown panel, before the tabs. + fn group_header(&mut self, panels: &[PanelKind], active: usize, ui: &mut Ui, _: &mut BodyCx<'_>) { + let Some(active) = panels.get(active).copied() else { return }; + let t = self.tokens; + let height = ui.available_height().max(18.0); + if has_lock(active) { + let (slot, _) = ui.allocate_exact_size(vec2(LOCK_W, height), Sense::hover()); + let lock = Rect::from_center_size(slot.center(), vec2(14.0, 14.0)); + let locked = is_locked(self.app, active); + if dock::lock_button(ui, lock, active, locked, &t, &mut self.app.auto) { + self.locks.push(active); + } + } + let (slot, _) = ui.allocate_exact_size(vec2(MENU_W, height), Sense::hover()); + let rect = Rect::from_center_size(slot.center(), vec2(18.0, 18.0)); + let response = ui.interact(rect, egui::Id::unique(("panel-menu-button", active.id())), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, response.enabled(), "panel menu")); + self.app.auto.add_response(&format!("panel.menu.{}", active.id()), &response, "panel menu"); + let color = if response.hovered() { t.tab_text_active } else { t.tab_text }; + icons::paint(ui.painter(), Rect::from_center_size(rect.center(), vec2(16.0, 16.0)), Icon::Hamburger, color); + crate::widgets::focus_outline(ui, &response, &t); + if response.clicked() { + self.app.ui.focused = active; + self.menu = Some((active, rect.left_bottom(), ui.ctx().viewport_id())); + } + } +} + +/// A file dropped on a floating panel's OS window, handed to the main window's file import. +#[cfg(not(target_arch = "wasm32"))] +#[derive(Debug)] +struct WindowFile(craft_ui::runtime::drag::OsFile); + +#[cfg(not(target_arch = "wasm32"))] +impl egui::DroppedFile for WindowFile { + fn path(&self) -> &std::path::Path { + self.0.path.as_deref().unwrap_or_else(|| std::path::Path::new(&self.0.name)) + } + + fn bytes(&self) -> Result, String> { + match (&self.0.bytes, &self.0.path) { + (Some(bytes), _) => Ok(bytes.to_vec()), + (None, Some(path)) => std::fs::read(path).map_err(|error| error.to_string()), + (None, None) => Err(format!("{}: no path or contents", self.0.name)), + } + } +} + /// Which body of a native floating window publishes its IME descriptor. /// /// Each OS window is an egui pass of its own. `viewer_text::finish_ime` publishes what the pass's @@ -702,13 +793,15 @@ pub(crate) struct NativeIme { } impl NativeIme { + /// `viewports` are the OS windows the dock reported last pass, each named by a panel of its + /// window. A window not among them yet (it opens this pass) publishes after every body. /// `unpublished` are the windows that drew last pass but never published: the layout's count /// was too high for them, so they publish after every body this pass. - pub(crate) fn new(floating: &[Floating], unpublished: &[egui::ViewportId]) -> Self { + pub(crate) fn new(floating: &[Floating], viewports: &[(PanelKind, egui::ViewportId)], unpublished: &[egui::ViewportId]) -> Self { let expected = floating .iter() .filter_map(|window| { - let viewport = window_viewport(window.id)?; + let viewport = viewports.iter().find(|(panel, _)| window.contains(panel)).map(|(_, viewport)| *viewport)?; let count = if unpublished.contains(&viewport) { 0 } else { window_bodies(window) }; Some((viewport, count)) }) @@ -778,148 +871,18 @@ pub(crate) fn drop_menu_of_closed_window(ctx: &egui::Context, windows: &[egui::V }); } -/// The OS window craft-ui opens for the floating window `id`. -#[cfg(not(target_arch = "wasm32"))] -fn window_viewport(id: u64) -> Option { - Some(DockArea::::window_viewport(area_id(), id)) -} - -/// The web keeps floating windows in the page. -#[cfg(target_arch = "wasm32")] -fn window_viewport(_id: u64) -> Option { - None -} - -/// The panel bodies craft-ui draws in a floating window: the active panel of each group and each -/// open stack entry. A minimized window shows its bar only. +/// The panel bodies the dock draws in a floating window: the shown panel of each group that is +/// not minimized. A window collapsed to icons shows none. fn window_bodies(window: &Floating) -> usize { - if window.minimized { + if window.column.iconic { return 0; } - let mut count = 0usize; - let mut nodes = vec![&window.root]; - while let Some(node) = nodes.pop() { - match node { - Node::Split { first, second, .. } => nodes.extend([&**first, &**second]), - Node::Tabs { panels, active } => count = count.saturating_add(usize::from(panels.get(*active).is_some())), - Node::Stack { entries } => count = count.saturating_add(entries.iter().filter(|e| e.open).count()), - _ => {} - } - } - count + window.groups().iter().filter(|group| !group.minimized && group.active_panel().is_some()).count() } -impl EffectContent<'_> { - fn header_width(&self, active: PanelKind, strip_width: f32) -> f32 { - let lock = if has_lock(active) { LOCK_W } else { 0.0 }; - (lock + MENU_W).min(strip_width * 2.0 / 3.0).max(MENU_W) - } - - /// Whether the group of `panels` shows comp tabs: it holds the Timeline and comps are open. - fn has_doc_tabs(&self, panels: &[PanelKind]) -> bool { - panels.contains(&PanelKind::Timeline) && !self.docs.is_empty() - } -} - -impl DockContent for EffectContent<'_> { - fn body(&mut self, ui: &mut egui::Ui, panel: &PanelKind) { - let t = self.tokens; - let rect = ui.max_rect(); - self.bodies.push((*panel, rect)); - // A floating panel's OS window is a pass of its own: its text IME descriptor is set up - // before its first body and published after its bodies (the main window does both in - // `draw`). - let viewport = ui.ctx().viewport_id(); - let native = viewport != egui::ViewportId::ROOT && !ui.ctx().embed_viewports(); - if native && self.ime.begin_body(viewport) { - panels::viewer_text::begin_ui(ui.ctx()); - } - self.app.panel_body(ui, *panel, rect); - if native && self.ime.publishes(viewport, panels::viewer_text::ime_recorded(ui.ctx())) { - panels::viewer_text::finish_ime(self.app, ui); - } - // The ≡ menu of a panel in its own OS window is drawn by that window's pass, after its - // last body, at that window's coordinates. - if native && self.ime.menu_turn(viewport) { - panels::panel_menu_area(self.app, ui); - } - // The body fills its frame; allocating it lets a floated panel keep its full size. - ui.allocate_rect(rect, Sense::hover()); - // Painted after the body so child backgrounds cannot hide the focus outline. - if self.app.ui.focused == *panel { - ui.painter().rect_stroke(rect, 0.0, Stroke::new(1.0, t.focus), StrokeKind::Inside); - } - } - - fn logical_label(&self, panel: &PanelKind) -> String { - let title = panel.title(); - // The Window menu names most panels; `Markers` is only in the panel catalog, and the two - // panels in neither (`History`, `ScriptUI Panel`) keep their English names. - let listed = crate::i18n::command_label("window.panel", title); - if listed == title { crate::i18n::tr(title).to_string() } else { listed.to_string() } - } - - /// The tab names what the panel shows ("Composition Intro"), after the label swatch of its - /// comp or layer. With comps open, the Timeline's own tab is just "Timeline"; each comp has a - /// tab of its own after the group's panel tabs. - fn label(&mut self, _ui: &egui::Ui, panel: &PanelKind, logical: &str, font: &egui::FontId, color: egui::Color32) -> egui::WidgetText { - let title = self.titles.iter().find(|(p, _)| p == panel).map_or(logical, |(_, s)| s.as_str()); - let Some((_, swatch)) = self.swatches.iter().find(|(p, _)| p == panel) else { return title.into() }; - let mut job = egui::text::LayoutJob::default(); - job.append("■ ", 0.0, egui::TextFormat::simple(font.clone(), *swatch)); - job.append(title, 0.0, egui::TextFormat::simple(font.clone(), color)); - job.into() - } - - fn group_header_width(&self, _panels: &[PanelKind], active: &PanelKind, _floating: bool, strip_width: f32) -> f32 { - self.header_width(*active, strip_width) - } - - /// The viewer lock and the ≡ panel menu of the shown panel. - fn group_header(&mut self, ui: &mut egui::Ui, _panels: &[PanelKind], active: &PanelKind, _floating: bool) { - let t = self.tokens; - let header = ui.max_rect(); - let menu = Rect::from_min_max(pos2((header.max.x - MENU_W).max(header.min.x), header.min.y), header.max); - if has_lock(*active) { - let lock = Rect::from_center_size(pos2(menu.min.x - LOCK_W / 2.0, header.center().y), vec2(14.0, 14.0)); - let locked = is_locked(self.app, *active); - if dock::lock_button(ui, lock, *active, locked, &t, &mut self.app.auto) { - self.locks.push(*active); - } - } - let rect = Rect::from_center_size(menu.center(), vec2(18.0, 18.0)); - let response = ui.interact(rect, egui::Id::unique(("panel-menu-button", active.id())), Sense::click()); - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, response.enabled(), "panel menu")); - self.app.auto.add_response(&format!("panel.menu.{}", active.id()), &response, "panel menu"); - let color = if response.hovered() { t.tab_text_active } else { t.tab_text }; - icons::paint(ui.painter(), Rect::from_center_size(rect.center(), vec2(16.0, 16.0)), Icon::Hamburger, color); - crate::widgets::focus_outline(ui, &response, &t); - if response.clicked() { - self.app.ui.focused = *active; - self.menu = Some((*active, rect.left_bottom(), ui.ctx().viewport_id())); - } - } - - fn group_extra_tabs_width(&self, panels: &[PanelKind], _active: &PanelKind, _floating: bool) -> f32 { - if !self.has_doc_tabs(panels) { - return 0.0; - } - dock::doc_widths(&self.ctx, &self.docs, &self.style.font).iter().sum() - } - - /// The Timeline's comp tabs, after its group's panel tabs whichever panel is shown. - fn group_extra_tabs(&mut self, ui: &mut egui::Ui, panels: &[PanelKind], active: &PanelKind, _floating: bool) { - if self.has_doc_tabs(panels) { - let selected = *active == PanelKind::Timeline; - self.doc_actions.extend(dock::doc_tabs(ui, ui.max_rect(), &self.docs, selected, &self.style, &mut self.app.auto)); - } - } -} - -/// Whether a handed-over *drop* named the Timeline. A floating window reports its hovered files -/// too, so a drag that only passes over the Timeline window must not count: its flag would survive -/// and send the next drop somewhere else. The panel comes from the window, which the main window's -/// pointer can never reach (#2661). +/// Whether a handed-over *drop* named the Timeline. Only a drop with files counts, so a window +/// that only saw a file pass over it never sends the next drop somewhere else. The panel comes +/// from the window, which the main window's pointer can never reach (#2661). fn handed_over_to_the_timeline(drops: impl Iterator) -> bool { drops.into_iter().any(|(panel, has_files)| has_files && matches!(panel, PanelKind::Timeline)) } @@ -929,8 +892,8 @@ mod tests { use super::*; /// A drop handed over by a floating window says which panel it landed on; only the Timeline - /// turns it into a layer instead of a project item. A window that only saw the file hover over - /// it carries no files and must not count, or its flag would outlive the drag (#2661). + /// turns it into a layer instead of a project item. A drop without files must not count, or + /// its flag would outlive the drag (#2661). #[test] fn only_a_timeline_drop_is_handed_over_to_the_timeline() { let cases = [ diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8f5030fcb..7ec994d60 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -27,10 +27,11 @@ pub mod control; pub mod credits; pub mod display_gpu; pub mod dock; +pub mod dock_command; pub mod dock_ui; mod expression_diagnostics; -pub mod framework; pub mod frames; +pub mod framework; pub mod gpu_failure; pub mod header; pub mod i18n; @@ -500,6 +501,8 @@ pub struct EffectcraftApp { pub(crate) unpublished_viewports: Vec, /// A floating panel shown by a command: its window comes to the front next frame. pub(crate) pending_panel_raise: Option, + /// What the dock area keeps between frames. + pub(crate) live_dock: dock_ui::LiveDock, /// Home screen: recent-project thumbnail textures by path (None = no thumbnail). pub(crate) home_thumbs: std::collections::HashMap>, /// The (project path, saved revision) whose thumbnail was stored last. diff --git a/crates/ui-egui/src/menus/entries.rs b/crates/ui-egui/src/menus/entries.rs index c3641196f..2a1434f78 100644 --- a/crates/ui-egui/src/menus/entries.rs +++ b/crates/ui-egui/src/menus/entries.rs @@ -132,7 +132,7 @@ pub(crate) fn entry_enabled(app: &EffectcraftApp, e: &MenuEntry) -> bool { return !app.session.is_rendering() && !app.session.project.render_queue.is_empty(); } if e.command == "file.close" && super::invoke::no_params(&e.params) && app.ui.focused == PanelKind::RenderQueue { - return !app.ui.dock.locked; + return !app.ui.dock_locked; } if e.command == "window.panel" { return true; diff --git a/crates/ui-egui/src/menus/frontend.rs b/crates/ui-egui/src/menus/frontend.rs index d03aa77cf..9f2590db0 100644 --- a/crates/ui-egui/src/menus/frontend.rs +++ b/crates/ui-egui/src/menus/frontend.rs @@ -363,7 +363,6 @@ pub fn frontend(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, p: Valu Value::Null } "window.saveWorkspace" => { - crate::workspace_state::ensure_positions_ready(&app.ui)?; let name = app.ui.workspace.clone(); app.ui.saved_workspaces.insert(name.clone(), app.ui.dock.clone()); app.store_saved_workspaces()?; @@ -380,7 +379,6 @@ pub fn frontend(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, p: Valu ); return Ok(Value::Null); }; - crate::workspace_state::ensure_positions_ready(&app.ui)?; app.ui.saved_workspaces.insert(name.clone(), app.ui.dock.clone()); app.ui.workspace = name.clone(); app.store_saved_workspaces()?; @@ -404,7 +402,6 @@ pub fn frontend(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, p: Valu }; let builtin = crate::dock::WORKSPACES.contains(&name.as_str()); if p.get("delete").and_then(Value::as_bool) == Some(true) { - crate::workspace_state::ensure_positions_ready(&app.ui)?; if app.ui.saved_workspaces.remove(&name).is_none() && !builtin { return Err(format!("no workspace `{name}`")); } @@ -419,7 +416,6 @@ pub fn frontend(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, p: Valu if builtin { return Err(format!("`{name}` is a built-in workspace: save it as a new workspace instead")); } - crate::workspace_state::ensure_positions_ready(&app.ui)?; let dock = app.ui.saved_workspaces.remove(&name).ok_or_else(|| format!("no workspace `{name}`"))?; app.ui.saved_workspaces.insert(new.to_string(), dock); if app.ui.workspace == name { diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 4bb7fae7c..bcd0f7481 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -243,7 +243,7 @@ pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: V // Close follows panel focus too: with the Render Queue active, Cmd+W closes that panel and // leaves the active composition open (it used to close the composition next to it). if id == "file.close" && no_params(¶ms) && app.ui.focused == PanelKind::RenderQueue { - app.apply_dock(craft_behavior::dock::Action::Close { panel: PanelKind::RenderQueue })?; + app.apply_dock(craft_behavior::dock::Action::close(PanelKind::RenderQueue))?; // The focus goes to a panel that is still there, so the next Close acts on the composition // instead of on the queue that is gone. let next = [PanelKind::Timeline, PanelKind::Composition, PanelKind::Project].into_iter().find(|p| panel_shown(app, *p)).unwrap_or(PanelKind::Project); @@ -443,17 +443,23 @@ pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: V "closePanel" => { let p = panel_of("panel").ok_or("closePanel: need `panel`")??; if app.ui.dock.is_open(p) { - app.apply_dock(craft_behavior::dock::Action::Close { panel: p })?; + app.apply_dock(craft_behavior::dock::Action::close(p))?; } return Ok(Value::Null); } "floatPanel" => { let p = panel_of("panel").ok_or("floatPanel: need `panel`")??; let r = match params.get("rect") { - Some(value) => serde_json::from_value::<[f32; 4]>(value.clone()).map_err(|_| "rect must contain four finite numbers")?, + Some(value) => { + let rect = serde_json::from_value::<[f32; 4]>(value.clone()).map_err(|_| "rect must contain four finite numbers")?; + if !rect.iter().all(|v| v.is_finite()) { + return Err("rect must contain four finite numbers".into()); + } + crate::dock_command::rect_of(rect) + } None => crate::dock_ui::default_float_rect(ctx.content_rect()), }; - app.apply_dock(craft_behavior::dock::Action::Float { panel: p, rect: r }).map_err(|e| format!("can't undock {}: {e}", p.title()))?; + app.apply_dock(craft_behavior::dock::Action::float(p, r)).map_err(|e| format!("can't undock {}: {e}", p.title()))?; return Ok(Value::Null); } _ => { @@ -475,8 +481,8 @@ pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: V if let Some(before) = panel_of("before") { command["before"] = json!(before?); } - let command: craft_ui::docking::DockCommand = - serde_json::from_value(command).map_err(|e| format!("dockPanel: zone: center|tab|left|right|top|bottom|above|below ({e})"))?; + let command = crate::dock_command::DockCommand::parse("window.panel.dock", &command) + .map_err(|e| format!("dockPanel: zone: center|tab|left|right|top|bottom|above|below ({e})"))?; app.run_dock_command(ctx, command).map_err(|e| format!("can't dock {}: {e}", p.title()))?; app.show_panel(p); return Ok(Value::Null); diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 97b678c61..5abae7e5a 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -685,7 +685,7 @@ fn closing_the_render_queue_reveals_the_panel_receiving_focus() { assert!(!app.ui.dock.is_visible(PanelKind::Project)); app.show_panel(PanelKind::RenderQueue); if maximized { - app.apply_dock(craft_behavior::dock::Action::Float { panel: PanelKind::RenderQueue, rect: [50.0, 60.0, 400.0, 200.0] }).unwrap(); + app.apply_dock(craft_behavior::dock::Action::float(PanelKind::RenderQueue, crate::dock_command::rect_of([50.0, 60.0, 400.0, 200.0]))).unwrap(); app.toggle_maximize(PanelKind::EffectControls); app.ui.focused = PanelKind::RenderQueue; assert!(app.ui.dock.is_floating(PanelKind::RenderQueue)); @@ -702,13 +702,16 @@ fn closing_the_render_queue_reveals_the_panel_receiving_focus() { fn closing_a_floating_queue_preserves_the_maximized_composition() { let mut session = effectcraft_engine::Session::default(); session.execute("comp.new", json!({"name": "A", "width": 32, "height": 32, "duration": 2})).unwrap(); - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_context_setup(crate::framework::install_headless).build_eframe(|_| EffectcraftApp::new(session)); + let mut h = egui_kittest::Harness::builder() + .with_size(egui::vec2(1200.0, 800.0)) + .with_context_setup(crate::framework::install_headless) + .build_eframe(|_| EffectcraftApp::new(session)); h.run_steps(3); let ctx = h.ctx.clone(); let app = h.state_mut(); app.show_panel(PanelKind::Composition); app.show_panel(PanelKind::RenderQueue); - app.apply_dock(craft_behavior::dock::Action::Float { panel: PanelKind::RenderQueue, rect: [50.0, 60.0, 400.0, 200.0] }).unwrap(); + app.apply_dock(craft_behavior::dock::Action::float(PanelKind::RenderQueue, crate::dock_command::rect_of([50.0, 60.0, 400.0, 200.0]))).unwrap(); app.toggle_maximize(PanelKind::Composition); app.ui.focused = PanelKind::RenderQueue; assert!(app.ui.dock.is_visible(PanelKind::Timeline), "the hidden underlying tab triggers the regression"); @@ -727,7 +730,7 @@ fn queue_close_preserves_state_when_workspace_is_locked() { let mut app = EffectcraftApp::new(effectcraft_engine::Session::default()); app.session.execute("comp.new", json!({"name": "A", "duration": 2})).unwrap(); app.show_panel(PanelKind::RenderQueue); - app.ui.dock.locked = true; + app.ui.dock_locked = true; let workspace = app.ui.dock.clone(); let comp = app.session.active_comp_id(); for _ in 0..2 { @@ -737,7 +740,7 @@ fn queue_close_preserves_state_when_workspace_is_locked() { assert_eq!(app.session.active_comp_id(), comp); } assert!(!menu_items(&app).iter().find(|item| item.id == "file.close").unwrap().enabled); - app.ui.dock.locked = false; + app.ui.dock_locked = false; invoke(&mut app, &ctx, "file.close", Value::Null).unwrap(); assert!(!app.ui.dock.is_open(PanelKind::RenderQueue)); } @@ -752,12 +755,8 @@ fn queue_close_preserves_viewer_command_target() { app.ui.viewers.insert(0, Some(a)); app.ui.viewers.insert(1, Some(b)); app.ui.active_viewer = 1; - app.apply_dock(craft_behavior::dock::Action::Move { - panel: PanelKind::Timeline, - anchor: PanelKind::Composition, - placement: craft_behavior::dock::DockPlacement::Tab { before: None }, - }) - .unwrap(); + app.apply_dock(craft_behavior::dock::Action::move_beside(PanelKind::Timeline, PanelKind::Composition, craft_behavior::dock::DockPlacement::tab(None))) + .unwrap(); app.close_panel(PanelKind::Timeline); app.show_panel(PanelKind::Composition); app.show_panel(PanelKind::RenderQueue); @@ -776,7 +775,10 @@ fn queue_close_keeps_passive_viewer_focus_across_frames() { let mut session = effectcraft_engine::Session::default(); let a = session.execute("comp.new", json!({"name": "A", "width": 32, "height": 32, "duration": 2})).unwrap()["comp"].as_u64().unwrap(); let b = session.execute("comp.new", json!({"name": "B", "width": 32, "height": 32, "duration": 2})).unwrap()["comp"].as_u64().unwrap(); - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_context_setup(crate::framework::install_headless).build_eframe(|_| EffectcraftApp::new(session)); + let mut h = egui_kittest::Harness::builder() + .with_size(egui::vec2(1200.0, 800.0)) + .with_context_setup(crate::framework::install_headless) + .build_eframe(|_| EffectcraftApp::new(session)); h.run_steps(3); let ctx = h.ctx.clone(); let app = h.state_mut(); @@ -784,12 +786,8 @@ fn queue_close_keeps_passive_viewer_focus_across_frames() { app.ui.viewers.insert(0, Some(a)); app.ui.viewers.insert(1, Some(b)); app.ui.active_viewer = 1; - app.apply_dock(craft_behavior::dock::Action::Move { - panel: PanelKind::Timeline, - anchor: PanelKind::Composition, - placement: craft_behavior::dock::DockPlacement::Tab { before: None }, - }) - .unwrap(); + app.apply_dock(craft_behavior::dock::Action::move_beside(PanelKind::Timeline, PanelKind::Composition, craft_behavior::dock::DockPlacement::tab(None))) + .unwrap(); app.close_panel(PanelKind::Timeline); app.show_panel(PanelKind::Composition); app.show_panel(PanelKind::RenderQueue); diff --git a/crates/ui-egui/src/native_menu.rs b/crates/ui-egui/src/native_menu.rs index a905fc7a0..5197481b3 100644 --- a/crates/ui-egui/src/native_menu.rs +++ b/crates/ui-egui/src/native_menu.rs @@ -443,7 +443,10 @@ impl MenuSync { /// window, where any widget that holds the keyboard counts (the Viewer's text editor is not an /// egui text field). pub fn text_field_window(ctx: &egui::Context) -> Option { - craft_ui::docking::typing_window(ctx).or_else(|| ctx.egui_wants_keyboard_input().then_some(egui::ViewportId::ROOT)) + let host = craft_ui::runtime::windows::WindowHost::of(ctx); + let window = host.key_window(); + let floating = (window != egui::ViewportId::ROOT && host.typing()).then_some(window); + floating.or_else(|| ctx.egui_wants_keyboard_input().then_some(egui::ViewportId::ROOT)) } /// Whether a focused text field takes the menu command `command` ([`activate`]): the native menu @@ -476,8 +479,8 @@ fn text_field_event(command: &str) -> Option> { /// Hand a text field's Edit command to the window `window` whose field has the keyboard. The /// main window gets the clipboard text itself and the events through the synthetic queue; a -/// floating panel's OS window gets each key pressed and released, and asks for the clipboard -/// text on Cmd+V (`craft_ui::docking::send_keys`). +/// floating panel's OS window gets each key pressed and released through the window host, and +/// the clipboard text as typed text on Cmd+V. fn send_to_text_field(app: &mut EffectcraftApp, ctx: &egui::Context, window: egui::ViewportId, events: Vec) { if window == egui::ViewportId::ROOT { for event in events { @@ -493,19 +496,25 @@ fn send_to_text_field(app: &mut EffectcraftApp, ctx: &egui::Context, window: egu ctx.request_repaint(); return; } - let events = events - .into_iter() - .flat_map(|event| { - let release = match &event { - egui::Event::Key { key, physical_key, modifiers, .. } => { - Some(egui::Event::Key { key: *key, physical_key: *physical_key, pressed: false, repeat: false, modifiers: *modifiers }) + let host = craft_ui::runtime::windows::WindowHost::of(ctx); + let platform = craft_keymap::egui::platform(ctx); + for event in events { + let (key, modifiers) = match event { + egui::Event::Key { key: egui::Key::V, .. } => { + if let Some(text) = app.hooks.clipboard_text.as_ref().and_then(|f| f()) { + host.inject_text(window, &text); } - _ => None, - }; - std::iter::once(event).chain(release) - }) - .collect(); - craft_ui::docking::send_keys(ctx, window, events); + continue; + } + egui::Event::Key { key, modifiers, .. } => (key, modifiers), + egui::Event::Copy => (egui::Key::C, egui::Modifiers::COMMAND), + egui::Event::Cut => (egui::Key::X, egui::Modifiers::COMMAND), + _ => continue, + }; + if let Some(key) = craft_keymap::Key::from_egui(key) { + host.inject_key(window, key, craft_keymap::Mods::from_egui(&modifiers, platform), false); + } + } } /// Run a native menu item (by id) the way the in-window menu bar does. While a text field has diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index e0be9a80d..b47492f53 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -344,13 +344,13 @@ pub(crate) fn panel_menu_area(app: &mut EffectcraftApp, ui: &mut egui::Ui) { // only ever narrows what the area measured: the separator fills whatever width it is given ui.set_max_width(ui.max_rect().width().min(width)); if ui.button(tr("Close Panel")).clicked() { - let _ = app.dock_command(ui.ctx(), craft_behavior::dock::Action::Close { panel }); + let _ = app.dock_command(ui.ctx(), craft_behavior::dock::Action::close(panel)); close = true; } let floating = crate::dock::WorkspaceExt::is_floating(&app.ui.dock, panel); if !floating && ui.button(tr("Undock Panel")).clicked() { let r = crate::dock_ui::default_float_rect(ui.ctx().content_rect()); - let _ = app.dock_command(ui.ctx(), craft_behavior::dock::Action::Float { panel, rect: r }); + let _ = app.dock_command(ui.ctx(), craft_behavior::dock::Action::float(panel, r)); close = true; } // Multiple monitors: an OS window of its own, which can go on another screen. Where diff --git a/crates/ui-egui/src/panels/viewer_text/tests.rs b/crates/ui-egui/src/panels/viewer_text/tests.rs index 3017fb632..639373038 100644 --- a/crates/ui-egui/src/panels/viewer_text/tests.rs +++ b/crates/ui-egui/src/panels/viewer_text/tests.rs @@ -147,7 +147,7 @@ impl ImePass { /// One native floating window holding the Timeline's group and then the Viewer's. fn two_group_window() -> craft_behavior::dock::Floating { let groups = vec![craft_behavior::dock::Group::new(vec![PanelKind::Timeline], 0), craft_behavior::dock::Group::new(vec![PanelKind::Viewer(1)], 0)]; - craft_behavior::dock::Floating::stack(groups, [0.0, 0.0, 320.0, 360.0]).expect("two groups make a window") + craft_behavior::dock::Floating::stack(1, groups, egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(320.0, 360.0))).expect("two groups make a window") } impl ImePass { @@ -169,7 +169,7 @@ impl ImePass { let raw = egui::RawInput { viewport_id: viewport, viewports, screen_rect: Some(rect), events, ..Default::default() }; let mut preedit = None; let mut out = ctx.run_ui(raw, |ui| { - let mut ime = crate::dock_ui::NativeIme::new(std::slice::from_ref(window), &[]); + let mut ime = crate::dock_ui::NativeIme::new(std::slice::from_ref(window), &[(PanelKind::Timeline, viewport)], &[]); let order = if viewer_first { [true, false] } else { [false, true] }; for viewer in order { if ime.begin_body(viewport) { @@ -198,7 +198,7 @@ impl ImePass { #[test] fn native_window_with_a_group_before_the_viewer_keeps_the_composition() { let window = two_group_window(); - let viewport = craft_ui::docking::DockArea::::window_viewport(crate::dock_ui::area_id(), window.id); + let viewport = egui::ViewportId::from_hash_of(("native panel window", window.id)); let preview = || egui::Event::Ime(egui::ImeEvent::Preedit { text: "é".into(), active_range_chars: None }); for viewer_first in [false, true] { let (mut app, _) = editor("abcd", 4, 4); @@ -223,12 +223,12 @@ fn native_window_with_a_group_before_the_viewer_keeps_the_composition() { assert_eq!(preedit, None); // A window that drew fewer bodies than its layout counts publishes after every body in // its next pass. - let mut ime = crate::dock_ui::NativeIme::new(std::slice::from_ref(&window), &[]); + let mut ime = crate::dock_ui::NativeIme::new(std::slice::from_ref(&window), &[(PanelKind::Timeline, viewport)], &[]); ime.begin_body(viewport); assert!(!ime.publishes(viewport, false)); let unpublished = ime.unpublished(); assert_eq!(unpublished, vec![viewport]); - let mut ime = crate::dock_ui::NativeIme::new(std::slice::from_ref(&window), &unpublished); + let mut ime = crate::dock_ui::NativeIme::new(std::slice::from_ref(&window), &[(PanelKind::Timeline, viewport)], &unpublished); ime.begin_body(viewport); assert!(ime.publishes(viewport, false)); } diff --git a/crates/ui-egui/src/panels/viewers.rs b/crates/ui-egui/src/panels/viewers.rs index 2959cded0..4fe287262 100644 --- a/crates/ui-egui/src/panels/viewers.rs +++ b/crates/ui-egui/src/panels/viewers.rs @@ -327,7 +327,7 @@ fn add_viewer(app: &mut EffectcraftApp, near: u32) -> u32 { app.ui.viewers.insert(id, None); let p = panel(id); let anchor = [panel(near), PanelKind::Composition].into_iter().find(|q| app.ui.dock.is_open(*q)); - let _ = app.ui.dock.apply(craft_behavior::dock::Action::Open { panel: p, anchor }, crate::dock::permissions); + let _ = app.ui.dock.apply(craft_behavior::dock::Action::open(p, anchor), app.ui.dock_locked, crate::dock::permissions); id } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0f7d97bc0..5a7df800b 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -653,11 +653,9 @@ pub struct UiState { /// The panel maximized to fill the dock area (`~`), if any. #[serde(default)] pub maximized: Option, - /// Floating windows of [`Self::dock`] whose native rect holds the OS window's outer - /// position, from a workspace file of an earlier version (see - /// `crate::dock_ui::native_outer_to_content`). Workspaces are not saved while any remain. - #[serde(skip)] - pub native_outer: Vec, + /// Lock Workspace: no panel of [`Self::dock`] moves, floats or closes. + #[serde(default)] + pub dock_locked: bool, /// Locked Composition / Timeline tabs (panel ids): opening another composition does not /// bring a locked panel forward (the tab's lock icon, as After Effects' viewer lock). #[serde(default)] @@ -792,7 +790,7 @@ impl Default for UiState { workspace: "Default".into(), dock: crate::dock::Workspace::new(crate::dock::workspace("Default")), saved_workspaces: Default::default(), - native_outer: Vec::new(), + dock_locked: false, maximized: None, locked_tabs: BTreeSet::new(), effect_controls_lock: None, diff --git a/crates/ui-egui/src/workspace_state.rs b/crates/ui-egui/src/workspace_state.rs index de2e99ce7..1005fb029 100644 --- a/crates/ui-egui/src/workspace_state.rs +++ b/crates/ui-egui/src/workspace_state.rs @@ -28,6 +28,10 @@ struct Snapshot { focused: PanelKind, maximized: Option, saved_workspaces: BTreeMap, + /// Lock Workspace. A file without it loads unlocked, unless its workspace carries the + /// earlier format's own `locked` ([`WorkspaceStore::load`]). + #[serde(default)] + locked: bool, } impl Snapshot { @@ -39,6 +43,7 @@ impl Snapshot { focused: ui.focused, maximized: ui.maximized, saved_workspaces: ui.saved_workspaces.clone(), + locked: ui.dock_locked, } } @@ -48,12 +53,7 @@ impl Snapshot { ui.focused = self.focused; ui.maximized = self.maximized; ui.saved_workspaces = self.saved_workspaces; - // A native window's place is made safe to hand to the windowing system. - for workspace in std::iter::once(&mut ui.dock).chain(ui.saved_workspaces.values_mut()) { - for window in &mut workspace.layout.floating { - window.native = window.native.map(crate::dock_ui::sanitized_window_rect); - } - } + ui.dock_locked = self.locked; // Reserve restored viewer slots without restoring any project-specific composition // links. New Viewer allocates from this map, including after switching named layouts. for workspace in std::iter::once(&ui.dock).chain(ui.saved_workspaces.values()) { @@ -107,19 +107,23 @@ pub(crate) struct WorkspaceStore { impl WorkspaceStore { pub(crate) fn load(config: Option<&dyn ConfigStore>, ui: &mut UiState) -> Self { let mut original = None; - let mut outer = Vec::new(); let loaded = config.map_or(Ok(None), |c| c.read_bounded(FILE, MAX_BYTES)).map_err(|e| e.to_string()).and_then(|text| { text.map(|text| { let value: serde_json::Value = serde_json::from_str(&text).map_err(|e| e.to_string())?; let snapshot = if legacy::is_legacy(&value) { - let (snapshot, windows) = legacy::migrate(value, ui)?; + let snapshot = legacy::migrate(value, ui)?; original = Some(text); - outer = windows; snapshot } else if value.get("version").is_none() { return Err("not a workspace file".to_string()); } else { - serde_json::from_value::(value).map_err(|e| e.to_string())? + // A file written before the lock moved out of the workspace keeps its lock once. + let earlier_lock = value.get("locked").is_none().then(|| value.pointer("/dock/locked").and_then(serde_json::Value::as_bool)).flatten(); + let mut snapshot = serde_json::from_value::(value).map_err(|e| e.to_string())?; + if let Some(locked) = earlier_lock { + snapshot.locked = locked; + } + snapshot }; snapshot.validate()?; Ok(snapshot) @@ -129,7 +133,6 @@ impl WorkspaceStore { let error = match loaded { Ok(Some(snapshot)) => { snapshot.apply(ui); - ui.native_outer = outer; None } Ok(None) => None, @@ -163,12 +166,12 @@ impl WorkspaceStore { || self.saved.focused != ui.focused || self.saved.maximized != ui.maximized || self.saved.saved_workspaces != ui.saved_workspaces + || self.saved.locked != ui.dock_locked } pub(crate) fn save(&mut self, config: Option<&dyn ConfigStore>, ui: &UiState) -> Result { let Some(config) = config else { return Ok(false) }; - // A window still at its outer position would be saved as if that were its content's. - if !self.has_changes(ui) || !ui.native_outer.is_empty() { + if !self.has_changes(ui) { return Ok(false); } let snapshot = Snapshot::capture(ui); @@ -197,20 +200,9 @@ impl WorkspaceStore { let path = config.dir().map_or_else(|| FILE.to_string(), |dir| dir.join(FILE).display().to_string()); return Err(format!("{path} couldn't be loaded at startup, so it is left untouched; fix or move it and restart")); } - ensure_positions_ready(ui)?; self.save(Some(config), ui).map(|_| ()) } } -/// Explicit saves must wait until migrated native-window positions refer to their content. -/// Check before capturing a named layout too, so a later background save cannot persist -/// a snapshot made with the old outer-window positions. -pub(crate) fn ensure_positions_ready(ui: &UiState) -> Result<(), String> { - if !ui.native_outer.is_empty() { - return Err("workspace window positions are still being restored; try saving again in a moment".into()); - } - Ok(()) -} - #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/workspace_state/legacy.rs b/crates/ui-egui/src/workspace_state/legacy.rs index 73b30bbf5..b3609477a 100644 --- a/crates/ui-egui/src/workspace_state/legacy.rs +++ b/crates/ui-egui/src/workspace_state/legacy.rs @@ -9,17 +9,16 @@ //! group with all its tabs; a frame with a height keeps it as a fixed size (its tab strip //! added), and the others share the rest. A closed frame's tabs join the open frame above it //! (below it, at the top of the column), as a split has no collapsed frames. -//! - A floating group in its own native window (`panel_windows`) keeps that place as the -//! window's native rect. The earlier version stored the OS window's outer position, so the -//! window's id is returned for [`crate::dock_ui::native_outer_to_content`] to move it to its -//! content position once the main window reports its frame. +//! - A floating group in its own native window (`panel_windows`) floats where it was in the +//! main window; the dock places its OS window again. //! - Closed panels had no recorded place: they stay closed and reopen at their default place. use std::collections::BTreeMap; +use craft_behavior::dock::SplitSize; use craft_behavior::dock::{Floating, Node}; use craft_behavior::flow::Axis; -use craft_behavior::dock::SplitSize; +use egui::{Rect, pos2, vec2}; use serde::Deserialize; use super::{Snapshot, VERSION}; @@ -64,13 +63,6 @@ struct OldFloating { rect: [f32; 4], } -/// The floating group holding `panel` shows in its own native window at `rect`. -#[derive(Deserialize)] -struct OldPanelWindow { - panel: PanelKind, - rect: [f32; 4], -} - #[derive(Deserialize)] struct OldSnapshot { workspace: String, @@ -80,8 +72,6 @@ struct OldSnapshot { maximized: Option, saved_workspaces: BTreeMap, saved_floating: BTreeMap>, - #[serde(default)] - panel_windows: Vec, } #[derive(Deserialize)] @@ -100,28 +90,25 @@ pub(super) fn is_legacy(value: &serde_json::Value) -> bool { } } -/// The snapshot an earlier version's file describes, and the ids of its floating windows whose -/// native rect holds the OS window's outer position. `ui` supplies what an unversioned record +/// The snapshot an earlier version's file describes. `ui` supplies what an unversioned record /// leaves out (the current arrangement). The caller validates the result. -pub(super) fn migrate(value: serde_json::Value, ui: &UiState) -> Result<(Snapshot, Vec), String> { +pub(super) fn migrate(value: serde_json::Value, ui: &UiState) -> Result { if value.get("version").is_none() { let record: OldRecord = serde_json::from_value(value).map_err(|e| e.to_string())?; let mut snapshot = Snapshot::capture(ui); snapshot.saved_workspaces = named(record.workspaces, record.floating)?; - return Ok((snapshot, Vec::new())); + return Ok(snapshot); } let old: OldSnapshot = serde_json::from_value(value).map_err(|e| e.to_string())?; - let dock = workspace(old.dock, old.floating, &old.panel_windows)?; - let outer = dock.layout.floating.iter().filter(|window| window.native.is_some()).map(|window| window.id).collect(); - let snapshot = Snapshot { + Ok(Snapshot { version: VERSION, workspace: old.workspace, - dock, + dock: workspace(old.dock, old.floating)?, focused: old.focused, maximized: old.maximized, saved_workspaces: named(old.saved_workspaces, old.saved_floating)?, - }; - Ok((snapshot, outer)) + locked: false, + }) } /// Named workspaces with their floating groups; floating groups of no named workspace are @@ -131,12 +118,12 @@ fn named(roots: BTreeMap, mut floating: BTreeMap, windows: &[OldPanelWindow]) -> Result { +fn workspace(root: OldNode, floating: Vec) -> Result { // Closing the last docked panel left an empty tab group as the root. let root = match root { OldNode::Tabs { panels, .. } if panels.is_empty() => None, @@ -144,14 +131,13 @@ fn workspace(root: OldNode, floating: Vec, windows: &[OldPanelWindo }; let floating = floating .into_iter() - .map(|group| { - let native = windows.iter().find(|window| group.panels.contains(&window.panel)).map(|window| window.rect); - let mut window = Floating::single(group.panels, group.active, group.rect); - window.native = native.map(crate::dock_ui::sanitized_window_rect); - window + .zip(1_u64..) + .map(|(group, id)| { + let [x, y, w, h] = group.rect; + Floating::single(id, group.panels, group.active, Rect::from_min_size(pos2(x, y), vec2(w, h))) }) .collect(); - Ok(Workspace::new(Layout { root, floating })) + Ok(Workspace::new(Layout::new(root, floating))) } fn node(old: OldNode, depth: usize) -> Result, String> { @@ -159,17 +145,17 @@ fn node(old: OldNode, depth: usize) -> Result, String> { return Err("workspace dock tree exceeds supported limits".into()); } Ok(match old { - OldNode::Tabs { panels, active } => Node::Tabs { panels, active }, - OldNode::Split { vertical, size, a, b } => Node::Split { - axis: if vertical { Axis::Y } else { Axis::X }, - size: match size { + OldNode::Tabs { panels, active } => Node::tabs(panels, active), + OldNode::Split { vertical, size, a, b } => Node::split( + if vertical { Axis::Y } else { Axis::X }, + match size { OldSplitSize::Ratio(value) => SplitSize::Ratio(value), OldSplitSize::FixedA(value) => SplitSize::FixedFirst(value), OldSplitSize::FixedB(value) => SplitSize::FixedSecond(value), }, - first: Box::new(node(*a, depth.saturating_add(1))?), - second: Box::new(node(*b, depth.saturating_add(1))?), - }, + node(*a, depth.saturating_add(1))?, + node(*b, depth.saturating_add(1))?, + ), OldNode::Stack { entries } => column(entries, depth)?, }) } @@ -227,7 +213,7 @@ fn column(entries: Vec, depth: usize) -> Result, for frame in frames.into_iter().rev() { let own = frame_size(&frame); let gap = if node.is_some() { FRAME_GAP } else { 0.0 }; - let tabs = Node::Tabs { panels: frame.panels, active: frame.active }; + let tabs = Node::tabs(frame.panels, frame.active); node = Some(match node { None => tabs, Some(rest) => { @@ -237,7 +223,7 @@ fn column(entries: Vec, depth: usize) -> Result, // Shares the rest with the flexible frames below. (None, None) => SplitSize::Ratio(1.0 / (below_flexible as f32 + 1.0)), }; - Node::Split { axis: Axis::Y, size, first: Box::new(tabs), second: Box::new(rest) } + Node::split(Axis::Y, size, tabs, rest) } }); below_fixed = match (own, below_fixed) { diff --git a/crates/ui-egui/src/workspace_state/tests.rs b/crates/ui-egui/src/workspace_state/tests.rs index 98a42fa65..04856b7f8 100644 --- a/crates/ui-egui/src/workspace_state/tests.rs +++ b/crates/ui-egui/src/workspace_state/tests.rs @@ -1,8 +1,8 @@ use super::*; use crate::dock::{Floating, Layout, Node, StackEntry, WorkspaceExt as _}; use craft_behavior::dock::Action; -use craft_behavior::flow::Axis; use craft_behavior::dock::SplitSize; +use craft_behavior::flow::Axis; use effectcraft_engine::config::MemoryConfig; fn minimal() -> Workspace { @@ -10,7 +10,11 @@ fn minimal() -> Workspace { } fn tabs(panels: &[PanelKind]) -> Node { - Node::Tabs { panels: panels.to_vec(), active: 0 } + Node::tabs(panels.to_vec(), 0) +} + +fn rect(x: f32, y: f32, w: f32, h: f32) -> egui::Rect { + egui::Rect::from_min_size(egui::pos2(x, y), egui::vec2(w, h)) } #[test] @@ -67,20 +71,12 @@ fn corrupt_future_or_unknown_workspace_keeps_defaults_and_original_file() { const V1: &str = include_str!("../../tests/fixtures/workspaces-v1.json"); #[test] -fn explicit_save_reports_pending_migration_and_can_be_retried() { +fn explicit_save_rewrites_an_earlier_file_and_keeps_a_backup() { let config = MemoryConfig::default(); config.write(FILE, V1).unwrap(); let mut ui = UiState::default(); let mut store = WorkspaceStore::load(Some(&config), &mut ui); - assert!(!ui.native_outer.is_empty()); - assert!(!store.save(Some(&config), &ui).unwrap(), "background saves defer quietly"); - let error = store.save_now(Some(&config), &ui).unwrap_err(); - assert!(error.contains("positions") && error.contains("try saving again"), "{error}"); - assert_eq!(config.read(FILE).as_deref(), Some(V1)); - assert_eq!(config.read(BACKUP), None); assert!(store.has_changes(&ui)); - - crate::dock_ui::native_outer_to_content(&mut ui, None, None, 3.0); store.save_now(Some(&config), &ui).unwrap(); assert_eq!(config.read(BACKUP).as_deref(), Some(V1)); let mut restored = UiState::default(); @@ -108,34 +104,26 @@ fn version_one_file_loads_with_every_panel_in_place() { ), tabs(&[Properties]), ); - assert_eq!(ui.dock.layout.root, Some(root)); - let floating: Vec<_> = ui.dock.layout.floating.iter().map(|w| (w.panels().copied().collect::>(), w.rect, w.native)).collect(); + assert_eq!(ui.dock.layout().root, Some(root)); + let floating: Vec<_> = ui.dock.layout().floating.iter().map(|w| (w.panels().copied().collect::>(), w.rect, w.native)).collect(); assert_eq!( floating, [ - (vec![Preview], [900.0, 120.0, 300.0, 260.0], None), - (vec![RenderQueue], [200.0, 500.0, 520.0, 240.0], Some(crate::dock_ui::sanitized_window_rect([200.0, 500.0, 520.0, 240.0]))), + (vec![Preview], rect(900.0, 120.0, 300.0, 260.0), None), + // Its native window's place goes: the dock places the OS window again. + (vec![RenderQueue], rect(200.0, 500.0, 520.0, 240.0), None), ] ); // Closed panels stay closed. for panel in [Align, Layer] { assert!(!ui.dock.is_open(panel), "{panel:?}"); } - // The native window's place is its outer position until the main window reports its - // frame (here a 28-point title bar); the file is not rewritten before. - let id = ui.dock.layout.floating[1].id; - assert_eq!(ui.native_outer, [id]); let mut store = store; - assert!(!store.save(Some(&config), &ui).unwrap()); - let outer = egui::Rect::from_min_size(egui::pos2(10.0, 20.0), egui::vec2(1600.0, 1000.0)); - crate::dock_ui::native_outer_to_content(&mut ui, Some(outer), Some(outer.translate(egui::vec2(0.0, 28.0))), 0.1); - assert_eq!(ui.dock.layout.floating[1].native, Some([200.0, 528.0, 520.0, 240.0])); - assert!(ui.native_outer.is_empty()); assert!(store.save(Some(&config), &ui).unwrap()); // The named workspace still has Layer, closed only after it was saved. let saved = ui.saved_workspaces.get("My Layout").unwrap(); assert!(saved.is_docked(Layer) && saved.is_floating(Preview) && !saved.is_open(Align)); - assert_eq!(saved.layout.floating.iter().filter_map(|w| w.native).count(), 0); + assert_eq!(saved.layout().floating.iter().filter(|w| w.native.is_some()).count(), 0); } #[test] @@ -144,13 +132,6 @@ fn version_one_file_is_rewritten_once_in_the_current_format_and_kept_as_a_backup config.write(FILE, V1).unwrap(); let mut ui = UiState::default(); let mut store = WorkspaceStore::load(Some(&config), &mut ui); - // A backend that reports no window positions: the native place stays as it was. - let native = ui.dock.layout.floating[1].native; - crate::dock_ui::native_outer_to_content(&mut ui, None, None, 1.0); - assert!(!ui.native_outer.is_empty(), "waits for a report"); - crate::dock_ui::native_outer_to_content(&mut ui, None, None, 5.0); - assert!(ui.native_outer.is_empty()); - assert_eq!(ui.dock.layout.floating[1].native, native); let migrated = Snapshot::capture(&ui); assert!(store.has_changes(&ui), "the migrated layout is written without waiting for an edit"); assert!(store.save(Some(&config), &ui).unwrap()); @@ -178,16 +159,16 @@ fn stacked_frames_with_tabs_and_an_empty_root_migrate() { let mut ui = UiState::default(); let store = WorkspaceStore::load(Some(&config), &mut ui); assert_eq!(store.error, None); - assert_eq!(ui.dock.layout.root, None); + assert_eq!(ui.dock.layout().root, None); assert!(ui.dock.is_floating(PanelKind::Project)); use PanelKind::*; // Each open frame is a tab group with all its tabs; a frame's height is a fixed size // (with its tab strip), and the frame without one takes the rest. let column = crate::dock::vsplit(SplitSize::FixedSecond(80.0 + crate::dock::TAB_STRIP), tabs(&[Info]), crate::dock::tabs(&[Audio, Preview], 1)); - assert_eq!(ui.saved_workspaces.get("Mine").and_then(|w| w.layout.root.clone()), Some(column)); + assert_eq!(ui.saved_workspaces.get("Mine").and_then(|w| w.layout().root.clone()), Some(column)); // Closed frames' tabs join the open frame above them, or below at the top. let column = crate::dock::vsplit(SplitSize::FixedFirst(46.0 + crate::dock::TAB_STRIP), tabs(&[Preview, Properties, Paint, Align]), tabs(&[Info])); - assert_eq!(ui.saved_workspaces.get("Column").and_then(|w| w.layout.root.clone()), Some(column)); + assert_eq!(ui.saved_workspaces.get("Column").and_then(|w| w.layout().root.clone()), Some(column)); assert_eq!(ui.saved_workspaces.len(), 2, "floating groups of no named workspace are dropped"); } @@ -214,25 +195,21 @@ fn explicit_save_with_nothing_new_succeeds() { #[test] fn invalid_tabs_split_and_deep_tree_are_rejected() { let mut snapshot = Snapshot::capture(&UiState::default()); - snapshot.dock = Workspace::new(Layout { root: Some(Node::Tabs { panels: vec![PanelKind::Project], active: usize::MAX }), floating: vec![] }); + snapshot.dock = Workspace::new(Layout::new(Some(Node::tabs(vec![PanelKind::Project], usize::MAX)), vec![])); assert!(snapshot.validate().is_err()); - let split = |size, first, second| Node::Split { axis: Axis::X, size, first: Box::new(first), second: Box::new(second) }; - snapshot.dock = Workspace::new(Layout { - root: Some(split(SplitSize::FixedFirst(f32::NAN), tabs(&[PanelKind::Project]), tabs(&[PanelKind::Timeline]))), - floating: vec![], - }); + let split = |size, first, second| Node::split(Axis::X, size, first, second); + snapshot.dock = + Workspace::new(Layout::new(Some(split(SplitSize::FixedFirst(f32::NAN), tabs(&[PanelKind::Project]), tabs(&[PanelKind::Timeline]))), vec![])); assert!(snapshot.validate().is_err()); let mut root = tabs(&[PanelKind::Composition]); for _ in 0..=craft_behavior::dock::MAX_DEPTH { root = split(SplitSize::Ratio(0.5), root, tabs(&[])); } - snapshot.dock = Workspace::new(Layout { root: Some(root), floating: vec![] }); + snapshot.dock = Workspace::new(Layout::new(Some(root), vec![])); assert!(snapshot.validate().is_err()); // A panel in two places. - snapshot.dock = Workspace::new(Layout { - root: Some(tabs(&[PanelKind::Project])), - floating: vec![Floating::single(vec![PanelKind::Project], 0, [0.0, 0.0, 200.0, 100.0])], - }); + snapshot.dock = + Workspace::new(Layout::new(Some(tabs(&[PanelKind::Project])), vec![Floating::single(1, vec![PanelKind::Project], 0, rect(0.0, 0.0, 200.0, 100.0))])); assert!(snapshot.validate().is_err()); } @@ -242,9 +219,9 @@ fn closing_all_docked_panels_remains_a_persistable_layout() { let mut ui = UiState::default(); let mut store = WorkspaceStore::load(Some(&config), &mut ui); for panel in ui.dock.panels() { - ui.dock.apply(Action::Close { panel }, crate::dock::permissions).unwrap(); + ui.dock.apply(Action::close(panel), false, crate::dock::permissions).unwrap(); } - assert!(ui.dock.layout.root.is_none()); + assert!(ui.dock.layout().root.is_none()); assert!(store.save(Some(&config), &ui).unwrap()); let mut restored = UiState::default(); let loaded = WorkspaceStore::load(Some(&config), &mut restored); @@ -258,8 +235,8 @@ fn floating_groups_and_named_snapshots_roundtrip_without_document_state() { let mut ui = UiState::default(); let mut store = WorkspaceStore::load(Some(&config), &mut ui); ui.workspace = "Floating".into(); - ui.dock.apply(Action::Float { panel: PanelKind::Preview, rect: [50.0, 80.0, 200.0, 160.0] }, crate::dock::permissions).unwrap(); - ui.dock.apply(Action::Close { panel: PanelKind::Align }, crate::dock::permissions).unwrap(); + ui.dock.apply(Action::float(PanelKind::Preview, crate::dock_command::rect_of([50.0, 80.0, 200.0, 160.0])), false, crate::dock::permissions).unwrap(); + ui.dock.apply(Action::close(PanelKind::Align), false, crate::dock::permissions).unwrap(); ui.saved_workspaces.insert(ui.workspace.clone(), ui.dock.clone()); ui.maximized = Some(PanelKind::Composition); ui.project_search = "do not persist".into(); @@ -268,7 +245,7 @@ fn floating_groups_and_named_snapshots_roundtrip_without_document_state() { WorkspaceStore::load(Some(&config), &mut restored); assert_eq!(Snapshot::capture(&restored), Snapshot::capture(&ui)); // The closed panel's place comes back with it. - assert!(restored.dock.hidden.iter().any(|(p, _)| *p == PanelKind::Align)); + assert!(restored.dock.hidden().iter().any(|(p, _)| *p == PanelKind::Align)); assert!(restored.project_search.is_empty()); } @@ -277,7 +254,7 @@ fn restored_viewer_slots_do_not_reuse_ids_or_restore_document_links() { let config = MemoryConfig::default(); let mut ui = UiState::default(); let mut store = WorkspaceStore::load(Some(&config), &mut ui); - let two = |viewer| Workspace::new(Layout { root: Some(tabs(&[PanelKind::Composition, PanelKind::Viewer(viewer)])), floating: vec![] }); + let two = |viewer| Workspace::new(Layout::new(Some(tabs(&[PanelKind::Composition, PanelKind::Viewer(viewer)])), vec![])); ui.dock = two(2); ui.saved_workspaces.insert("Two views".into(), two(5)); ui.viewers.insert(2, Some(42)); @@ -296,15 +273,12 @@ fn invalid_viewer_ids_are_rejected_in_every_workspace_reference() { for location in 0..8 { let mut snapshot = Snapshot::capture(&UiState::default()); let panel = PanelKind::Viewer(id); - let docked = Workspace::new(Layout { root: Some(tabs(&[panel])), floating: vec![] }); - let stacked = - Workspace::new(Layout { root: Some(Node::Stack { entries: vec![StackEntry { panel, open: true, height: None }] }), floating: vec![] }); - let floating = Workspace::new(Layout { - root: Some(tabs(&[PanelKind::Composition])), - floating: vec![Floating::single(vec![panel], 0, [0.0, 0.0, 200.0, 100.0])], - }); - let mut hidden = Workspace::new(Layout { root: Some(tabs(&[PanelKind::Composition, panel])), floating: vec![] }); - hidden.apply(Action::Close { panel }, crate::dock::permissions).unwrap(); + let docked = Workspace::new(Layout::new(Some(tabs(&[panel])), vec![])); + let stacked = Workspace::new(Layout::new(Some(Node::stack(vec![StackEntry::new(panel)])), vec![])); + let floating = + Workspace::new(Layout::new(Some(tabs(&[PanelKind::Composition])), vec![Floating::single(1, vec![panel], 0, rect(0.0, 0.0, 200.0, 100.0))])); + let mut hidden = Workspace::new(Layout::new(Some(tabs(&[PanelKind::Composition, panel])), vec![])); + hidden.apply(Action::close(panel), false, crate::dock::permissions).unwrap(); match location { 0 => snapshot.focused = panel, 1 => snapshot.maximized = Some(panel), @@ -324,19 +298,32 @@ fn invalid_viewer_ids_are_rejected_in_every_workspace_reference() { } } +/// Lock Workspace persists with the workspaces; a file without it loads unlocked, and a file +/// whose workspace carries the earlier format's own lock keeps it once. #[test] -fn hostile_native_window_places_are_made_safe_on_load() { +fn the_workspace_lock_survives_a_save_and_an_earlier_files_lock_carries_over() { let config = MemoryConfig::default(); let mut ui = UiState::default(); let mut store = WorkspaceStore::load(Some(&config), &mut ui); - ui.dock.apply(Action::Float { panel: PanelKind::Project, rect: [10.0, 10.0, 300.0, 200.0] }, crate::dock::permissions).unwrap(); - ui.dock.apply(Action::SetNative { panel: PanelKind::Project, rect: Some([90_000.0, -90_000.0, 1.0e5, 0.5]) }, crate::dock::permissions).unwrap(); + ui.dock_locked = true; assert!(store.save(Some(&config), &ui).unwrap()); let mut restored = UiState::default(); WorkspaceStore::load(Some(&config), &mut restored); - let native = restored.dock.layout.floating.iter().find(|w| w.contains(&PanelKind::Project)).and_then(|w| w.native).unwrap(); - assert_eq!(native, crate::dock_ui::sanitized_window_rect(native)); - assert!(native[2] <= crate::dock_ui::PANEL_WINDOW_MAX && native[3] >= crate::dock_ui::PANEL_WINDOW_MIN[1]); + assert!(restored.dock_locked); + + let mut saved: serde_json::Value = serde_json::from_str(&config.read(FILE).unwrap()).unwrap(); + saved.as_object_mut().unwrap().remove("locked"); + config.write(FILE, &saved.to_string()).unwrap(); + let mut unlocked = UiState::default(); + WorkspaceStore::load(Some(&config), &mut unlocked); + assert!(!unlocked.dock_locked, "a file without the lock loads unlocked"); + + saved["dock"]["locked"] = serde_json::json!(true); + config.write(FILE, &saved.to_string()).unwrap(); + let mut earlier = UiState::default(); + let loaded = WorkspaceStore::load(Some(&config), &mut earlier); + assert_eq!(loaded.error, None); + assert!(earlier.dock_locked, "the earlier workspace's own lock carries over"); } #[test] diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 4444fcc5e..5e6ce22f0 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -29,7 +29,6 @@ mod ui_crypto_pick; mod ui_crypto_pick_undo; mod ui_crypto_select; mod ui_dialog_preview; -mod ui_dock_resize; mod ui_drag_drop; mod ui_effect_controls; mod ui_effect_drop_highlight; diff --git a/crates/ui-egui/tests/it/shared_docking_ui.rs b/crates/ui-egui/tests/it/shared_docking_ui.rs index 12e598a19..052d4f8a4 100644 --- a/crates/ui-egui/tests/it/shared_docking_ui.rs +++ b/crates/ui-egui/tests/it/shared_docking_ui.rs @@ -1,7 +1,6 @@ //! EffectCraft's workspaces in craft-ui's shared docking: transactions, the command path, pointer //! gestures and persistence. -use craft_behavior::dock::{Action, DockPlacement, Node, StackEntry}; -use craft_ui::docking::Zone; +use craft_behavior::dock::{Action, DockPlacement, Node}; use effectcraft_engine::Session; use effectcraft_ui_egui::{ EffectcraftApp, @@ -17,7 +16,12 @@ fn invoke(app: &mut EffectcraftApp, id: &str, params: serde_json::Value) -> Resu } fn floating(app: &EffectcraftApp) -> &[dock::Floating] { - &app.ui.dock.layout.floating + &app.ui.dock.layout().floating +} + +/// A rect as `[x, y, width, height]`. +fn rect4(r: Rect) -> [f32; 4] { + [r.min.x, r.min.y, r.width(), r.height()] } #[test] @@ -27,28 +31,28 @@ fn shared_move_preserves_accordion_metadata_and_unrelated_active_tabs() { dock::tabs(&[PanelKind::Project, PanelKind::Composition, PanelKind::Layer], 1), dock::stack(&[(PanelKind::Preview, false, Some(73.0)), (PanelKind::Properties, true, Some(211.0)), (PanelKind::Align, false, None)]), )); - workspace.apply(Action::Close { panel: PanelKind::Project }, dock::permissions).unwrap(); + workspace.apply(Action::close(PanelKind::Project), false, dock::permissions).unwrap(); assert!(workspace.is_visible(PanelKind::Composition)); - workspace - .apply(Action::Move { panel: PanelKind::Preview, anchor: PanelKind::Layer, placement: DockPlacement::Tab { before: None } }, dock::permissions) - .unwrap(); - let Some(Node::Split { second, size, .. }) = &workspace.layout.root else { panic!("split was lost") }; + workspace.apply(Action::move_beside(PanelKind::Preview, PanelKind::Layer, DockPlacement::tab(None)), false, dock::permissions).unwrap(); + let Some(Node::Split { second, size, .. }) = &workspace.layout().root else { panic!("split was lost") }; assert_eq!(*size, SplitSize::FixedSecond(300.0)); - let Node::Stack { entries } = second.as_ref() else { panic!("stack was lost") }; + let Node::Stack { entries, .. } = second.as_ref() else { panic!("stack was lost") }; // The unrelated stacked panels keep their exact state. - assert_eq!( - entries, - &vec![StackEntry { panel: PanelKind::Properties, open: true, height: Some(211.0) }, StackEntry { panel: PanelKind::Align, open: false, height: None }] - ); + let entries: Vec<_> = entries.iter().map(|entry| (entry.panel, entry.open, entry.height)).collect(); + assert_eq!(entries, [(PanelKind::Properties, true, Some(211.0)), (PanelKind::Align, false, None)]); assert_eq!(workspace.group_of(PanelKind::Preview), vec![PanelKind::Composition, PanelKind::Layer, PanelKind::Preview]); // Rejected moves and geometry change nothing. let before = workspace.clone(); assert!( workspace - .apply(Action::Move { panel: PanelKind::Preview, anchor: PanelKind::Audio, placement: DockPlacement::Split(Zone::Left) }, dock::permissions) + .apply(Action::move_beside(PanelKind::Preview, PanelKind::Audio, DockPlacement::Split(craft_behavior::DockSide::Start)), false, dock::permissions) + .is_err() + ); + assert!( + workspace + .apply(Action::float(PanelKind::Preview, effectcraft_ui_egui::dock_command::rect_of([0.0, 0.0, f32::INFINITY, 200.0])), false, dock::permissions) .is_err() ); - assert!(workspace.apply(Action::Float { panel: PanelKind::Preview, rect: [0.0, 0.0, f32::INFINITY, 200.0] }, dock::permissions).is_err()); assert_eq!(workspace, before); } @@ -66,14 +70,14 @@ fn every_builtin_workspace_validates_and_roundtrips_with_dynamic_identities() { let ids = |layout: &Layout| layout.floating.iter().map(|w| w.id).collect::>(); assert_eq!(ids(&dock::workspace("Undocked Panels")), ids(&dock::workspace("Undocked Panels"))); let mut workspace = dock::docked(dock::tabs(&[PanelKind::Composition, PanelKind::Viewer(42), PanelKind::ScriptPanel(77)], 1)); - workspace.apply(Action::Float { panel: PanelKind::ScriptPanel(77), rect: [20.0, 30.0, 400.0, 300.0] }, dock::permissions).unwrap(); + workspace + .apply(Action::float(PanelKind::ScriptPanel(77), effectcraft_ui_egui::dock_command::rect_of([20.0, 30.0, 400.0, 300.0])), false, dock::permissions) + .unwrap(); let text = serde_json::to_string(&workspace).unwrap(); assert!(text.contains("\"ScriptPanel\":77") && text.contains("\"Viewer\":42"), "{text}"); assert_eq!(serde_json::from_str::(&text).unwrap(), workspace); - workspace - .apply(Action::Move { panel: PanelKind::ScriptPanel(77), anchor: PanelKind::Viewer(42), placement: DockPlacement::Tab { before: None } }, dock::permissions) - .unwrap(); - assert!(workspace.layout.floating.is_empty()); + workspace.apply(Action::move_beside(PanelKind::ScriptPanel(77), PanelKind::Viewer(42), DockPlacement::tab(None)), false, dock::permissions).unwrap(); + assert!(workspace.layout().floating.is_empty()); assert!(workspace.is_visible(PanelKind::ScriptPanel(77))); } @@ -114,7 +118,8 @@ fn pointer_drop_merges_floats_and_redocks_without_project_changes() { ), dock::tabs(&[PanelKind::Timeline], 0), )); - let mut h = Harness::builder().with_size(vec2(1200.0, 760.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(move |_| app); + let mut h = + Harness::builder().with_size(vec2(1200.0, 760.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(move |_| app); h.run_steps(4); let project = h.state().session.project.clone(); let times = h.state().session.state.times.clone(); @@ -132,14 +137,14 @@ fn pointer_drop_merges_floats_and_redocks_without_project_changes() { let grips: Vec<_> = h.query_all_by_label("Resize panel window").collect(); assert!(!grips.is_empty() && grips.iter().all(|grip| grip.accesskit_node().role() == egui::accesskit::Role::Button)); // Its corner resizes it and its title bar moves it. - let original = floating(h.state())[0].rect; + let original = rect4(floating(h.state())[0].rect); let grip = rect(&h, "panel.float.0.resize").center(); drag(&mut h, grip, grip - vec2(36.0, 24.0), Modifiers::NONE); - let resized = floating(h.state())[0].rect; + let resized = rect4(floating(h.state())[0].rect); assert!(resized[2] < original[2] - 25.0 && resized[3] < original[3] - 15.0, "{original:?} -> {resized:?}"); let bar = rect(&h, "panel.float.0.move"); drag(&mut h, bar.center(), bar.center() - vec2(24.0, 18.0), Modifiers::NONE); - let moved = floating(h.state())[0].rect; + let moved = rect4(floating(h.state())[0].rect); assert!(moved[0] < resized[0] - 15.0 && moved[1] < resized[1] - 10.0, "{resized:?} -> {moved:?}"); // Its tab dropped on a docked tab strip docks it again. let from = rect(&h, "panel.tab.Info").center(); @@ -157,10 +162,10 @@ fn current_and_named_floating_layouts_survive_restart() { use std::sync::Arc; let store = Arc::new(MemoryConfig::default()); let mut app = EffectcraftApp::new(Session { config: Some(store.clone()), ..Default::default() }); - app.apply_dock(Action::Float { panel: PanelKind::Project, rect: [45.0, 65.0, 430.0, 310.0] }).unwrap(); + app.apply_dock(Action::float(PanelKind::Project, effectcraft_ui_egui::dock_command::rect_of([45.0, 65.0, 430.0, 310.0]))).unwrap(); invoke(&mut app, "window.saveWorkspaceAs", json!({"name": "Shared float"})).unwrap(); let saved = app.ui.dock.clone(); - app.apply_dock(Action::MoveFloating { panel: PanelKind::Project, rect: [75.0, 95.0, 480.0, 360.0] }).unwrap(); + app.apply_dock(Action::move_floating(PanelKind::Project, effectcraft_ui_egui::dock_command::rect_of([75.0, 95.0, 480.0, 360.0]))).unwrap(); let current = app.ui.dock.clone(); eframe::App::on_exit(&mut app); let mut restarted = EffectcraftApp::new(Session { config: Some(store), ..Default::default() }); @@ -181,12 +186,12 @@ fn float_command_rejects_malformed_rectangles_and_keeps_one_docked_panel() { // The last docked panel stays docked, whether it moves alone, with its group or by command. app.ui.dock = dock::docked(dock::tabs(&[PanelKind::Project], 0)); let before = app.ui.dock.clone(); - assert!(app.apply_dock(Action::Float { panel: PanelKind::Project, rect: [1.0, 2.0, 300.0, 200.0] }).is_err()); + assert!(app.apply_dock(Action::float(PanelKind::Project, effectcraft_ui_egui::dock_command::rect_of([1.0, 2.0, 300.0, 200.0]))).is_err()); assert!(invoke(&mut app, "window.panel.float", json!({"panel": "Project", "group": true})).is_err()); assert_eq!(app.ui.dock, before); // Closing it is allowed. invoke(&mut app, "window.closePanel", json!({"panel": "Project"})).unwrap(); - assert!(app.ui.dock.layout.root.is_none()); + assert!(app.ui.dock.layout().root.is_none()); } /// A floating panel dragged towards the window's bottom edge moves there, and its title bar @@ -204,11 +209,11 @@ fn floating_panel_dragged_towards_the_window_edge_keeps_moving() { h.run_steps(3); let bar = rect(&h, "panel.float.0.move"); drag(&mut h, bar.center(), bar.center() + vec2(40.0, 420.0), Modifiers::NONE); - let moved = floating(h.state())[0].rect; + let moved = rect4(floating(h.state())[0].rect); assert!(moved[1] > 550.0, "the panel moved down: {moved:?}"); let bar = rect(&h, "panel.float.0.move"); drag(&mut h, bar.center(), bar.center() - vec2(30.0, 200.0), Modifiers::NONE); - let back = floating(h.state())[0].rect; + let back = rect4(floating(h.state())[0].rect); assert!(back[1] < moved[1] - 150.0, "{moved:?} -> {back:?}"); } @@ -221,15 +226,15 @@ fn catalog_docking_action_supports_resize_reorder_and_floating_geometry() { dock::tabs(&[PanelKind::Composition], 0), )); for action in [ - Action::ResizeSplit { path: vec![], size: SplitSize::FixedFirst(360.0) }, - Action::Move { panel: PanelKind::Info, anchor: PanelKind::Project, placement: DockPlacement::Tab { before: Some(PanelKind::Project) } }, - Action::Float { panel: PanelKind::Info, rect: [20.0, 40.0, 300.0, 200.0] }, - Action::MoveFloating { panel: PanelKind::Info, rect: [45.0, 65.0, 330.0, 240.0] }, + Action::resize_split(vec![], SplitSize::FixedFirst(360.0)), + Action::move_beside(PanelKind::Info, PanelKind::Project, DockPlacement::tab(Some(PanelKind::Project))), + Action::float(PanelKind::Info, effectcraft_ui_egui::dock_command::rect_of([20.0, 40.0, 300.0, 200.0])), + Action::move_floating(PanelKind::Info, effectcraft_ui_egui::dock_command::rect_of([45.0, 65.0, 330.0, 240.0])), ] { invoke(&mut app, "window.dockAction", json!({"action": action})).unwrap(); } - assert_eq!(floating(&app)[0].rect, [45.0, 65.0, 330.0, 240.0]); - let Some(Node::Split { size, .. }) = &app.ui.dock.layout.root else { panic!("split lost") }; + assert_eq!(rect4(floating(&app)[0].rect), [45.0, 65.0, 330.0, 240.0]); + let Some(Node::Split { size, .. }) = &app.ui.dock.layout().root else { panic!("split lost") }; assert_eq!(*size, SplitSize::FixedFirst(360.0)); let before = app.ui.dock.clone(); assert!(invoke(&mut app, "window.dockAction", json!({"action": {"ResizeSplit": {"path": [true, true], "size": {"Ratio": 0.5}}}})).is_err()); @@ -252,7 +257,7 @@ fn ui_dock_and_window_panel_commands_parse_craft_ui_commands() { invoke(&mut app, "ui.dock", json!({"action": {"Activate": {"panel": "Layer"}}})).unwrap(); assert!(app.ui.dock.is_visible(PanelKind::Layer)); invoke(&mut app, "ui.dock", json!({"operation": "float", "panel": "Info", "rect": [100, 100, 300, 200]})).unwrap(); - assert_eq!(floating(&app)[0].rect, [100.0, 100.0, 300.0, 200.0]); + assert_eq!(rect4(floating(&app)[0].rect), [100.0, 100.0, 300.0, 200.0]); // `window.panel.*` takes EffectCraft's panel names too. invoke(&mut app, "window.panel.dock", json!({"panel": "Info", "anchor": "Project", "zone": "right"})).unwrap(); assert!(floating(&app).is_empty() && app.ui.dock.is_docked(PanelKind::Info)); @@ -284,10 +289,7 @@ fn raw_open_actions_are_rejected_through_every_docking_route() { let mut app = EffectcraftApp::new(Session::default()); let before = app.ui.dock.clone(); for panel in [PanelKind::ScriptPanel(77), PanelKind::Viewer(42)] { - for action in [ - Action::Open { panel, anchor: Some(PanelKind::Project) }, - Action::OpenAt { panel, anchor: PanelKind::Project, placement: DockPlacement::Tab { before: None } }, - ] { + for action in [Action::open(panel, Some(PanelKind::Project)), Action::open_at(panel, PanelKind::Project, DockPlacement::tab(None))] { for id in ["ui.dock", "window.panel.layout", "window.dockAction"] { let error = invoke(&mut app, id, json!({"action": action})).unwrap_err(); assert!(error.contains("panel open commands"), "{id}: {error}"); @@ -311,9 +313,9 @@ fn catalog_close_keeps_dynamic_panel_identity_and_releases_viewers() { app.ui.viewers.insert(42, Some(7)); app.ui.maximized = Some(PanelKind::Viewer(42)); for panel in [PanelKind::Viewer(42), PanelKind::ScriptPanel(77)] { - invoke(&mut app, "window.dockAction", json!({"action": Action::Close { panel }})).unwrap(); + invoke(&mut app, "window.dockAction", json!({"action": Action::close(panel)})).unwrap(); assert!(!app.ui.dock.is_open(panel)); - assert!(app.ui.dock.hidden.iter().any(|(p, _)| *p == panel), "{panel:?} keeps its place"); + assert!(app.ui.dock.hidden().iter().any(|(p, _)| *p == panel), "{panel:?} keeps its place"); } assert!(app.ui.dock.is_docked(PanelKind::Composition)); assert_eq!(app.ui.maximized, None); @@ -326,7 +328,8 @@ fn stacked_panels_resize_by_pointer_without_changing_closed_entries() { session.execute("comp.new", json!({"width": 160, "height": 90, "duration": 1})).unwrap(); let mut app = EffectcraftApp::new(session); app.ui.start_screen = false; - let mut h = Harness::builder().with_size(vec2(1000.0, 720.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(move |_| app); + let mut h = + Harness::builder().with_size(vec2(1000.0, 720.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(move |_| app); h.run_steps(4); h.state_mut().ui.dock = dock::docked(dock::stack(&[(PanelKind::Preview, true, Some(100.0)), (PanelKind::Properties, true, None), (PanelKind::Align, false, Some(77.0))])); @@ -337,9 +340,9 @@ fn stacked_panels_resize_by_pointer_without_changing_closed_entries() { drag(&mut h, from, from + vec2(0.0, 16.0), Modifiers::NONE); let after = rect(&h, "panel.Preview").height(); assert!((after - before - 16.0).abs() < 2.0, "{before} -> {after}"); - let Some(Node::Stack { entries }) = &h.state().ui.dock.layout.root else { panic!("stack lost") }; + let Some(Node::Stack { entries, .. }) = &h.state().ui.dock.layout().root else { panic!("stack lost") }; assert!(entries[0].height.unwrap_or_default() > 100.0, "{entries:?}"); - assert_eq!(entries[2], StackEntry { panel: PanelKind::Align, open: false, height: Some(77.0) }); + assert_eq!((entries[2].panel, entries[2].open, entries[2].height), (PanelKind::Align, false, Some(77.0))); assert!(std::sync::Arc::ptr_eq(&project, &h.state().session.project)); } @@ -348,7 +351,7 @@ fn failed_close_preserves_viewer_lifecycle_and_maximize_state() { let mut app = EffectcraftApp::new(Session::default()); // A locked workspace refuses the close. app.ui.dock = dock::docked(dock::tabs(&[PanelKind::Composition, PanelKind::Viewer(42)], 1)); - app.ui.dock.locked = true; + app.ui.dock_locked = true; app.ui.maximized = Some(PanelKind::Viewer(42)); app.ui.viewers.insert(42, Some(3)); app.ui.active_viewer = 42; diff --git a/crates/ui-egui/tests/it/ui_dock_resize.rs b/crates/ui-egui/tests/it/ui_dock_resize.rs deleted file mode 100644 index 29af2cdce..000000000 --- a/crates/ui-egui/tests/it/ui_dock_resize.rs +++ /dev/null @@ -1,85 +0,0 @@ -//! Shared pane resizing in the full application, including application shortcut ownership. - -use crate::gpu_test::RenderSerial; -use craft_ui::docking::{Divider, DockArea, Hit}; -use effectcraft_engine::Session; -use effectcraft_ui_egui::EffectcraftApp; -use effectcraft_ui_egui::dock::{self, Node, PanelKind, SplitSize}; -use effectcraft_ui_egui::theme::ThemeKind; -use egui::{Event, Key, Modifiers, PointerButton, Rect, pos2, vec2}; -use egui_kittest::Harness; -use serde_json::json; - -fn snapshots(h: &mut Harness<'_, EffectcraftApp>, directory: Option<&std::path::Path>, phase: &str) { - let Some(directory) = directory else { return }; - std::fs::create_dir_all(directory).unwrap(); - for (name, theme) in [("dark", ThemeKind::Dark), ("darker", ThemeKind::Darker), ("light", ThemeKind::Light)] { - let ctx = h.ctx.clone(); - h.state_mut().set_theme(&ctx, theme); - h.run_steps(3); - h.render_serialized().unwrap().save(directory.join(format!("effectcraft-{phase}-{name}.png"))).unwrap(); - } - let ctx = h.ctx.clone(); - h.state_mut().set_theme(&ctx, ThemeKind::Dark); - h.run_steps(3); -} - -fn first_size(h: &Harness<'_, EffectcraftApp>) -> f32 { - match &h.state().ui.dock.layout.root { - Some(Node::Split { size: SplitSize::FixedFirst(value), .. }) => *value, - ref other => panic!("fixed-size mode changed: {other:?}"), - } -} - -#[test] -fn focused_dock_resize_owns_arrows_and_keeps_pointer_dragging() { - let _device = crate::gpu_test::lock(); - let mut session = Session::default(); - session.execute("comp.new", json!({"name": "Split test", "width": 160, "height": 90, "duration": 1})).unwrap(); - session.execute("layer.newSolid", json!({"name": "Selected", "color": [1.0, 0.0, 0.0, 1.0]})).unwrap(); - let mut app = EffectcraftApp::new(session); - app.ui.start_screen = false; - let directory = std::env::var_os("CRAFT_UI_PANES_SNAPSHOT_DIR").map(std::path::PathBuf::from); - let mut builder = Harness::builder().with_size(vec2(1400.0, 900.0)).with_max_steps(10_000); - if directory.is_some() { - builder = builder.wgpu(); - } - let mut h = builder.with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(move |_| app); - h.run_steps(4); - snapshots(&mut h, directory.as_deref(), "workspace"); - h.state_mut().ui.focused = PanelKind::Composition; - h.state_mut().ui.dock = - dock::docked(dock::hsplit(SplitSize::FixedFirst(400.0), dock::tabs(&[PanelKind::Project], 0), dock::tabs(&[PanelKind::Composition], 0))); - h.run_steps(3); - let before_project = h.state().session.project.clone(); - let before_times = h.state().session.state.times.clone(); - let id = DockArea::::hit_id(effectcraft_ui_egui::dock_ui::area_id(), &Hit::Divider(Divider::Split(Vec::new()))); - h.ctx.memory_mut(|memory| memory.request_focus(id)); - h.run_steps(2); - assert_eq!(h.ctx.memory(|memory| memory.focused()), Some(id)); - snapshots(&mut h, directory.as_deref(), "focused-resize"); - h.event(Event::Key { key: Key::ArrowRight, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); - h.step(); - h.event(Event::Key { key: Key::ArrowRight, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE }); - h.step(); - assert_eq!(first_size(&h), 408.0); - assert_eq!(h.state().session.state.times, before_times); - assert!(std::sync::Arc::ptr_eq(&h.state().session.project, &before_project), "the viewer shortcut must not nudge a selected layer"); - - h.run_steps(2); - let element = h.state().auto.find("dock.gutter.").unwrap(); - let from = Rect::from_min_size(pos2(element.rect[0], element.rect[1]), vec2(element.rect[2], element.rect[3])).center(); - h.event(Event::PointerMoved(from)); - h.step(); - h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - h.step(); - for offset in [5.0, 10.0, 15.0, 20.0] { - h.event(Event::PointerMoved(from + vec2(offset, 0.0))); - h.step(); - } - h.event(Event::PointerButton { pos: from + vec2(20.0, 0.0), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - h.step(); - assert_eq!(first_size(&h), 428.0); - assert_eq!(h.state().session.state.times, before_times); - assert!(std::sync::Arc::ptr_eq(&h.state().session.project, &before_project)); -} diff --git a/crates/ui-egui/tests/it/ui_effect_controls.rs b/crates/ui-egui/tests/it/ui_effect_controls.rs index 0a8a5095b..b51490176 100644 --- a/crates/ui-egui/tests/it/ui_effect_controls.rs +++ b/crates/ui-egui/tests/it/ui_effect_controls.rs @@ -104,7 +104,11 @@ fn header_arrow_harness() -> (Harness<'static, EffectcraftApp>, LayerId, [(u64, let mut app = EffectcraftApp::new(s); app.show_panel(PanelKind::EffectControls); app.toggle_maximize(PanelKind::EffectControls); - let mut h = Harness::builder().with_size(egui::vec2(1000.0, 700.0)).with_step_dt(1.0 / 60.0).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = Harness::builder() + .with_size(egui::vec2(1000.0, 700.0)) + .with_step_dt(1.0 / 60.0) + .with_context_setup(effectcraft_ui_egui::framework::install_headless) + .build_eframe(|_| app); h.run_steps(4); (h, LayerId(lid), effects) } @@ -165,7 +169,12 @@ fn effect_header_arrows_ignore_hidden_panels_with_stale_focus() { "closed" => h.state_mut().close_panel(PanelKind::EffectControls), "maximized" => h.state_mut().toggle_maximize(PanelKind::Composition), "floating under maximized" => { - h.state_mut().apply_dock(craft_behavior::dock::Action::Float { panel: PanelKind::EffectControls, rect: [40.0, 40.0, 600.0, 400.0] }).unwrap(); + h.state_mut() + .apply_dock(craft_behavior::dock::Action::float( + PanelKind::EffectControls, + effectcraft_ui_egui::dock_command::rect_of([40.0, 40.0, 600.0, 400.0]), + )) + .unwrap(); h.state_mut().toggle_maximize(PanelKind::Composition); } _ => h.state_mut().ui.start_screen = true, @@ -187,10 +196,15 @@ fn effect_header_arrows_work_wherever_effect_controls_is_on_screen() { let (mut h, lid, [(fx, prop), _, _]) = header_arrow_harness(); h.state_mut().toggle_maximize(PanelKind::EffectControls); if place == "floating" { - h.state_mut().apply_dock(craft_behavior::dock::Action::Float { panel: PanelKind::EffectControls, rect: [40.0, 40.0, 600.0, 400.0] }).unwrap(); + h.state_mut() + .apply_dock(craft_behavior::dock::Action::float( + PanelKind::EffectControls, + effectcraft_ui_egui::dock_command::rect_of([40.0, 40.0, 600.0, 400.0]), + )) + .unwrap(); } else { - let placement = craft_behavior::dock::DockPlacement::Tab { before: None }; - h.state_mut().apply_dock(craft_behavior::dock::Action::Move { panel: PanelKind::EffectControls, anchor: PanelKind::Composition, placement }).unwrap(); + let placement = craft_behavior::dock::DockPlacement::tab(None); + h.state_mut().apply_dock(craft_behavior::dock::Action::move_beside(PanelKind::EffectControls, PanelKind::Composition, placement)).unwrap(); h.state_mut().toggle_maximize(PanelKind::Composition); assert_eq!(h.state().ui.maximized, Some(PanelKind::Composition), "the frame was maximized from its Composition tab"); } @@ -439,7 +453,11 @@ fn effect_header_down_and_up_scroll_the_picked_effect_into_view() { app.show_panel(PanelKind::EffectControls); app.toggle_maximize(PanelKind::EffectControls); app.ui.focused = PanelKind::EffectControls; - let mut h = Harness::builder().with_size(egui::vec2(800.0, 300.0)).with_step_dt(1.0 / 60.0).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = Harness::builder() + .with_size(egui::vec2(800.0, 300.0)) + .with_step_dt(1.0 / 60.0) + .with_context_setup(effectcraft_ui_egui::framework::install_headless) + .build_eframe(|_| app); h.run_steps(4); let panel = rect_of(&h, "panel.EffectControls"); let last = fx[fx.len() - 1]; @@ -463,7 +481,8 @@ fn effect_header_down_and_up_scroll_the_picked_effect_into_view() { #[test] fn effect_controls_widgets_register_automation_ids() { let (app, x) = app(); - let mut h = Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = + Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); settle(&mut h); let have = ids(&h); let want = [ @@ -515,7 +534,8 @@ fn tint_swap_button_targets_its_instance_and_undoes_both_colors() { let blur = s.execute("effect.apply", json!({"effect": "Gaussian Blur"})).unwrap()["effects"][0].as_u64().unwrap(); let mut app = EffectcraftApp::new(s); app.show_panel(PanelKind::EffectControls); - let mut h = Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = + Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); h.run_steps(4); let id = format!("effectControls.effect.{target}.swapColors"); let rect = h.state().auto.find(&id).unwrap().rect; @@ -542,7 +562,8 @@ fn tint_swap_button_targets_its_instance_and_undoes_both_colors() { #[test] fn crosshair_and_eyedropper_pick_from_the_viewer() { let (app, x) = app(); - let mut h = Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = + Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); settle(&mut h); // Crosshair: a click at comp (330, 190) is layer (105, 55) on the 200%-scaled layer // (anchor (100, 50) at position (320, 180)). @@ -580,7 +601,8 @@ fn the_eyedropper_samples_under_the_pointer_in_a_region_of_interest() { app.session.execute("view.setRegionOfInterest", json!({"rect": [0.0, 0.0, 320.0, 180.0]})).unwrap(); // (Not the red it will pick.) app.session.execute("prop.set", json!({"layer": x.small, "prop": x.color, "value": [0.0, 0.0, 1.0, 1.0]})).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = + Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); settle(&mut h); h.state_mut().ui.fx_pick = Some(FxPick { kind: "color".into(), layer: x.small, prop: x.color, name: "Color".into() }); h.step(); @@ -611,7 +633,10 @@ fn the_eyedropper_stays_armed_until_the_viewer_has_a_frame() { let KV::Color(c) = v else { panic!("{v:?}") }; c }; - let mut h = Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| EffectcraftApp::new(s)); + let mut h = Harness::builder() + .with_size(egui::vec2(1700.0, 1100.0)) + .with_context_setup(effectcraft_ui_egui::framework::install_headless) + .build_eframe(|_| EffectcraftApp::new(s)); h.state_mut().ui.fx_pick = Some(FxPick { kind: "color".into(), layer: top, prop, name: "Color".into() }); h.step(); let pos = effectcraft_ui_egui::panels::viewer::comp_to_screen(&h.ctx, [100.0, 100.0]).unwrap(); @@ -642,7 +667,8 @@ fn keyer_eyedropper_picks_the_screen_from_the_effect_input() { s.state.selected_layers = vec![LayerId(screen)]; let mut app = EffectcraftApp::new(s); app.show_panel(PanelKind::EffectControls); - let mut h = Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = + Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); settle(&mut h); h.state_mut().ui.fx_pick = Some(FxPick { kind: "color".into(), layer: screen, prop, name: "Screen Colour".into() }); h.step(); @@ -664,7 +690,8 @@ fn keyer_eyedropper_picks_the_screen_from_the_effect_input() { #[test] fn command_clicking_an_effect_twirl_closes_and_opens_its_groups() { let (app, x) = app(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = + Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); let fx = h.state_mut().session.execute("effect.apply", json!({"layers": [x.small], "effect": "Color Grading"})).unwrap()["effects"][0].as_u64().unwrap(); // Only this effect open, so its header is on screen. let l = layer(&h.state().session, x.small); @@ -694,7 +721,8 @@ fn command_clicking_an_effect_twirl_closes_and_opens_its_groups() { #[test] fn shift_click_on_effect_headers_selects_a_range_and_command_toggles() { let (app, x) = app(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = + Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); let fx: Vec = layer(&h.state().session, x.small).effects().unwrap().groups().map(|g| g.uid).collect(); // All twirled closed, so every header is on screen. h.state_mut().ui.fx_closed.extend(fx.iter().copied()); @@ -756,7 +784,8 @@ fn type_into(h: &mut Harness<'_, EffectcraftApp>, id: &str, text: &str) { #[test] fn angle_revolutions_scrub_and_take_typing() { let (app, x) = app(); - let mut h = Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = + Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); settle(&mut h); let angle = |h: &Harness<'_, EffectcraftApp>| layer(&h.state().session, x.small).effects().unwrap().find(x.angle).unwrap().value.as_f64(); h.state_mut().session.execute("prop.set", json!({"layer": x.small, "prop": x.angle, "value": 45.0})).unwrap(); @@ -820,7 +849,8 @@ fn right_click_in_effect_controls_shows_the_effect_menu() { s.state.selected_layers = vec![LayerId(b), LayerId(a)]; let mut app = EffectcraftApp::new(s); app.show_panel(PanelKind::EffectControls); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = + Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); h.run_steps(3); let category = " Blur & Sharpen"; // An effect's header: its own menu. @@ -883,7 +913,8 @@ fn extractor_offers_the_exr_layers_and_channels() { s.state.selected_layers = vec![LayerId(l)]; let mut app = EffectcraftApp::new(s); app.show_panel(PanelKind::EffectControls); - let mut h = Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = + Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); settle(&mut h); let values = |h: &Harness<'_, EffectcraftApp>| -> Vec { let l = layer(&h.state().session, l); @@ -956,7 +987,8 @@ fn cryptomatte_layer_popup_follows_the_footage() { s.state.selected_layers = vec![LayerId(l)]; let mut app = EffectcraftApp::new(s); app.show_panel(PanelKind::EffectControls); - let mut h = Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = + Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); settle(&mut h); // The file has only CryptoMaterial, so that is what the closed popup shows, and all it lists. assert!(h.query_by_label("CryptoMaterial").is_some() && h.query_by_label("CryptoObject").is_none()); @@ -996,7 +1028,8 @@ fn point_picker_handle_follows_hover_then_commits_once_across_effects() { app.show_panel(PanelKind::EffectControls); app.ui.viewer.zoom = Some(0.85); app.ui.viewer.pan = [25.0, -10.0]; - let mut h = Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = + Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); settle(&mut h); let id = format!("viewer.effectPoint.{point}"); let original = rect_of(&h, &id).center(); @@ -1027,7 +1060,8 @@ fn point_picker_handle_follows_hover_then_commits_once_across_effects() { #[test] fn point_picker_preview_cancels_and_works_with_layer_controls_hidden() { let (app, x) = app(); - let mut h = Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = + Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); settle(&mut h); let value = layer(&h.state().session, x.small).props.find(x.point).unwrap().value.clone(); let undo = h.state().session.history.undo.len(); @@ -1058,7 +1092,8 @@ fn radial_center_stays_draggable_when_its_property_is_selected() { let effect = l.effects().unwrap().groups().find(|g| g.match_id == "ec.blur.ccradialfast").unwrap(); let point = effect.get("center").unwrap().uid; app.session.state.selected_props = vec![(LayerId(x.small), point)]; - let mut h = Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = + Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); settle(&mut h); let id = format!("viewer.effectPoint.{point}"); assert!(ids(&h).contains(&id), "selected point must keep its handle"); @@ -1085,7 +1120,11 @@ fn radial_center_stays_draggable_when_its_property_is_selected() { #[test] fn clicking_an_effect_parameter_activates_its_header_and_handles() { let (app, x) = app(); - let mut h = Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_step_dt(1.0 / 60.0).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = Harness::builder() + .with_size(egui::vec2(1700.0, 1100.0)) + .with_step_dt(1.0 / 60.0) + .with_context_setup(effectcraft_ui_egui::framework::install_headless) + .build_eframe(|_| app); settle(&mut h); let name = rect_of(&h, &format!("effectControls.prop.{}.name", x.point)).center(); click(&mut h, name); @@ -1111,7 +1150,8 @@ fn non_point_parameters_activate_handles_across_effect_families() { s.state.selected_props.clear(); let mut app = EffectcraftApp::new(s); app.show_panel(PanelKind::EffectControls); - let mut h = Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = + Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); settle(&mut h); let name = rect_of(&h, &format!("effectControls.prop.{prop}.name")).center(); click(&mut h, name); @@ -1125,7 +1165,8 @@ fn non_point_parameters_activate_handles_across_effect_families() { #[test] fn custom_effect_editors_activate_their_owner() { let (app, x) = app(); - let mut h = Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = + Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); settle(&mut h); let graph = rect_of(&h, &format!("effectControls.effect.{}.curves.graph", x.curves)).center(); click(&mut h, graph); @@ -1167,7 +1208,8 @@ fn file_and_text_parameters_have_widgets() { assert_eq!(exts, ["cube"]); vec![pick.lock().unwrap().clone()] })); - let mut h = Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = + Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); settle(&mut h); let ctx = h.ctx.clone(); let r = effectcraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "effect.apply", json!({"effect": "Apply Color LUT"})).unwrap(); @@ -1217,7 +1259,11 @@ fn file_and_text_parameters_have_widgets() { #[test] fn effect_control_name_can_be_renamed_from_its_header() { let (app, x) = app(); - let mut h = Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_step_dt(1.0 / 60.0).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = Harness::builder() + .with_size(egui::vec2(1700.0, 1100.0)) + .with_step_dt(1.0 / 60.0) + .with_context_setup(effectcraft_ui_egui::framework::install_headless) + .build_eframe(|_| app); settle(&mut h); let name = format!("effectControls.effect.{}.name", x.point_fx); let point = rect_of(&h, &name).center(); @@ -1242,7 +1288,11 @@ fn effect_control_name_can_be_renamed_from_its_header() { #[test] fn effect_rename_opens_with_the_name_selected() { let (app, x) = app(); - let mut h = Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_step_dt(1.0 / 60.0).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = Harness::builder() + .with_size(egui::vec2(1700.0, 1100.0)) + .with_step_dt(1.0 / 60.0) + .with_context_setup(effectcraft_ui_egui::framework::install_headless) + .build_eframe(|_| app); settle(&mut h); let edit = format!("effectControls.effect.{}.nameEdit", x.point_fx); let current_name = @@ -1294,7 +1344,11 @@ fn effect_rename_opens_with_the_name_selected() { #[test] fn double_clicking_an_effect_property_name_reveals_it_in_the_timeline() { let (app, x) = app(); - let mut h = Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_step_dt(1.0 / 60.0).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = Harness::builder() + .with_size(egui::vec2(1700.0, 1100.0)) + .with_step_dt(1.0 / 60.0) + .with_context_setup(effectcraft_ui_egui::framework::install_headless) + .build_eframe(|_| app); settle(&mut h); let row = format!("timeline.prop.{}.name", x.point); assert!(!ids(&h).contains(&row), "the effect's property is not in the Timeline before the double-click"); @@ -1309,7 +1363,11 @@ fn double_clicking_an_effect_property_name_reveals_it_in_the_timeline() { #[test] fn effect_rename_escape_keeps_the_name() { let (app, x) = app(); - let mut h = Harness::builder().with_size(egui::vec2(1700.0, 1100.0)).with_step_dt(1.0 / 60.0).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = Harness::builder() + .with_size(egui::vec2(1700.0, 1100.0)) + .with_step_dt(1.0 / 60.0) + .with_context_setup(effectcraft_ui_egui::framework::install_headless) + .build_eframe(|_| app); settle(&mut h); let point = rect_of(&h, &format!("effectControls.effect.{}.name", x.point_fx)).center(); double_click(&mut h, point); @@ -1371,7 +1429,8 @@ fn select_layer(h: &mut Harness<'_, EffectcraftApp>, layer: u64) { #[test] fn locked_effect_controls_keep_their_layer_until_it_is_deleted() { let (app, a, b, fa, fb) = two_layers(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = + Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); h.run_steps(4); assert!(shows_effect(&h, fa) && !shows_effect(&h, fb), "A is shown before locking"); let comp = h.state().session.active_comp_id().unwrap().0; @@ -1424,7 +1483,8 @@ fn locked_effect_controls_keep_their_layer_until_it_is_deleted() { #[test] fn replacing_the_project_unlocks_effect_controls() { let (app, a, b, _, _) = two_layers(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = + Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); h.run_steps(4); let lock = rect_of(&h, "panel.tab.EffectControls.lock").center(); click(&mut h, lock); @@ -1453,7 +1513,8 @@ fn a_lock_request_with_no_layer_shown_fails_and_keeps_the_other_comps_lock() { } } let (app, a, _, _, _) = two_layers(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = + Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); h.run_steps(4); assert_eq!(send(&mut h)["ok"], true); let kept = h.state().ui.effect_controls_lock; @@ -1484,7 +1545,8 @@ fn a_lock_request_while_locked_in_another_comp_fails() { } } let (app, a, _, _, _) = two_layers(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = + Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); h.run_steps(4); assert_eq!(send(&mut h)["ok"], true); let kept = h.state().ui.effect_controls_lock; @@ -1516,7 +1578,8 @@ fn a_lock_request_after_a_project_replacement_does_not_report_the_old_lock() { } } let (app, a, _, _, _) = two_layers(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = + Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); h.run_steps(4); assert_eq!(send(&mut h)["ok"], true); assert_eq!(h.state().ui.effect_controls_lock.map(|l| l.layer), Some(a)); @@ -1532,7 +1595,8 @@ fn a_lock_request_after_a_project_replacement_does_not_report_the_old_lock() { #[test] fn applying_an_effect_while_locked_keeps_the_selection() { let (app, a, b, fa, _) = two_layers(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = + Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); h.run_steps(4); let lock = rect_of(&h, "panel.tab.EffectControls.lock").center(); click(&mut h, lock); @@ -1567,7 +1631,8 @@ fn effect_controls_lock_over_the_control_channel() { } } let (app, a, b, fa, fb) = two_layers(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); + let mut h = + Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| app); h.run_steps(4); assert_eq!(send(&mut h, json!({"effectControlsLocked": true}))["ok"], true); assert_eq!(h.state().ui.effect_controls_lock.map(|l| l.layer), Some(a)); diff --git a/crates/ui-egui/tests/it/ui_panel_focus.rs b/crates/ui-egui/tests/it/ui_panel_focus.rs index 99d687379..04fa5ee57 100644 --- a/crates/ui-egui/tests/it/ui_panel_focus.rs +++ b/crates/ui-egui/tests/it/ui_panel_focus.rs @@ -19,7 +19,10 @@ fn harness() -> (Harness<'static, EffectcraftApp>, u64, u64) { s.execute("layer.newSolid", json!({"name": "Red", "color": [1.0, 0.0, 0.0, 1.0]})).unwrap(); s.state.open_comps = vec![ItemId(main)]; s.state.active_comp = Some(ItemId(main)); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| EffectcraftApp::new(s)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 1000.0)) + .with_context_setup(effectcraft_ui_egui::framework::install_headless) + .build_eframe(|_| EffectcraftApp::new(s)); h.run_steps(3); (h, other, main) } @@ -93,9 +96,9 @@ fn opening_a_comp_in_the_minimal_workspace_docks_the_viewer_above_the_timeline() invoke(&mut h, "window.closePanel", json!({"panel": "Composition"})); assert!(!h.state().ui.dock.is_docked(PanelKind::Composition)); invoke(&mut h, "comp.open", json!({"comp": other})); - match &h.state().ui.dock.layout.root { + match &h.state().ui.dock.layout().root { Some(Node::Split { axis: effectcraft_ui_egui::dock::SplitAxis::Vertical, first, second, .. }) => { - assert_eq!(**first, Node::Tabs { panels: vec![PanelKind::Composition], active: 0 }, "the viewer is on top"); + assert_eq!(**first, Node::tabs(vec![PanelKind::Composition], 0), "the viewer is on top"); assert!(matches!(&**second, Node::Tabs { panels, .. } if panels.contains(&PanelKind::Timeline))); } other => panic!("expected the viewer above the Timeline, got {other:?}"), diff --git a/crates/ui-egui/tests/it/ui_panel_windows.rs b/crates/ui-egui/tests/it/ui_panel_windows.rs index 9f9dec821..b4dee1600 100644 --- a/crates/ui-egui/tests/it/ui_panel_windows.rs +++ b/crates/ui-egui/tests/it/ui_panel_windows.rs @@ -5,17 +5,12 @@ use effectcraft_engine::Session; use effectcraft_ui_egui::EffectcraftApp; use effectcraft_ui_egui::dock::{PanelKind, WorkspaceExt as _}; -use effectcraft_ui_egui::dock_ui::sanitized_window_rect; use serde_json::json; fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, params: serde_json::Value) -> Result { effectcraft_ui_egui::menus::invoke(app, ctx, "window.panelWindow", params) } -fn native(app: &EffectcraftApp, panel: PanelKind) -> Option<[f32; 4]> { - app.ui.dock.layout.floating.iter().find(|w| w.contains(&panel)).and_then(|w| w.native) -} - #[test] fn panel_window_command_moves_a_docked_panel_into_its_own_window_and_back() { let mut app = EffectcraftApp::new(Session::default()); @@ -24,10 +19,8 @@ fn panel_window_command_moves_a_docked_panel_into_its_own_window_and_back() { assert_eq!(invoke(&mut app, &ctx, json!({"panel": "Project", "window": true})).unwrap(), json!({"window": true})); // Undocked first, then given a window of its own. assert!(!app.ui.dock.is_docked(PanelKind::Project)); - assert!(app.ui.dock.layout.floating.iter().any(|w| w.panels().copied().collect::>() == [PanelKind::Project])); + assert!(app.ui.dock.layout().floating.iter().any(|w| w.panels().copied().collect::>() == [PanelKind::Project])); assert!(app.in_panel_window(PanelKind::Project)); - let rect = native(&app, PanelKind::Project).unwrap(); - assert_eq!(rect, sanitized_window_rect(rect)); // Asking again changes nothing; no `window` toggles. assert_eq!(invoke(&mut app, &ctx, json!({"panel": "Project", "window": true})).unwrap(), json!({"window": true})); assert_eq!(invoke(&mut app, &ctx, json!({"panel": "Project"})).unwrap(), json!({"window": false})); @@ -49,36 +42,20 @@ fn panel_window_command_moves_a_docked_panel_into_its_own_window_and_back() { assert!(app.ui.dock.is_docked(PanelKind::Project)); } -#[test] -fn panel_windows_survive_restart_with_hostile_places_made_safe() { - use effectcraft_engine::config::MemoryConfig; - use std::sync::Arc; - let store = Arc::new(MemoryConfig::default()); - let mut app = EffectcraftApp::new(Session { config: Some(store.clone()), ..Default::default() }); - let ctx = egui::Context::default(); - invoke(&mut app, &ctx, json!({"panel": "Project", "window": true})).unwrap(); - let hostile = [90_000.0, -99_000.0, 99_000.0, 0.5]; - app.apply_dock(craft_behavior::dock::Action::SetNative { panel: PanelKind::Project, rect: Some(hostile) }).unwrap(); - eframe::App::on_exit(&mut app); - let restarted = EffectcraftApp::new(Session { config: Some(store), ..Default::default() }); - assert_eq!(native(&restarted, PanelKind::Project), Some(sanitized_window_rect(hostile))); - let [x, y, w, h] = sanitized_window_rect(hostile); - assert!(x <= 100_000.0 && y >= -100_000.0 && (160.0..=16_384.0).contains(&w) && (100.0..=16_384.0).contains(&h)); - assert!(sanitized_window_rect([f32::NAN, f32::INFINITY, f32::NAN, f32::NEG_INFINITY]).iter().all(|v| v.is_finite())); -} - #[test] fn a_click_on_a_floating_panel_does_nothing_while_a_dialog_is_open() { - use egui::{Event, Modifiers, PointerButton, pos2, vec2}; + use egui::{Event, Modifiers, PointerButton, vec2}; use egui_kittest::Harness; let mut app = EffectcraftApp::new(Session::default()); app.ui.start_screen = false; - app.apply_dock(craft_behavior::dock::Action::Float { panel: PanelKind::Project, rect: [80.0, 120.0, 320.0, 240.0] }).unwrap(); - let mut h = Harness::builder().with_size(vec2(1400.0, 900.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(move |_| app); + app.apply_dock(craft_behavior::dock::Action::float(PanelKind::Project, effectcraft_ui_egui::dock_command::rect_of([80.0, 120.0, 320.0, 240.0]))).unwrap(); + let mut h = + Harness::builder().with_size(vec2(1400.0, 900.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(move |_| app); h.run_steps(3); + // The floating window's ×, by its accessible name. let close = |h: &Harness<'_, EffectcraftApp>| { - let e = h.state().auto.elements.iter().find(|e| e.id.starts_with("panel.float.") && e.id.ends_with(".close")).expect("the floating window's ×"); - pos2(e.rect[0] + e.rect[2] / 2.0, e.rect[1] + e.rect[3] / 2.0) + use egui_kittest::kittest::Queryable; + h.get_by_label("Close panel window").rect().center() }; let click = |h: &mut Harness<'_, EffectcraftApp>, pos| { h.event(Event::PointerMoved(pos)); diff --git a/crates/ui-egui/tests/it/ui_scrolling.rs b/crates/ui-egui/tests/it/ui_scrolling.rs index bec6fc244..af994d8e1 100644 --- a/crates/ui-egui/tests/it/ui_scrolling.rs +++ b/crates/ui-egui/tests/it/ui_scrolling.rs @@ -17,7 +17,8 @@ use super::ui_tail::drag; fn harness(w: f32, h: f32) -> Harness<'static, EffectcraftApp> { let mut s = Session::default(); s.execute("file.openDemoProject", json!({})).unwrap(); - let mut h = Harness::builder().with_size(vec2(w, h)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| EffectcraftApp::new(s)); + let mut h = + Harness::builder().with_size(vec2(w, h)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| EffectcraftApp::new(s)); h.run_steps(3); h } @@ -462,7 +463,8 @@ fn effect_values_stay_clear_of_the_keyframe_navigator() { app.session.execute("prop.toggleAnimation", json!({"layer": lid, "path": path})).unwrap(); app.session.execute("prop.set", json!({"layer": lid, "path": path, "value": [123456.7, 123456.7]})).unwrap(); let uid = app.session.active_comp().unwrap().layer(effectcraft_engine::project::LayerId(lid)).unwrap().props.prop(path).unwrap().uid; - app.apply_dock(craft_behavior::dock::Action::Float { panel: PanelKind::EffectControls, rect: [300.0, 150.0, 330.0, 500.0] }).unwrap(); + app.apply_dock(craft_behavior::dock::Action::float(PanelKind::EffectControls, effectcraft_ui_egui::dock_command::rect_of([300.0, 150.0, 330.0, 500.0]))) + .unwrap(); h.run_steps(3); let value = rect(&h, &format!("effectControls.prop.{uid}.value.1")); let nav = rect(&h, &format!("effectControls.prop.{uid}.prevKey")); diff --git a/crates/ui-egui/tests/it/ui_tabs.rs b/crates/ui-egui/tests/it/ui_tabs.rs index fe40ca05f..0b8fd2fcd 100644 --- a/crates/ui-egui/tests/it/ui_tabs.rs +++ b/crates/ui-egui/tests/it/ui_tabs.rs @@ -20,7 +20,10 @@ fn harness() -> (Harness<'static, EffectcraftApp>, u64, u64) { s.execute("layer.addItem", json!({"item": pre})).unwrap(); s.state.open_comps = vec![ItemId(main)]; s.state.active_comp = Some(ItemId(main)); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| EffectcraftApp::new(s)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 1000.0)) + .with_context_setup(effectcraft_ui_egui::framework::install_headless) + .build_eframe(|_| EffectcraftApp::new(s)); h.run_steps(3); (h, pre, main) } @@ -181,8 +184,8 @@ fn panels_dock_beside_others_and_gutters_resize_them() { let dock = |h: &Harness<'_, EffectcraftApp>| h.state().ui.dock.clone(); let tab = rect(&h, "panel.tab.EffectControls"); let tl = rect(&h, "panel.Timeline"); - // Inside the Timeline body's left drop zone. - let depth = craft_ui::docking::SIDE_EDGE_ZONE_DEPTH.min(tl.width().min(tl.height()) / 4.0); + // Inside the Timeline body's left drop zone, a few points in from its edge. + let depth = 16.0_f32.min(tl.width().min(tl.height()) / 4.0); drag(&mut h, tab.center(), pos2(tl.min.x + depth / 2.0, tl.center().y)); assert_eq!(group_of(&dock(&h), PanelKind::EffectControls), Some(vec![PanelKind::EffectControls])); assert!(!group_of(&dock(&h), PanelKind::Timeline).unwrap().contains(&PanelKind::EffectControls)); @@ -251,7 +254,7 @@ fn the_preview_frame_divider_resizes_it() { _ => None, } } - rec(w.layout.root.as_ref()?) + rec(w.layout().root.as_ref()?) } let (preview, props) = (rect(&h, "panel.Preview"), rect(&h, "panel.Properties")); let gap = preview_divider(&h); @@ -440,7 +443,10 @@ fn open_comps_are_tabs_in_the_timeline_row_and_the_rest_are_in_its_overflow_menu .collect(); s.state.open_comps = vec![ItemId(comps[0])]; s.state.active_comp = Some(ItemId(comps[0])); - let mut h = Harness::builder().with_size(egui::vec2(1000.0, 800.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| EffectcraftApp::new(s)); + let mut h = Harness::builder() + .with_size(egui::vec2(1000.0, 800.0)) + .with_context_setup(effectcraft_ui_egui::framework::install_headless) + .build_eframe(|_| EffectcraftApp::new(s)); h.run_steps(3); let alone = rect(&h, "panel.tab.RenderQueue"); h.state_mut().session.state.open_comps = comps.iter().map(|c| ItemId(*c)).collect(); diff --git a/crates/ui-egui/tests/it/ui_viewers.rs b/crates/ui-egui/tests/it/ui_viewers.rs index 122f29a3d..038b0884e 100644 --- a/crates/ui-egui/tests/it/ui_viewers.rs +++ b/crates/ui-egui/tests/it/ui_viewers.rs @@ -65,7 +65,10 @@ fn new_viewers_lock_route_comps_and_activate_on_click() { let c = new_comp(&mut s, "C"); let b = new_comp(&mut s, "B"); let a = new_comp(&mut s, "A"); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| EffectcraftApp::new(s)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 1000.0)) + .with_context_setup(effectcraft_ui_egui::framework::install_headless) + .build_eframe(|_| EffectcraftApp::new(s)); h.run_steps(3); // View ▸ New Viewer: viewer 1 shows A too, viewer 0 (the Composition panel) is locked. invoke(&mut h, "view.newViewer", json!({})); @@ -74,13 +77,13 @@ fn new_viewers_lock_route_comps_and_activate_on_click() { assert_eq!((h.state().ui.active_viewer, shows(&h, 0), shows(&h, 1)), (1, Some(a), Some(a))); // Side by side, so both draw. h.state_mut() - .apply_dock(craft_behavior::dock::Action::Move { - panel: PanelKind::Viewer(1), - anchor: PanelKind::Composition, - placement: craft_behavior::dock::DockPlacement::Split(craft_ui::docking::Zone::Right), - }) + .apply_dock(craft_behavior::dock::Action::move_beside( + PanelKind::Viewer(1), + PanelKind::Composition, + craft_behavior::dock::DockPlacement::Split(craft_behavior::DockSide::End), + )) .unwrap(); - h.state_mut().apply_dock(craft_behavior::dock::Action::Activate { panel: PanelKind::Composition }).unwrap(); + h.state_mut().apply_dock(craft_behavior::dock::Action::activate(PanelKind::Composition)).unwrap(); h.run_steps(3); // Opening B shows it in the active (unlocked) viewer; the locked one keeps A. invoke(&mut h, "comp.open", json!({"comp": b})); @@ -127,7 +130,10 @@ fn a_locked_viewer_keeps_its_comp_when_the_project_panel_opens_another() { let mut s = Session::default(); let b = new_comp(&mut s, "B"); let a = new_comp(&mut s, "A"); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| EffectcraftApp::new(s)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 1000.0)) + .with_context_setup(effectcraft_ui_egui::framework::install_headless) + .build_eframe(|_| EffectcraftApp::new(s)); h.run_steps(3); // Viewer 0 locked to A, and B in viewer 1 (a tab next to it). invoke(&mut h, "view.newViewer", json!({})); @@ -150,17 +156,20 @@ fn viewers_snapshot() { let mut s = Session::default(); s.execute("file.openDemoProject", json!({})).unwrap(); let other = s.project.items.values().filter(|i| i.as_comp().is_some()).map(|i| i.id).find(|id| Some(*id) != s.active_comp_id()).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(|_| EffectcraftApp::new(s)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 1000.0)) + .with_context_setup(effectcraft_ui_egui::framework::install_headless) + .build_eframe(|_| EffectcraftApp::new(s)); h.run_steps(3); invoke(&mut h, "view.newViewer", json!({})); h.state_mut() - .apply_dock(craft_behavior::dock::Action::Move { - panel: PanelKind::Viewer(1), - anchor: PanelKind::Composition, - placement: craft_behavior::dock::DockPlacement::Split(craft_ui::docking::Zone::Right), - }) + .apply_dock(craft_behavior::dock::Action::move_beside( + PanelKind::Viewer(1), + PanelKind::Composition, + craft_behavior::dock::DockPlacement::Split(craft_behavior::DockSide::End), + )) .unwrap(); - h.state_mut().apply_dock(craft_behavior::dock::Action::Activate { panel: PanelKind::Composition }).unwrap(); + h.state_mut().apply_dock(craft_behavior::dock::Action::activate(PanelKind::Composition)).unwrap(); invoke(&mut h, "comp.open", json!({"comp": other.0})); for _ in 0..300 { h.step(); diff --git a/crates/ui-egui/tests/it/ui_workspace_focus.rs b/crates/ui-egui/tests/it/ui_workspace_focus.rs index 62a5498b2..c527379ff 100644 --- a/crates/ui-egui/tests/it/ui_workspace_focus.rs +++ b/crates/ui-egui/tests/it/ui_workspace_focus.rs @@ -11,32 +11,13 @@ use egui::{Event, Id, Key, Modifiers, vec2}; use egui_kittest::Harness; use serde_json::json; -/// The egui id of panel `p`'s dock tab. -fn tab_id(p: PanelKind) -> Id { - craft_ui::docking::DockArea::::hit_id(effectcraft_ui_egui::dock_ui::area_id(), &craft_ui::docking::Hit::Tab(p)) -} - -#[test] -fn workspace_commands_wait_for_migration_without_changing_named_layouts() { - let store = Arc::new(MemoryConfig::default()); - let original = include_str!("../fixtures/workspaces-v1.json"); - store.write("workspaces.json", original).unwrap(); - let mut app = EffectcraftApp::new(Session { config: Some(store.clone()), ..Default::default() }); - assert!(!app.ui.native_outer.is_empty()); - let ctx = egui::Context::default(); - let before = (app.ui.workspace.clone(), app.ui.saved_workspaces.clone(), app.ui.dock.clone()); - for (id, params) in [ - ("window.saveWorkspace", json!({})), - ("window.saveWorkspaceAs", json!({"name": "Too soon"})), - ("window.editWorkspaces", json!({"name": "My Layout", "delete": true})), - ("window.editWorkspaces", json!({"name": "My Layout", "rename": "Too soon"})), - ] { - let error = effectcraft_ui_egui::menus::invoke(&mut app, &ctx, id, params).unwrap_err(); - assert!(error.contains("positions"), "{id}: {error}"); - assert_eq!((app.ui.workspace.clone(), app.ui.saved_workspaces.clone(), app.ui.dock.clone()), before); - assert_eq!(store.read("workspaces.json").as_deref(), Some(original)); - assert_eq!(store.read("workspaces.old.json"), None); - } +/// Whether key focus is on the dock tab whose name starts with `name` (a tab names what its panel +/// shows: "Effect Controls Selected"), as the accessibility tree reports it. +fn tab_focused(h: &Harness<'_, EffectcraftApp>, name: &str) -> bool { + use egui_kittest::kittest::{NodeT, Queryable}; + h.root().children_recursive().any(|n| { + n.is_focused() && n.accesskit_node().role() == egui::accesskit::Role::Tab && n.accesskit_node().label().is_some_and(|label| label.starts_with(name)) + }) } #[test] @@ -51,7 +32,7 @@ fn named_and_current_workspaces_survive_frontend_restart() { let ctx = egui::Context::default(); effectcraft_ui_egui::menus::invoke(&mut app, &ctx, "window.saveWorkspaceAs", json!({"name": "Restart layout"})).unwrap(); let saved = app.ui.dock.clone(); - if let Some(Node::Split { size, .. }) = &mut app.ui.dock.layout.root { + if let Some(Node::Split { size, .. }) = &mut app.ui.dock.layout().root { *size = SplitSize::FixedFirst(390.0); } app.ui.focused = PanelKind::Layer; @@ -154,7 +135,8 @@ fn tab_and_shift_tab_traverse_toolbar_and_space_activates_only_focused_tool() { let mut app = EffectcraftApp::new(session); app.ui.start_screen = false; app.ui.show_menu_bar = false; - let mut h = Harness::builder().with_size(vec2(1400.0, 900.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(move |_| app); + let mut h = + Harness::builder().with_size(vec2(1400.0, 900.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(move |_| app); h.run_steps(3); for _ in 0..8 { key(&mut h, Key::Tab, Modifiers::NONE); @@ -196,40 +178,32 @@ fn tab_traversal_activates_an_inactive_dock_tab_without_editing_the_project() { app.ui.start_screen = false; app.ui.show_menu_bar = false; // Leave the inactive, layer-named tab visible instead of behind the overflow control. - if let Some(Node::Split { first, .. }) = &mut app.ui.dock.layout.root + if let Some(Node::Split { first, .. }) = &mut app.ui.dock.layout().root && let Node::Split { first, .. } = first.as_mut() && let Node::Split { size, .. } = first.as_mut() { *size = SplitSize::FixedFirst(420.0); } - let mut h = Harness::builder().with_size(vec2(1200.0, 760.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(move |_| app); + let mut h = + Harness::builder().with_size(vec2(1200.0, 760.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(move |_| app); h.run_steps(3); assert!(h.state().auto.find("panel.tab.EffectControls").is_some(), "the inactive tab must be visible in this fixture"); let before = h.state().ui.dock.clone(); - let target = tab_id(PanelKind::EffectControls); + let target = "Effect Controls"; let mut tabs = 0; for _ in 0..200 { key(&mut h, Key::Tab, Modifiers::NONE); tabs += 1; - if h.ctx.memory(|m| m.focused()) == Some(target) { + if tab_focused(&h, target) { break; } } - assert_eq!(h.ctx.memory(|m| m.focused()), Some(target)); + assert!(tab_focused(&h, target)); println!("Tab presses from no focus to Effect Controls: {tabs}"); assert_eq!(h.state().ui.dock, before, "traversal alone must not activate a tab"); - // craft-ui outlines the keyboard-focused tab, inset 2 pt, in the dock's accent (EffectCraft's - // focus colour). - let response = h.ctx.read_response(target).unwrap(); - assert!( - h.output().shapes.iter().any(|shape| { - matches!(&shape.shape, egui::Shape::Rect(r) if r.rect == response.rect.shrink(2.0) && r.stroke.color == h.state().tokens.focus && r.stroke.width > 0.0) - }), - "the dock tab must visibly show keyboard focus" - ); key(&mut h, Key::Space, Modifiers::NONE); let mut activated = before; - activated.apply(craft_behavior::dock::Action::Activate { panel: PanelKind::EffectControls }, dock::permissions).unwrap(); + activated.apply(craft_behavior::dock::Action::activate(PanelKind::EffectControls), false, dock::permissions).unwrap(); assert_eq!(h.state().ui.dock, activated); assert_eq!(h.state().ui.focused, PanelKind::EffectControls); assert!(!h.state().playback.playing); @@ -237,7 +211,7 @@ fn tab_traversal_activates_an_inactive_dock_tab_without_editing_the_project() { let inspected = effectcraft_ui_egui::control::inspect(h.state(), &h.ctx); assert_eq!(inspected["keyboardFocus"]["automationId"], "panel.tab.EffectControls"); key(&mut h, Key::Tab, Modifiers::SHIFT); - assert_eq!(h.ctx.memory(|m| m.focused()), Some(tab_id(PanelKind::Project))); + assert!(tab_focused(&h, "Project")); key(&mut h, Key::Enter, Modifiers::NONE); assert_eq!(h.state().ui.focused, PanelKind::Project); assert!(!h.state().playback.playing); @@ -255,7 +229,13 @@ impl ControlDriver { let mut app = EffectcraftApp::new(Session::default()).with_control(rx); app.ui.start_screen = false; app.ui.show_menu_bar = false; - let mut driver = Self { h: Harness::builder().with_size(vec2(1200.0, 760.0)).with_context_setup(effectcraft_ui_egui::framework::install_headless).build_eframe(move |_| app), tx }; + let mut driver = Self { + h: Harness::builder() + .with_size(vec2(1200.0, 760.0)) + .with_context_setup(effectcraft_ui_egui::framework::install_headless) + .build_eframe(move |_| app), + tx, + }; driver.frames(4, true); driver.ok("engine.execute", json!({"command":"comp.new", "params":{"name":"Native Validation", "width":160,"height":90,"duration":1}}), true); driver.ok("engine.execute", json!({"command":"layer.newSolid", "params":{"name":"Validation Red","color":"#ff0000"}}), true); @@ -316,16 +296,16 @@ fn control_root_divider_drag_after_toolbar_and_dock_tab_keyboard_activation() { d.ok("ui.click", json!({"id":"tools.Selection"}), true); // The toolbar can grow as upstream adds controls. Traverse to the actual response // identity rather than assuming a fixed number of focus stops. - let target = tab_id(PanelKind::EffectControls); + let target = "Effect Controls"; for tabs in 1..=200 { d.ok("ui.key", json!({"key":"Tab"}), true); assert!(d.h.state().ui.mini_flowchart.is_none(), "dock-tab traversal must not open a foreground popup"); - if d.h.ctx.memory(|memory| memory.focused()) == Some(target) { + if tab_focused(&d.h, target) { println!("control Tab presses to Effect Controls: {tabs}"); break; } } - assert_eq!(d.h.ctx.memory(|memory| memory.focused()), Some(target), "Effect Controls must remain reachable by control-channel Tab traversal"); + assert!(tab_focused(&d.h, target), "Effect Controls must remain reachable by control-channel Tab traversal"); d.ok("ui.key", json!({"key":"Space"}), true); assert_eq!(d.h.state().ui.focused, PanelKind::EffectControls); d.ok("ui.key", json!({"key":"Tab","shift":true}), true); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index d83c811f9..dc54b05a1 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -156,8 +156,7 @@ frames and can be assigned through `shortcuts.set`. | `ui.screenshot` | `{path?, panel?, id?}` | `{path, width, height}`: a PNG of the window, or cropped to one panel or element. The panel or element rectangle is resolved when the capture is issued (after the UI settles), so it follows a panel that moved; a panel or id that is not on screen is retried and then reported, never replaced by a whole-window shot. | Element ids are stable, for example `tools.Selection`, `panel.Timeline`, `panel.tab.EffectControls`, -`panel.tab.Timeline.` (one Timeline tab per open comp; `panel.tab.Timeline` is the shown -one), `panel.tab.Viewer()` and `viewers.` (View ▸ New Viewer's other Composition viewers; +`panel.tab.Viewer()` and `viewers.` (View ▸ New Viewer's other Composition viewers; `viewers.0` is the Composition panel while another viewer is active), `header.workspace.Animation`, `project.item.` (a double-click opens the item, Enter renames it), `viewer.comp`, `viewer.handle..`, `timeline.layer..bar`, `timeline.layer..nestedMarker.` (a precomp's comp markers), `timeline.layer..twirl`, `timeline.layer..row` (click selects, @@ -231,12 +230,14 @@ takes a name, or as `{"Viewer":42}` and `{"ScriptPanel":77}` for viewers and Scr floating window holding Info. `Open` and `OpenAt` are refused: panels open through the panel commands (`window.panel`, `ui.panel.show`), which run the viewer and ScriptUI lifecycles. Closing runs them too. Pointer gestures dispatch through this command. -- craft-ui's commands: `window.panel.move`, `.float`, `.dock`, `.activate`, `.close`, - `.closeGroup`, `.closeOthers`, `.minimize`, `.iconic`, `.window` and `.layout`, with the params - of craft-ui's `DockCommand` (`docs/ui-docking.md` in craft-libs). `window.panel.` +- The panel commands `window.panel.move {panel, anchor, zone?, before?, group?}`, + `.float {panel, x?, y?, width?, height?, group?, column?}`, + `.dock {panel, anchor?, zone?, before?, group?, column?, side?}`, `.activate`, `.close`, + `.closeGroup`, `.closeOthers`, `.minimize {minimized?}`, `.iconic {iconic?}`, + `.window {native?}` (as `window.panelWindow`) and `.layout {action}`. `window.panel.` (`window.panel.Align`) opens and shows that panel. `window.panel.activate` on a closed panel reopens it where it was. -- `ui.dock {operation, panel, …}` or `ui.dock {action}`: craft-ui's `ui.dock` operations +- `ui.dock {operation, panel, …}` or `ui.dock {action}`: the operations (`open`, `close`, `activate`, `float {rect}`, `moveFloating {rect}`, `move {target, zone?, before?}`, `setStackOpen {open}`, `resizeStack {height}`, `resizeSplit {path, size}`; `rect` is `[x, y, width, height]`). It returns @@ -261,12 +262,11 @@ run the main window's shortcuts, and files dropped on one import as on the main modal dialog is open, floating windows take no input. The automation ids of the docking chrome are `panel.tab.`, `panel.drag.` (a -group's drag bar), `panel.tabs.more.`, `panel.menu.` (≡), `panel.header.` -(a stacked panel's open and close button), `panel.tab..lock` (viewer lock), -`panel.tab.Timeline.` and `panel.tab.Timeline.close` (the Timeline's comp tabs), -`panel.float..move`, `.close`, `.resize` and `.resize.` for floating window `n`, +group's drag bar), `panel.menu.` (≡), `panel.tab..lock` (viewer lock), +`panel.float..move`, `.resize` and `.resize.` for floating window `n`, and `dock.gutter.` for dividers (`a`/`b` per split level; a stack's gap below entry `i` adds -`s`) and `dock.corner..` where two dividers meet. +`s`). The other parts (the Timeline's comp tabs, a floating window's close button, the tab +overflow menu) are found by their accessible names. Saved workspaces (`workspaces.json`, version 2) hold craft-ui `Workspace`s: the layout, the closed panels with where each goes back, the lock, and each floating window's desktop place. A