FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
UI.9: draw panels with craft-ui shared docking (Frame profile)
aiongg2a19266ba884
diff --git a/Cargo.lock b/Cargo.lockindex 43b781b41..e2eb13f25 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1019,7 +1019,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=82a24b006eefa036b43c09[[package]]name = "craft-ui"version = "0.1.0"-source = "git+https://github.com/storytold/craft-libs?rev=5c874d51eeb3de70e735c8ce87a59a7dedd47675#5c874d51eeb3de70e735c8ce87a59a7dedd47675"+source = "git+https://github.com/storytold/craft-libs?rev=787b70627461a3c988157ed776e8f6051cbc94c3#787b70627461a3c988157ed776e8f6051cbc94c3"dependencies = ["egui","serde",diff --git a/Cargo.toml b/Cargo.tomlindex 625558e91..dfa2509bb 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -74,7 +74,7 @@ craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-l# ui# Shared frontend components; keep this dependency above the engine boundary.-craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5c874d51eeb3de70e735c8ce87a59a7dedd47675", features = ["serde"] }+craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "787b70627461a3c988157ed776e8f6051cbc94c3", features = ["serde"] }egui = "0.36"eframe = { version = "0.36", default-features = false }egui_kittest = "0.36"diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rsindex d144bd57e..929f9da6c 100644--- a/crates/ui-egui/src/dock.rs+++ b/crates/ui-egui/src/dock.rs@@ -1,11 +1,12 @@-//! Premiere-style docking: a tree of splits and tab groups. Panels are rounded frames separated by-//! thin gutters; each group has a tab strip (active tab bright, with a panel menu "≡"); the focused-//! panel gets a blue outline. Gutters drag to resize; workspaces are serialized trees.+//! FilmCraft's panels and workspaces. craft-ui's docking (Frame profile) owns the frame tree,+//! the tab strips, floating windows and gestures (`dock_ui.rs` draws it); this module names the+//! panels, builds the built-in workspaces and draws the Timeline's sequence tabs.use egui::{Align2, Rect, Sense, Stroke, StrokeKind, pos2, vec2};use serde::{Deserialize, Serialize};-use craft_ui::layout::{ResizeHandle, ResizeHandleStyle, SplitAxis, SplitSize as SharedSplitSize, split_rect};+use craft_ui::docking::{Action, Floating, Node};+use craft_ui::layout::{SplitAxis, SplitSize};use crate::icons::{self, Icon};use crate::theme::Tokens;@@ -133,48 +134,19 @@ impl PanelKind {}}-#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]-pub enum SplitSize {- Ratio(f32),- /// First child has a fixed size in points.- FixedA(f32),- /// Second child has a fixed size in points.- FixedB(f32),-}--impl SplitSize {- fn shared(self) -> SharedSplitSize {- match self {- Self::Ratio(value) => SharedSplitSize::Ratio(value),- Self::FixedA(value) => SharedSplitSize::FixedFirst(value),- Self::FixedB(value) => SharedSplitSize::FixedSecond(value),- }- }-}--#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]-pub enum DockNode {- /// `vertical`: children stacked top/bottom; else side by side.- Split {- vertical: bool,- size: SplitSize,- a: Box<DockNode>,- b: Box<DockNode>,- },- Tabs {- panels: Vec<PanelKind>,- active: usize,- },-}+/// A FilmCraft panel arrangement: craft-ui's frame tree and floating windows.+pub type Layout = craft_ui::docking::Layout<PanelKind>;+/// What a saved workspace stores: its layout, closed panels and lock.+pub type Workspace = craft_ui::docking::Workspace<PanelKind>;-fn tabs(p: &[PanelKind], active: usize) -> DockNode {- DockNode::Tabs { panels: p.to_vec(), active }+fn tabs(p: &[PanelKind], active: usize) -> Node<PanelKind> {+ Node::Tabs { panels: p.to_vec(), active }}-fn hsplit(size: SplitSize, a: DockNode, b: DockNode) -> DockNode {- DockNode::Split { vertical: false, size, a: Box::new(a), b: Box::new(b) }+fn hsplit(size: SplitSize, a: Node<PanelKind>, b: Node<PanelKind>) -> Node<PanelKind> {+ Node::Split { axis: SplitAxis::Horizontal, size, first: Box::new(a), second: Box::new(b) }}-fn vsplit(size: SplitSize, a: DockNode, b: DockNode) -> DockNode {- DockNode::Split { vertical: true, size, a: Box::new(a), b: Box::new(b) }+fn vsplit(size: SplitSize, a: Node<PanelKind>, b: Node<PanelKind>) -> Node<PanelKind> {+ Node::Split { axis: SplitAxis::Vertical, size, first: Box::new(a), second: Box::new(b) }}pub const WORKSPACES: [&str; 9] = ["Editing", "Assembly", "Color", "Effects", "Audio", "Captions and Graphics", "Learning", "Review", "All Panels"];@@ -191,15 +163,19 @@ pub struct WorkspacePrefs {pub current: String,}-/// A named layout. `layout` is a [`DockNode`] kept as JSON, so one unreadable entry (a panel a-/// newer version added) doesn't lose the others.+/// A named workspace. `workspace` is a craft-ui [`Workspace`] kept as JSON, so one unreadable+/// entry (a panel a newer version added) doesn't lose the others. Files written before+/// FilmCraft used craft-ui workspaces hold a frame tree in `layout` and floating groups in+/// `floating` instead; [`saved_workspace`] reads them, and saving writes `workspace`.#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase", default)]pub struct SavedWorkspace {pub name: String,+ #[serde(skip_serializing_if = "serde_json::Value::is_null")]+ pub workspace: serde_json::Value,+ #[serde(skip_serializing_if = "serde_json::Value::is_null")]pub layout: serde_json::Value,- /// Kept raw for the same per-workspace failure isolation as the dock tree.- #[serde(default, skip_serializing_if = "serde_json::Value::is_null")]+ #[serde(skip_serializing_if = "serde_json::Value::is_null")]pub floating: serde_json::Value,}@@ -254,63 +230,145 @@ pub fn find(prefs: &WorkspacePrefs, query: &str) -> Option<String> {names(prefs).into_iter().find(|n| slug(n) == slug(query))}-/// The saved layout of a workspace: the user's saved version, else the built-in default.-pub fn saved_layout(prefs: &WorkspacePrefs, name: &str) -> DockNode {- saved_docking(prefs, name).root-}--pub fn saved_docking(prefs: &WorkspacePrefs, name: &str) -> Layout {+/// A workspace as saved: the user's saved version, else the built-in default. An entry that+/// does not read or validate falls back to the default and stays in the file untouched.+pub fn saved_workspace(prefs: &WorkspacePrefs, name: &str) -> Workspace {let saved = prefs.saved.iter().find(|saved| saved.name == name).and_then(|saved| {- let mut layout = Layout {- root: serde_json::from_value(saved.layout.clone()).ok()?,- floating: if saved.floating.is_null() { vec![] } else { serde_json::from_value(saved.floating.clone()).ok()? },+ let workspace = if saved.workspace.is_null() {+ Workspace::new(legacy::layout(&saved.layout, &saved.floating)?)+ } else {+ serde_json::from_value::<Workspace>(saved.workspace.clone()).ok()?};- if layout.floating.is_empty() {- migrate_legacy_effects(&mut layout.root);- }- layout.validate().ok().map(|()| layout)+ workspace.validate().ok().map(|()| workspace)});- saved.unwrap_or_else(|| Layout { root: workspace(name), floating: vec![] })+ saved.unwrap_or_else(|| Workspace::new(workspace(name)))+}++/// The saved layout of a workspace (see [`saved_workspace`]).+pub fn saved_docking(prefs: &WorkspacePrefs, name: &str) -> Layout {+ saved_workspace(prefs, name).layout}-/// Older Effects workspaces stored the same Effect Controls panel twice: selected beside-/// Source, and an inactive duplicate beside Essential Graphics. Remove only that known-/// duplicate shape; unrelated malformed or ambiguous saved layouts still fail validation.-fn migrate_legacy_effects(root: &mut DockNode) {- let Ok(shared) = crate::dock_shared::encode(root, &[]) else { return };- if shared.panels().iter().filter(|panel| ***panel == PanelKind::EffectControls).count() != 2 {- return;+/// The frame tree and floating groups FilmCraft wrote before its workspaces were craft-ui+/// [`Workspace`]s.+mod legacy {+ use super::{Floating, Layout, Node, PanelKind, SplitAxis, SplitSize};+ use serde::Deserialize;++ const MAX_DEPTH: usize = 32;++ #[derive(Deserialize)]+ enum Tree {+ /// `vertical`: children stacked top/bottom; else side by side.+ Split {+ vertical: bool,+ size: Size,+ a: Box<Tree>,+ b: Box<Tree>,+ },+ Tabs {+ panels: Vec<PanelKind>,+ active: usize,+ },}- fn selected_source(node: &DockNode) -> bool {- match node {- DockNode::Tabs { panels, active } => {- panels.contains(&PanelKind::Source) && panels.contains(&PanelKind::AudioClipMixer) && panels.get(*active) == Some(&PanelKind::EffectControls)++ #[derive(Deserialize)]+ enum Size {+ Ratio(f32),+ FixedA(f32),+ FixedB(f32),+ }++ #[derive(Deserialize)]+ struct Group {+ panels: Vec<PanelKind>,+ active: usize,+ rect: [f32; 4],+ }++ fn node(tree: Tree, depth: usize) -> Option<Node<PanelKind>> {+ if depth > MAX_DEPTH {+ return None;+ }+ Some(match tree {+ Tree::Tabs { panels, active } => Node::Tabs { panels, active },+ Tree::Split { vertical, size, a, b } => Node::Split {+ axis: if vertical { SplitAxis::Vertical } else { SplitAxis::Horizontal },+ size: match size {+ Size::Ratio(value) => SplitSize::Ratio(value),+ Size::FixedA(value) => SplitSize::FixedFirst(value),+ Size::FixedB(value) => SplitSize::FixedSecond(value),+ },+ first: Box::new(node(*a, depth + 1)?),+ second: Box::new(node(*b, depth + 1)?),+ },+ })+ }++ pub(super) fn layout(root: &serde_json::Value, floating: &serde_json::Value) -> Option<Layout> {+ let tree: Tree = serde_json::from_value(root.clone()).ok()?;+ let floating: Vec<Group> = if floating.is_null() { vec![] } else { serde_json::from_value(floating.clone()).ok()? };+ let mut root = match node(tree, 0)? {+ Node::Tabs { panels, .. } if panels.is_empty() => None,+ root => Some(root),+ };+ if floating.is_empty()+ && let Some(root) = root.as_mut()+ {+ migrate_effects(root);+ }+ Some(Layout { root, floating: floating.into_iter().map(|group| Floating::single(group.panels, group.active, group.rect)).collect() })+ }++ /// Effects workspaces saved by early versions held the Effect Controls panel twice: selected+ /// beside Source, and an inactive duplicate beside Essential Graphics. Remove only that known+ /// duplicate shape; other malformed saved layouts still fail validation.+ fn migrate_effects(root: &mut Node<PanelKind>) {+ fn count(node: &Node<PanelKind>) -> usize {+ match node {+ Node::Tabs { panels, .. } => panels.iter().filter(|panel| **panel == PanelKind::EffectControls).count(),+ Node::Split { first, second, .. } => count(first) + count(second),+ _ => 0,}- DockNode::Split { a, b, .. } => selected_source(a) || selected_source(b),}- }- fn remove_inactive(node: &mut DockNode) {- match node {- DockNode::Tabs { panels, active } if panels.as_slice() == [PanelKind::EffectControls, PanelKind::EssentialGraphics] && *active == 1 => {- panels.remove(0);- *active = 0;+ fn selected_source(node: &Node<PanelKind>) -> bool {+ match node {+ Node::Tabs { panels, active } => {+ panels.contains(&PanelKind::Source)+ && panels.contains(&PanelKind::AudioClipMixer)+ && panels.get(*active) == Some(&PanelKind::EffectControls)+ }+ Node::Split { first, second, .. } => selected_source(first) || selected_source(second),+ _ => false,}- DockNode::Split { a, b, .. } => {- remove_inactive(a);- remove_inactive(b);+ }+ fn remove_inactive(node: &mut Node<PanelKind>) {+ match node {+ Node::Tabs { panels, active } if panels.as_slice() == [PanelKind::EffectControls, PanelKind::EssentialGraphics] && *active == 1 => {+ panels.remove(0);+ *active = 0;+ }+ Node::Split { first, second, .. } => {+ remove_inactive(first);+ remove_inactive(second);+ }+ _ => {}}- DockNode::Tabs { .. } => {}}- }- if selected_source(root) {- remove_inactive(root);+ if count(root) == 2 && selected_source(root) {+ remove_inactive(root);+ }}}/// The default layout of a named workspace.-pub fn workspace(name: &str) -> DockNode {+pub fn workspace(name: &str) -> Layout {+ Layout { root: Some(workspace_root(name)), floating: vec![] }+}++fn workspace_root(name: &str) -> Node<PanelKind> {use PanelKind::*;- use SplitSize::*;+ use SplitSize::{FixedFirst as FixedA, FixedSecond as FixedB, Ratio};let bottom_editing = || hsplit(FixedA(64.0), tabs(&[Tools], 0), hsplit(FixedB(116.0), tabs(&[Timeline], 0), tabs(&[AudioMeters], 0)));match name {"Assembly" => vsplit(@@ -385,505 +443,283 @@ pub fn workspace(name: &str) -> DockNode {}}-impl DockNode {- /// Every panel in the tree.- pub fn panels(&self, out: &mut Vec<PanelKind>) {- match self {- DockNode::Split { a, b, .. } => {- a.panels(out);- b.panels(out);+/// FilmCraft's queries and changes on a [`Layout`] beyond craft-ui's actions.+pub trait LayoutExt {+ /// Whether `panel` is the shown tab of its frame or floating window.+ fn is_visible(&self, panel: PanelKind) -> bool;+ /// The shown panel of each frame in layout order, then of each floating window.+ fn visible_panels(&self) -> Vec<PanelKind>;+ /// Put the Timeline panel back where the workspaces keep it (left of the audio meters) after+ /// it was closed, so opening a sequence always has somewhere to show it.+ fn restore_timeline(&mut self);+ /// Add a panel as a tab next to `near` (else Project, Program or the first docked panel).+ fn open_near(&mut self, panel: PanelKind, near: PanelKind);+}++impl LayoutExt for Layout {+ fn is_visible(&self, panel: PanelKind) -> bool {+ self.panel_state(&panel) == craft_ui::docking::PanelState::Front+ }++ fn visible_panels(&self) -> Vec<PanelKind> {+ fn walk(node: &Node<PanelKind>, out: &mut Vec<PanelKind>) {+ match node {+ Node::Tabs { panels, active } => out.extend(panels.get(*active).copied()),+ Node::Split { first, second, .. } => {+ walk(first, out);+ walk(second, out);+ }+ _ => {}}- DockNode::Tabs { panels, .. } => out.extend(panels.iter().copied()),}- }- pub fn contains(&self, p: PanelKind) -> bool {- let mut v = Vec::new();- self.panels(&mut v);- v.contains(&p)- }- /// Make `p` the active tab of its group. Returns false if not present.- pub fn activate(&mut self, p: PanelKind) -> bool {- crate::dock_shared::apply_tree(self, craft_ui::docking::Action::Activate { panel: p })- }- pub fn is_visible(&self, p: PanelKind) -> bool {- match self {- DockNode::Split { a, b, .. } => a.is_visible(p) || b.is_visible(p),- DockNode::Tabs { panels, active } => panels.get(*active) == Some(&p),+ let mut out = Vec::new();+ if let Some(root) = &self.root {+ walk(root, &mut out);}+ out.extend(self.floating.iter().flat_map(|window| window.groups.iter().filter_map(|group| group.panels.get(group.active).copied())));+ out}- /// Close a panel (remove its tab; empty groups collapse their split).- pub fn close(&mut self, p: PanelKind) {- crate::dock_shared::apply_tree(self, craft_ui::docking::Action::Close { panel: p });- }- /// Put the Timeline panel back where the workspaces keep it (left of the audio meters) after- /// it was closed, so opening a sequence always has somewhere to show it.- pub fn restore_timeline(&mut self) {- if self.contains(PanelKind::Timeline) {++ fn restore_timeline(&mut self) {+ if self.contains(&PanelKind::Timeline) {return;}- fn beside_meters(n: &mut DockNode) -> bool {+ fn beside_meters(n: &mut Node<PanelKind>) -> bool {match n {- DockNode::Split { a, b, .. } => beside_meters(a) || beside_meters(b),- DockNode::Tabs { panels, .. } if panels.as_slice() == [PanelKind::AudioMeters] => {- *n = hsplit(SplitSize::FixedB(116.0), tabs(&[PanelKind::Timeline], 0), tabs(&[PanelKind::AudioMeters], 0));+ Node::Split { first, second, .. } => beside_meters(first) || beside_meters(second),+ Node::Tabs { panels, .. } if panels.as_slice() == [PanelKind::AudioMeters] => {+ *n = hsplit(SplitSize::FixedSecond(116.0), tabs(&[PanelKind::Timeline], 0), tabs(&[PanelKind::AudioMeters], 0));true}- DockNode::Tabs { .. } => false,+ _ => false,}}- if !beside_meters(self) {+ if !self.root.as_mut().is_some_and(beside_meters) {self.open_near(PanelKind::Timeline, PanelKind::Project);}}- /// Add a panel as a tab next to `near` (or into the first group).- pub fn open_near(&mut self, p: PanelKind, near: PanelKind) {- if crate::dock_shared::encode(self, &[]).is_err() {- return;- }- let anchor = [near, PanelKind::Project, PanelKind::Program].into_iter().find(|panel| self.contains(*panel)).or_else(|| {- let mut panels = Vec::new();- self.panels(&mut panels);- panels.first().copied()- });- crate::dock_shared::apply_tree(self, craft_ui::docking::Action::Open { panel: p, anchor });- }-}-/// A floating group retains the same panel identities as docked tabs.-#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]-pub struct Floating {- pub panels: Vec<PanelKind>,- pub active: usize,- /// [x, y, width, height] in logical points.- pub rect: [f32; 4],+ fn open_near(&mut self, panel: PanelKind, near: PanelKind) {+ let docked = Layout { root: self.root.clone(), floating: vec![] };+ let anchor = [near, PanelKind::Project, PanelKind::Program]+ .into_iter()+ .find(|candidate| docked.contains(candidate))+ .or_else(|| docked.panels().first().map(|first| **first));+ let _ = self.apply(Action::Open { panel, anchor });+ }}-/// App persistence shape; all mutations pass through the shared docking model.-#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]-pub struct Layout {- pub root: DockNode,- #[serde(default)]- pub floating: Vec<Floating>,+/// The sequences open in the Timeline panel, in tab order: `(project item id, name)`.+#[derive(Debug, Clone, Default)]+pub struct SeqTabs {+ pub open: Vec<(u64, String)>,+ pub active: Option<u64>,}-impl Layout {- pub fn apply(&mut self, action: craft_ui::docking::Action<PanelKind>) -> Result<(), String> {- crate::dock_shared::apply(self, action)+impl SeqTabs {+ /// The Timeline panel's tab label: its active sequence.+ pub fn label(&self) -> String {+ let name = self.open.iter().find(|(id, _)| self.active == Some(*id)).map(|(_, n)| n.clone());+ name.unwrap_or_else(|| tl!("Timeline: (no sequences)").into())}- pub fn validate(&self) -> Result<(), String> {- crate::dock_shared::encode(&self.root, &self.floating)?.validate().map_err(|error| error.to_string())- }- pub fn contains(&self, panel: PanelKind) -> bool {- self.root.contains(panel) || self.floating.iter().any(|group| group.panels.contains(&panel))- }-}--/// One laid-out tab group.-pub struct Group {- pub path: String,- pub rect: Rect,- pub content: Rect,- pub panels: Vec<PanelKind>,- pub active: usize,}-/// Actions produced by interacting with the dock chrome.+/// What the sequence tabs ask for.#[derive(Debug, Clone, PartialEq)]-pub enum DockAction {- Activate(PanelKind),- BeginDrag(PanelKind),- Focus(PanelKind),- Close(PanelKind),- PanelMenu(PanelKind, egui::Pos2),- /// A sequence tab of the Timeline panel was clicked / closed (project item id).- OpenSequence(u64),- CloseSequence(u64),+pub enum SeqAction {+ Open(u64),+ Close(u64),/// A sequence tab was dragged past a neighbour: its new place among the sequence tabs.- MoveSequence(u64, usize),+ Move(u64, usize),+ /// A right click: show that sequence and open the Timeline's panel menu there.+ Menu(u64, egui::Pos2),}-/// Lay out the tree into group rects (with `gap` gutters) and handle gutter dragging.-pub fn layout(ui: &mut egui::Ui, node: &mut DockNode, rect: Rect, t: &Tokens, path: &str, out: &mut Vec<Group>, reg: &mut crate::automation::Registry) {- let mut actions = Vec::new();- layout_with_actions(ui, node, rect, t, path, out, reg, &mut actions);- for action in actions {- crate::dock_shared::apply_tree(node, action);- }-}--/// Lay out chrome while returning mutations for the application's UI command route.-pub fn layout_with_actions(- ui: &mut egui::Ui,- node: &mut DockNode,- rect: Rect,- t: &Tokens,- path: &str,- out: &mut Vec<Group>,- reg: &mut crate::automation::Registry,- actions: &mut Vec<craft_ui::docking::Action<PanelKind>>,-) {- layout_inner(ui, node, rect, t, path, &[], out, reg, actions);-}--fn layout_inner(- ui: &mut egui::Ui,- node: &mut DockNode,- rect: Rect,- t: &Tokens,- path: &str,- tree_path: &[bool],- out: &mut Vec<Group>,- reg: &mut crate::automation::Registry,- actions: &mut Vec<craft_ui::docking::Action<PanelKind>>,-) {- match node {- DockNode::Tabs { panels, active } => {- let tab_h = if panels.len() == 1 && panels[0].compact() { 8.0 } else { t.tab_h };- let content = Rect::from_min_max(pos2(rect.min.x, rect.min.y + tab_h), rect.max);- out.push(Group { path: path.to_string(), rect, content, panels: panels.clone(), active: *active });- }- DockNode::Split { vertical, size, a, b } => {- let axis = if *vertical { SplitAxis::Vertical } else { SplitAxis::Horizontal };- let Some(split) = split_rect(rect, axis, size.shared(), t.gap, 20.0) else { return };- let id = egui::Id::new(("dock-gutter", path.to_string()));- let handle_style = ResizeHandleStyle { hovered: t.focus.gamma_multiply(0.4), dragged: t.focus.gamma_multiply(0.9), focused: t.focus };- let label = if *vertical { tl!("Height:") } else { tl!("Width:") };- let response = ResizeHandle::new(id, axis, split.divider, label, handle_style).value(split.first_size(), 0.0..=split.available()).show(ui);- reg.add_response(&format!("dock.gutter.{path}"), &response.response, "gutter");- if response.delta != 0.0- && let Some(resized) = split.resized(size.shared(), response.delta, 40.0)- {- actions.push(craft_ui::docking::Action::ResizeSplit { path: tree_path.to_vec(), size: resized });- }- let mut first_path = tree_path.to_vec();- first_path.push(false);- let mut second_path = tree_path.to_vec();- second_path.push(true);- layout_inner(ui, a, split.first, t, &format!("{path}a"), &first_path, out, reg, actions);- layout_inner(ui, b, split.second, t, &format!("{path}b"), &second_path, out, reg, actions);- }- }-}--/// Draw a group's frame + tab strip. Returns actions (tab clicks, panel menu, focus).-/// The sequences open in the Timeline panel, in tab order: `(project item id, name)`.-#[derive(Debug, Clone, Default)]-pub struct SeqTabs {- pub open: Vec<(u64, String)>,- pub active: Option<u64>,-}--pub fn draw_group_chrome(- ui: &mut egui::Ui,- g: &Group,- focused: PanelKind,- seqs: &SeqTabs,- t: &Tokens,- reg: &mut crate::automation::Registry,-) -> Vec<DockAction> {- let chrome = draw_group_chrome_details(ui, g, seqs, t, reg);- paint_group_focus(ui, g, focused, t);- chrome.actions+fn sequence_widths(ui: &egui::Ui, seqs: &SeqTabs) -> Vec<f32> {+ seqs.open+ .iter()+ .map(|(id, name)| {+ let label = ui.painter().layout_no_wrap(name.clone(), Tokens::ui(12.0), egui::Color32::WHITE).size().x;+ label + 16.0 + if seqs.active == Some(*id) { 16.0 } else { 0.0 }+ })+ .collect()}-#[derive(Default)]-pub struct Chrome {- pub actions: Vec<DockAction>,- pub tabs: Vec<(PanelKind, Rect)>,+/// The width [`sequence_tabs`] needs to show every open sequence.+pub fn sequence_tabs_width(ui: &egui::Ui, seqs: &SeqTabs) -> f32 {+ sequence_widths(ui, seqs).iter().map(|w| w + 8.0).sum::<f32>() + 12.0}-pub fn draw_group_chrome_details(ui: &mut egui::Ui, g: &Group, seqs: &SeqTabs, t: &Tokens, reg: &mut crate::automation::Registry) -> Chrome {+/// Draw the Timeline panel's sequence tabs in `strip`: one tab per open sequence, × on the active+/// one, drag to reorder, middle-click to close, the wheel to step through them, and a » list+/// when they don't fit.+pub fn sequence_tabs(ui: &mut egui::Ui, strip: Rect, seqs: &SeqTabs, t: &Tokens, reg: &mut crate::automation::Registry) -> Vec<SeqAction> {let mut actions = Vec::new();- let mut tab_rects: Vec<(PanelKind, Rect)> = Vec::new();- let painter = ui.painter().clone();- painter.rect_filled(g.rect, t.radius, t.panel_bg);- let active_panel = g.panels.get(g.active).copied();- let compact = g.panels.len() == 1 && g.panels[0].compact();- // A narrow header grip moves the entire panel, including Timeline panels whose tabs- // separately reorder open sequences.- if let Some(panel) = active_panel {- let grip = Rect::from_min_size(g.rect.min, vec2(if compact { g.rect.width() } else { 10.0 }, if compact { 8.0 } else { t.tab_h }));- let response = ui.interact(grip, egui::Id::new(("panel-drag", g.path.clone())), Sense::drag());- reg.add_response(&format!("panel.drag.{}", panel.id()), &response, "Move panel");- if response.drag_started() {- actions.push(DockAction::BeginDrag(panel));+ let painter = ui.painter_at(strip);+ let active_at = seqs.open.iter().position(|(id, _)| seqs.active == Some(*id)).unwrap_or(0);+ let text_y = strip.center().y;+ // Which tabs fit. The active tab is always shown: tabs before it are left out until it+ // fits, then as many after it as there is room for. The » list reaches the rest.+ let widths = sequence_widths(ui, seqs);+ let span = |from: usize, to: usize| widths.get(from..=to).map_or(0.0, |w| w.iter().sum::<f32>() + 8.0 * w.len() as f32);+ let room = strip.width() - 12.0;+ let all_fit = span(0, seqs.open.len().saturating_sub(1)) <= room;+ let room = if all_fit { room } else { room - 24.0 };+ let mut first = 0;+ while first < active_at && span(first, active_at) > room {+ first += 1;+ }+ let mut last = active_at.max(first);+ while last + 1 < seqs.open.len() && span(first, last + 1) <= room {+ last += 1;+ }+ let list_id = egui::Id::new("timeline-tab-list");+ let more = (!all_fit).then(|| Rect::from_min_size(pos2(strip.max.x - 22.0, strip.center().y - 10.0), vec2(18.0, 20.0)));+ let mut list_opened = false;+ if let Some(r) = more {+ let resp = ui.interact(r, egui::Id::new("timeline-tab-overflow"), Sense::click());+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, resp.enabled(), "more tabs"));+ reg.add_response("timeline.tabs.more", &resp, "more tabs");+ let c = if resp.hovered() { t.tab_text_active } else { t.tab_text };+ icons::paint(&painter, r.shrink(4.0).translate(vec2(-2.0, 0.0)), Icon::ChevronRight, c);+ icons::paint(&painter, r.shrink(4.0).translate(vec2(2.0, 0.0)), Icon::ChevronRight, c);+ paint_widget_focus(&painter, &resp, t);+ if resp.clicked() {+ let open = ui.ctx().data(|d| d.get_temp::<bool>(list_id)).unwrap_or(false);+ ui.ctx().data_mut(|d| d.insert_temp(list_id, !open));+ list_opened = !open;}}- if compact {- // grip dots- let c = pos2(g.rect.center().x, g.rect.min.y + 4.0);- for dx in [-4.0, 0.0, 4.0] {- painter.circle_filled(c + vec2(dx, 0.0), 1.0, t.text_faint);+ // The wheel over the strip steps through the tabs: down = next, up = previous, one tab per+ // notch (trackpad scrolling adds up to a notch first), stopping at the ends.+ let wheel_id = egui::Id::new("timeline-tab-wheel");+ if ui.rect_contains_pointer(strip) && !seqs.open.is_empty() {+ const NOTCH: f32 = 40.0;+ let total = ui.ctx().data(|d| d.get_temp::<f32>(wheel_id)).unwrap_or(0.0) + crate::panels::timeline::wheel_input(ui.ctx()).delta.y;+ let steps = (total / NOTCH).trunc();+ ui.ctx().data_mut(|d| d.insert_temp(wheel_id, total - steps * NOTCH));+ let to = (active_at as i64).saturating_sub(steps as i64).clamp(0, seqs.open.len() as i64 - 1) as usize;+ if let Some((id, _)) = seqs.open.get(to).filter(|_| to != active_at) {+ actions.push(SeqAction::Open(*id));}} else {- let strip = Rect::from_min_size(g.rect.min, vec2(g.rect.width(), t.tab_h));- // the Timeline panel shows one tab per open sequence (its own tab names the sequence)- struct Tab {- panel: PanelKind,- seq: Option<u64>,- title: String,- active: bool,- }- let mut tabs: Vec<Tab> = Vec::new();- for (i, p) in g.panels.iter().enumerate() {- let active = i == g.active;- if *p == PanelKind::Timeline && active && !seqs.open.is_empty() {- tabs.extend(seqs.open.iter().map(|(id, name)| Tab { panel: *p, seq: Some(*id), title: name.clone(), active: seqs.active == Some(*id) }));- } else if *p == PanelKind::Timeline {- let name = seqs.open.iter().find(|(id, _)| seqs.active == Some(*id)).map(|(_, n)| n.clone());- tabs.push(Tab { panel: *p, seq: None, title: name.unwrap_or_else(|| tl!("Timeline: (no sequences)").into()), active });- } else {- tabs.push(Tab { panel: *p, seq: None, title: crate::i18n::t(p.title()).to_string(), active });- }+ ui.ctx().data_mut(|d| d.remove::<f32>(wheel_id));+ }+ let mut x = strip.min.x + 12.0;+ let mut seq_rects: Vec<(u64, Rect)> = Vec::new();+ let mut dragged: Option<u64> = None;+ for (i, (id, name)) in seqs.open.iter().enumerate().take(last + 1).skip(first) {+ let is_active = seqs.active == Some(*id);+ let galley = painter.layout_no_wrap(name.clone(), Tokens::ui(12.0), if is_active { t.tab_text_active } else { t.tab_text });+ let close_w = if is_active { 16.0 } else { 0.0 };+ let w = widths.get(i).copied().unwrap_or(0.0);+ let tab_rect = Rect::from_min_size(pos2(x, strip.min.y), vec2(w, strip.height()));+ // a sequence tab keeps its identity when the tabs are reordered under the pointer+ let resp = ui.interact(tab_rect, egui::Id::new(("tab-seq", *id)), Sense::click_and_drag());+ resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, resp.enabled(), is_active, name));+ ui.ctx().accesskit_node_builder(resp.id, |node| {+ node.set_role(egui::accesskit::Role::Tab);+ node.set_selected(is_active);+ });+ paint_widget_focus(&painter, &resp, t);+ seq_rects.push((*id, tab_rect));+ if resp.dragged() {+ dragged = Some(*id);}- let activate = |tab: &Tab, actions: &mut Vec<DockAction>| match tab.seq {- Some(id) => actions.push(DockAction::OpenSequence(id)),- None => actions.push(DockAction::Activate(tab.panel)),- };- let active_at = tabs.iter().position(|tab| tab.active).unwrap_or(0);- let text_y = strip.min.y + 16.0;- // Which tabs fit. The active tab is always shown: tabs before it are left out until it- // fits, then as many after it as there is room for. Tabs that are left out are reached- // through the » list at the right end of the strip.- let widths: Vec<f32> = tabs- .iter()- .map(|tab| {- let label = painter.layout_no_wrap(tab.title.clone(), Tokens::ui(12.0), t.tab_text).size().x;- label + 16.0 + if tab.active { 20.0 } else { 0.0 } + if tab.active && tab.seq.is_some() { 16.0 } else { 0.0 }- })- .collect();- let span = |from: usize, to: usize| widths.get(from..=to).map_or(0.0, |w| w.iter().sum::<f32>() + 8.0 * w.len() as f32);- let room = strip.width() - 12.0;- let all_fit = span(0, tabs.len().saturating_sub(1)) <= room;- let room = if all_fit { room } else { room - 24.0 };- let mut first = 0;- while first < active_at && span(first, active_at) > room {- first += 1;+ // Escape puts a dragged tab back where it was (egui ends the drag on Escape, #580)+ let home = egui::Id::new(("tab-seq-home", *id));+ if resp.drag_started() {+ ui.data_mut(|d| d.insert_temp(home, i));}- let mut last = active_at.max(first);- while last + 1 < tabs.len() && span(first, last + 1) <= room {- last += 1;+ if resp.drag_stopped()+ && let Some(at) = ui.data_mut(|d| d.remove_temp::<usize>(home))+ && ui.input(|input| input.key_pressed(egui::Key::Escape))+ {+ actions.push(SeqAction::Move(*id, at));}- let list_id = egui::Id::new(("tab-list", g.path.clone()));- let more = (!all_fit).then(|| Rect::from_min_size(pos2(strip.max.x - 22.0, strip.min.y + 6.0), vec2(18.0, 20.0)));- let mut list_opened = false;- if let Some(r) = more {- let resp = ui.interact(r, egui::Id::new(("tab-overflow", g.path.clone())), Sense::click());- let name = if g.panels.contains(&PanelKind::Timeline) { "timeline.tabs.more".to_string() } else { format!("panel.tabs.more.{}", g.path) };- resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, resp.enabled(), "more tabs"));- reg.add_response(&name, &resp, "more tabs");- let c = if resp.hovered() { t.tab_text_active } else { t.tab_text };- icons::paint(&painter, r.shrink(4.0).translate(vec2(-2.0, 0.0)), Icon::ChevronRight, c);- icons::paint(&painter, r.shrink(4.0).translate(vec2(2.0, 0.0)), Icon::ChevronRight, c);- paint_widget_focus(&painter, &resp, t);- if resp.clicked() {- let open = ui.ctx().data(|d| d.get_temp::<bool>(list_id)).unwrap_or(false);- ui.ctx().data_mut(|d| d.insert_temp(list_id, !open));- list_opened = !open;+ reg.add_response(&format!("timeline.tab.{id}"), &resp, name);+ let label_x = tab_rect.min.x + 8.0 + close_w;+ let col = if is_active || resp.hovered() { t.tab_text_active } else { t.tab_text };+ let label_w = galley.size().x;+ painter.galley_with_override_text_color(pos2(label_x, text_y - galley.size().y / 2.0), galley, col);+ let mut closed = false;+ if is_active {+ // × closes the sequence's tab (the sequence stays in the project)+ let cr = Rect::from_center_size(pos2(tab_rect.min.x + 10.0, text_y), vec2(8.0, 8.0));+ let cresp = ui.interact(cr.expand(4.0), egui::Id::new(("tab-close", *id)), Sense::click());+ cresp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, cresp.enabled(), "close sequence"));+ reg.add_response(&format!("timeline.tab.{id}.close"), &cresp, "close sequence");+ let cc = if cresp.hovered() { t.tab_text_active } else { t.tab_text };+ painter.line_segment([cr.left_top(), cr.right_bottom()], Stroke::new(1.2, cc));+ painter.line_segment([cr.right_top(), cr.left_bottom()], Stroke::new(1.2, cc));+ paint_widget_focus(&painter, &cresp, t);+ if cresp.clicked() {+ actions.push(SeqAction::Close(*id));+ closed = true;}+ let uy = strip.max.y - 2.0;+ painter.line_segment([pos2(label_x, uy), pos2(label_x + label_w, uy)], Stroke::new(1.0, t.tab_text_active));}- // The wheel over the strip steps through the tabs: down = next, up = previous, one tab- // per wheel notch (trackpad scrolling adds up to a notch first), stopping at the ends.- let wheel_id = egui::Id::new(("tab-wheel", g.path.clone()));- if ui.rect_contains_pointer(strip) && !tabs.is_empty() {- const NOTCH: f32 = 40.0;- let total = ui.ctx().data(|d| d.get_temp::<f32>(wheel_id)).unwrap_or(0.0) + crate::panels::timeline::wheel_input(ui.ctx()).delta.y;- let steps = (total / NOTCH).trunc();- ui.ctx().data_mut(|d| d.insert_temp(wheel_id, total - steps * NOTCH));- let to = (active_at as i64).saturating_sub(steps as i64).clamp(0, tabs.len() as i64 - 1) as usize;- if let Some(tab) = tabs.get(to).filter(|_| to != active_at) {- activate(tab, &mut actions);- actions.push(DockAction::Focus(tab.panel));- }- } else {- ui.ctx().data_mut(|d| d.remove::<f32>(wheel_id));+ if (resp.clicked() || resp.drag_started()) && !closed && !is_active {+ actions.push(SeqAction::Open(*id));}- let mut x = strip.min.x + 12.0;- // sequence tabs as drawn (for dragging one past its neighbours), and the one being dragged- let mut seq_rects: Vec<(u64, Rect)> = Vec::new();- let mut dragged: Option<u64> = None;- for (i, tab) in tabs.iter().enumerate().take(last + 1).skip(first) {- let p = &tab.panel;- let is_active = tab.active;- let galley = painter.layout_no_wrap(tab.title.clone(), Tokens::ui(12.0), if is_active { t.tab_text_active } else { t.tab_text });- let close_w = if is_active && tab.seq.is_some() { 16.0 } else { 0.0 };- let w = widths.get(i).copied().unwrap_or(0.0);- let tab_rect = Rect::from_min_size(pos2(x, strip.min.y), vec2(w, t.tab_h));- // a sequence tab keeps its identity when the tabs are reordered under the pointer- let resp = match tab.seq {- Some(id) => ui.interact(tab_rect, egui::Id::new(("tab-seq", g.path.clone(), id)), Sense::click_and_drag()),- None => ui.interact(tab_rect, egui::Id::new(("tab", g.path.clone(), i)), Sense::click_and_drag()),- };- if tab.seq.is_none() && resp.drag_started() {- actions.push(DockAction::BeginDrag(*p));- }- if let Some((_, rect)) = tab_rects.iter_mut().find(|(panel, _)| panel == p) {- *rect = rect.union(tab_rect);- } else {- tab_rects.push((*p, tab_rect));- }- resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, resp.enabled(), is_active, &tab.title));- ui.ctx().accesskit_node_builder(resp.id, |node| {- node.set_role(egui::accesskit::Role::Tab);- node.set_selected(is_active);- });- paint_widget_focus(&painter, &resp, t);- if let Some(id) = tab.seq {- seq_rects.push((id, tab_rect));- if resp.dragged() {- dragged = Some(id);- }- // Escape puts a dragged tab back where it was (egui ends the drag on Escape, #580)- let home = egui::Id::new(("tab-seq-home", id));- if resp.drag_started()- && let Some(at) = seqs.open.iter().position(|(s, _)| *s == id)- {- ui.data_mut(|d| d.insert_temp(home, at));- }- if resp.drag_stopped()- && let Some(at) = ui.data_mut(|d| d.remove_temp::<usize>(home))- && ui.input(|i| i.key_pressed(egui::Key::Escape))- {- actions.push(DockAction::MoveSequence(id, at));- }- }- if let Some(id) = tab.seq {- reg.add_response(&format!("timeline.tab.{id}"), &resp, &tab.title);- }- if tab.seq.is_none() || is_active {- reg.add_response(&format!("panel.tab.{}", p.id()), &resp, p.title());- }- let label_x = tab_rect.min.x + 8.0 + close_w;- let label_w = galley.size().x;- let col = if is_active || resp.hovered() { t.tab_text_active } else { t.tab_text };- painter.galley_with_override_text_color(pos2(label_x, text_y - galley.size().y / 2.0), galley, col);- let mut closed = false;- if let Some(id) = tab.seq.filter(|_| is_active) {- // × closes the sequence's tab (the sequence stays in the project)- let cr = Rect::from_center_size(pos2(tab_rect.min.x + 10.0, text_y), vec2(8.0, 8.0));- let cresp = ui.interact(cr.expand(4.0), egui::Id::new(("tab-close", g.path.clone(), id)), Sense::click());- cresp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, cresp.enabled(), "close sequence"));- reg.add_response(&format!("timeline.tab.{id}.close"), &cresp, "close sequence");- let cc = if cresp.hovered() { t.tab_text_active } else { t.tab_text };- painter.line_segment([cr.left_top(), cr.right_bottom()], Stroke::new(1.2, cc));- painter.line_segment([cr.right_top(), cr.left_bottom()], Stroke::new(1.2, cc));- paint_widget_focus(&painter, &cresp, t);- if cresp.clicked() {- actions.push(DockAction::CloseSequence(id));- closed = true;- }- }- if is_active {- let mr = Rect::from_center_size(pos2(label_x + label_w + 12.0, text_y), vec2(12.0, 10.0));- let mresp = ui.interact(mr.expand(3.0), egui::Id::new(("tab-menu", g.path.clone())), Sense::click());- mresp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, mresp.enabled(), "panel menu"));- reg.add_response(&format!("panel.menu.{}", p.id()), &mresp, "panel menu");- let mc = if mresp.hovered() { t.tab_text_active } else { t.tab_text };- icons::paint(&painter, Rect::from_center_size(mr.center(), vec2(16.0, 16.0)), Icon::Hamburger, mc);- // 1 pt underline spanning label + ≡, 23 pt below the frame top- let uy = strip.min.y + 23.0;- painter.line_segment([pos2(label_x, uy), pos2(mr.max.x, uy)], Stroke::new(1.0, t.tab_text_active));- paint_widget_focus(&painter, &mresp, t);- if mresp.clicked() {- actions.push(DockAction::PanelMenu(*p, mr.left_bottom()));- }- }- if (resp.clicked() || resp.drag_started()) && !closed {- activate(tab, &mut actions);- actions.push(DockAction::Focus(*p));- }- // a right-click shows the tab and opens its panel menu (as in Premiere)- if resp.secondary_clicked() {- activate(tab, &mut actions);- actions.push(DockAction::Focus(*p));- let at = resp.interact_pointer_pos().unwrap_or(tab_rect.left_bottom());- actions.push(DockAction::PanelMenu(*p, at));- }- if resp.middle_clicked() {- // a sequence tab closes its sequence; the Timeline panel itself stays- match tab.seq.or(seqs.active.filter(|_| *p == PanelKind::Timeline)) {- Some(id) => actions.push(DockAction::CloseSequence(id)),- None => actions.push(DockAction::Close(*p)),- }- }- x += w + 8.0;+ if resp.middle_clicked() {+ actions.push(SeqAction::Close(*id));}- // Dragging a sequence tab sideways: it changes places with a neighbour when the pointer- // passes that neighbour's middle.- if let Some(id) = dragged- && let Some(px) = ui.input(|i| i.pointer.latest_pos()).map(|p| p.x)- && let Some(at) = seq_rects.iter().position(|(s, _)| *s == id)- && let Some(index) = seqs.open.iter().position(|(s, _)| *s == id)- {- let before = at.checked_sub(1).and_then(|k| seq_rects.get(k));- let after = seq_rects.get(at + 1);- if before.is_some_and(|(_, r)| px < r.center().x) {- actions.push(DockAction::MoveSequence(id, index.saturating_sub(1)));- } else if after.is_some_and(|(_, r)| px > r.center().x) {- actions.push(DockAction::MoveSequence(id, index + 1));- }+ if resp.secondary_clicked() {+ actions.push(SeqAction::Menu(*id, resp.interact_pointer_pos().unwrap_or(tab_rect.left_bottom())));}- // the » list: every tab of the group, the shown one ticked- let list_open = ui.ctx().data(|d| d.get_temp::<bool>(list_id)).unwrap_or(false);- if let Some(r) = more.filter(|_| list_open) {- let mut picked = None;- let area = egui::Area::new(list_id.with("area")).order(egui::Order::Foreground).pivot(Align2::RIGHT_TOP).fixed_pos(r.right_bottom()).show(- ui.ctx(),- |ui| {- egui::Frame::popup(ui.style()).show(ui, |ui| {- ui.set_min_width(160.0);- // many open sequences: the list scrolls instead of leaving the window- egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| {- for tab in &tabs {- let label = if tab.active { format!("✓ {}", tab.title) } else { tab.title.clone() };- let resp = ui.button(label);- match tab.seq {- Some(id) => reg.add_response(&format!("timeline.tabs.list.{id}"), &resp, &tab.title),- None => reg.add_response(&format!("panel.tabs.list.{}", tab.panel.id()), &resp, &tab.title),- }- if resp.clicked() {- picked = Some(tab);- }+ x += w + 8.0;+ }+ // Dragging a sequence tab sideways: it changes places with a neighbour when the pointer+ // passes that neighbour's middle.+ if let Some(id) = dragged+ && let Some(px) = ui.input(|i| i.pointer.latest_pos()).map(|p| p.x)+ && let Some(at) = seq_rects.iter().position(|(s, _)| *s == id)+ && let Some(index) = seqs.open.iter().position(|(s, _)| *s == id)+ {+ let before = at.checked_sub(1).and_then(|k| seq_rects.get(k));+ let after = seq_rects.get(at + 1);+ if before.is_some_and(|(_, r)| px < r.center().x) {+ actions.push(SeqAction::Move(id, index.saturating_sub(1)));+ } else if after.is_some_and(|(_, r)| px > r.center().x) {+ actions.push(SeqAction::Move(id, index + 1));+ }+ }+ // the » list: every open sequence, the shown one ticked+ let list_open = ui.ctx().data(|d| d.get_temp::<bool>(list_id)).unwrap_or(false);+ if let Some(r) = more.filter(|_| list_open) {+ let mut picked = None;+ let area =+ egui::Area::new(list_id.with("area")).order(egui::Order::Foreground).pivot(Align2::RIGHT_TOP).fixed_pos(r.right_bottom()).show(ui.ctx(), |ui| {+ egui::Frame::popup(ui.style()).show(ui, |ui| {+ ui.set_min_width(160.0);+ // many open sequences: the list scrolls instead of leaving the window+ egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| {+ for (id, name) in &seqs.open {+ let label = if seqs.active == Some(*id) { format!("✓ {name}") } else { name.clone() };+ let resp = ui.button(label);+ reg.add_response(&format!("timeline.tabs.list.{id}"), &resp, name);+ if resp.clicked() {+ picked = Some(*id);}- });+ }});- },- );- if let Some(tab) = picked {- activate(tab, &mut actions);- actions.push(DockAction::Focus(tab.panel));- }- if picked.is_some() || (!list_opened && area.response.clicked_elsewhere()) {- ui.ctx().data_mut(|d| d.remove::<bool>(list_id));- }- } else if list_open {+ });+ });+ if let Some(id) = picked {+ actions.push(SeqAction::Open(id));+ }+ if picked.is_some() || (!list_opened && area.response.clicked_elsewhere()) {ui.ctx().data_mut(|d| d.remove::<bool>(list_id));}+ } else if list_open {+ ui.ctx().data_mut(|d| d.remove::<bool>(list_id));}- // Activating presses focus their tab immediately, rather than the group's old active panel.- // Otherwise entering an inspector can briefly reactivate a stale Project/Timeline selection.- // Middle-click closes a tab, so it keeps the active panel as the focus target.- if let Some(p) = active_panel- && ui.rect_contains_pointer(g.rect)- && ui.input(|i| i.pointer.any_pressed())- {- let panel = ui- .input(|i| i.pointer.interact_pos().filter(|_| i.pointer.primary_pressed() || i.pointer.secondary_pressed()))- .and_then(|pos| tab_rects.iter().find(|(_, rect)| rect.contains(pos)).map(|(panel, _)| *panel))- .unwrap_or(p);- actions.push(DockAction::Focus(panel));- }- Chrome { actions, tabs: tab_rects }+ actions}-/// Paint once after the group's contents so child backgrounds cannot hide its focus (#1075).-pub(crate) fn paint_group_focus(ui: &egui::Ui, group: &Group, focused: PanelKind, tokens: &Tokens) {- if group.panels.get(group.active).copied() == Some(focused) {- ui.painter().rect_stroke(group.rect, 0.0, Stroke::new(1.0, tokens.focus), StrokeKind::Inside);- }-}--fn paint_widget_focus(painter: &egui::Painter, response: &egui::Response, tokens: &Tokens) {+pub(crate) fn paint_widget_focus(painter: &egui::Painter, response: &egui::Response, tokens: &Tokens) {if response.has_focus() {painter.rect_stroke(response.rect.shrink(2.0), 2.0, Stroke::new(1.5, tokens.focus), StrokeKind::Inside);}@@ -898,68 +734,53 @@ pub fn placeholder(ui: &mut egui::Ui, rect: Rect, t: &Tokens, text: &str) {mod tests {use super::*;- #[test]- fn split_first_never_panics_on_tiny_areas() {- let split_first = |size: SplitSize, avail: f32| {- split_rect(Rect::from_min_size(egui::Pos2::ZERO, vec2(avail, 100.0)), SplitAxis::Horizontal, size.shared(), 0.0, 20.0).unwrap().first_size()- };- for avail in [0.0, 1.0, 15.0, 20.0, 35.0, 39.9, 40.0, 100.0, 2000.0] {- for size in [- SplitSize::Ratio(0.0),- SplitSize::Ratio(0.5),- SplitSize::Ratio(1.0),- SplitSize::FixedA(300.0),- SplitSize::FixedB(300.0),- SplitSize::FixedA(0.0),- ] {- let f = split_first(size, avail);- assert!((0.0..=avail).contains(&f), "{size:?} in {avail}: {f}");- }- }- assert_eq!(split_first(SplitSize::FixedA(300.0), 1000.0), 300.0);- assert_eq!(split_first(SplitSize::FixedB(300.0), 1000.0), 700.0);- assert_eq!(split_first(SplitSize::Ratio(0.0), 1000.0), 20.0);- }-#[test]fn workspaces_contain_core_panels() {for w in WORKSPACES {let d = workspace(w);- assert!(d.contains(PanelKind::Timeline), "{w}");- assert!(d.contains(PanelKind::Program), "{w}");+ d.validate().unwrap();+ assert!(d.contains(&PanelKind::Timeline), "{w}");+ assert!(d.contains(&PanelKind::Program), "{w}");}}- #[test]- fn close_and_open() {- let mut d = workspace("Editing");- d.close(PanelKind::Metadata);- assert!(!d.contains(PanelKind::Metadata));- d.open_near(PanelKind::LumetriColor, PanelKind::Program);- assert!(d.is_visible(PanelKind::LumetriColor));- let s = serde_json::to_string(&d).unwrap();- let back: DockNode = serde_json::from_str(&s).unwrap();- assert_eq!(back, d);- }-/// #284: with Project and Program closed (or every panel closed) a panel still opens.#[test]fn open_near_falls_back_to_the_first_group() {let mut d = workspace("Editing");- let mut all = Vec::new();- d.panels(&mut all);- for p in all {- d.close(p);+ for p in d.panels().into_iter().copied().collect::<Vec<_>>() {+ d.apply(Action::Close { panel: p }).unwrap();}- assert_eq!(d, DockNode::Tabs { panels: vec![], active: 0 });+ assert_eq!(d.root, None);d.open_near(PanelKind::Program, PanelKind::Project);assert!(d.is_visible(PanelKind::Program));d.restore_timeline();assert!(d.is_visible(PanelKind::Timeline));// a tree without Project or Program: the panel joins the first group- let mut d = hsplit(SplitSize::Ratio(0.5), tabs(&[PanelKind::Effects], 0), tabs(&[PanelKind::Markers], 0));+ let mut d = Layout { root: Some(hsplit(SplitSize::Ratio(0.5), tabs(&[PanelKind::Effects], 0), tabs(&[PanelKind::Markers], 0))), floating: vec![] };d.open_near(PanelKind::Info, PanelKind::Source);assert!(d.is_visible(PanelKind::Info));- assert_eq!(d, hsplit(SplitSize::Ratio(0.5), tabs(&[PanelKind::Effects, PanelKind::Info], 1), tabs(&[PanelKind::Markers], 0)));+ assert_eq!(d.root, Some(hsplit(SplitSize::Ratio(0.5), tabs(&[PanelKind::Effects, PanelKind::Info], 1), tabs(&[PanelKind::Markers], 0))));+ }++ /// A workspace file written before FilmCraft saved craft-ui workspaces still opens, and a+ /// saved workspace reads back as written.+ #[test]+ fn saved_workspaces_read_earlier_files_and_round_trip() {+ let legacy = serde_json::json!({"saved": [{"name": "Mine", "layout": {"Split": {"vertical": false, "size": {"FixedA": 300.0},+ "a": {"Tabs": {"panels": ["Project", "Info"], "active": 1}}, "b": {"Tabs": {"panels": ["Timeline"], "active": 0}}}},+ "floating": [{"panels": ["Effects"], "active": 0, "rect": [10.0, 20.0, 300.0, 200.0]}]},+ {"name": "Broken", "layout": {"Tabs": {"panels": ["NoSuchPanel"], "active": 0}}}], "current": "Mine"});+ let prefs: WorkspacePrefs = serde_json::from_value(legacy).unwrap();+ let mine = saved_docking(&prefs, "Mine");+ assert!(mine.is_visible(PanelKind::Info) && mine.is_visible(PanelKind::Timeline) && mine.is_visible(PanelKind::Effects));+ assert!(matches!(mine.root, Some(Node::Split { size: SplitSize::FixedFirst(300.0), .. })));+ assert_eq!(saved_docking(&prefs, "Broken"), workspace("Broken"));+ let saved = SavedWorkspace { name: "Mine".into(), workspace: serde_json::to_value(Workspace::new(mine.clone())).unwrap(), ..Default::default() };+ let prefs = WorkspacePrefs { saved: vec![saved], current: "Mine".into() };+ let text = serde_json::to_string(&prefs).unwrap();+ assert!(!text.contains("\"layout\":{\"Split\""), "{text}");+ let back: WorkspacePrefs = serde_json::from_str(&text).unwrap();+ assert_eq!(saved_docking(&back, "Mine"), mine);}}diff --git a/crates/ui-egui/src/dock_shared.rs b/crates/ui-egui/src/dock_shared.rsdeleted file mode 100644index 2b64351db..000000000--- a/crates/ui-egui/src/dock_shared.rs+++ /dev/null@@ -1,131 +0,0 @@-//! Convert the persisted workspace schema to shared docking transactions.--use craft_ui::docking::{Action, Floating as SharedFloating, Layout as SharedLayout, Location, Node, Placement, Zone};-use craft_ui::layout::{SplitAxis, SplitSize as SharedSplitSize};--use crate::dock::{DockNode, Floating, Layout, PanelKind, SplitSize};--const MAX_DEPTH: usize = 32;-const MAX_NODES: usize = 4096;-const MAX_PANELS: usize = 128;--fn encode_node(node: &DockNode, depth: usize, count: &mut usize) -> Result<Node<PanelKind>, String> {- *count = count.saturating_add(1);- if depth > MAX_DEPTH || *count > MAX_NODES {- return Err("workspace dock tree exceeds supported limits".into());- }- Ok(match node {- DockNode::Tabs { panels, active } => {- if panels.len() > MAX_PANELS {- return Err("too many workspace tabs".into());- }- Node::Tabs { panels: panels.clone(), active: *active }- }- DockNode::Split { vertical, size, a, b } => Node::Split {- axis: if *vertical { SplitAxis::Vertical } else { SplitAxis::Horizontal },- size: match *size {- SplitSize::Ratio(value) => SharedSplitSize::Ratio(value),- SplitSize::FixedA(value) => SharedSplitSize::FixedFirst(value),- SplitSize::FixedB(value) => SharedSplitSize::FixedSecond(value),- },- first: Box::new(encode_node(a, depth.saturating_add(1), count)?),- second: Box::new(encode_node(b, depth.saturating_add(1), count)?),- },- })-}--fn decode_node(node: Node<PanelKind>) -> Result<DockNode, String> {- Ok(match node {- Node::Tabs { panels, active } => DockNode::Tabs { panels, active },- Node::Stack { .. } => return Err("FilmCraft does not use stacked panels".into()),- Node::Split { axis, size, first, second } => DockNode::Split {- vertical: axis == SplitAxis::Vertical,- size: match size {- SharedSplitSize::Ratio(value) => SplitSize::Ratio(value),- SharedSplitSize::FixedFirst(value) => SplitSize::FixedA(value),- SharedSplitSize::FixedSecond(value) => SplitSize::FixedB(value),- },- a: Box::new(decode_node(*first)?),- b: Box::new(decode_node(*second)?),- },- })-}--pub(crate) fn encode(root: &DockNode, floating: &[Floating]) -> Result<SharedLayout<PanelKind>, String> {- if floating.len() > MAX_PANELS || floating.iter().any(|group| group.panels.len() > MAX_PANELS) {- return Err("too many floating workspace panels".into());- }- let root = if matches!(root, DockNode::Tabs { panels, active: 0 } if panels.is_empty()) { None } else { Some(encode_node(root, 0, &mut 0)?) };- Ok(SharedLayout {- root,- floating: floating.iter().map(|group| SharedFloating { panels: group.panels.clone(), active: group.active, rect: group.rect }).collect(),- })-}--pub(crate) fn decode(layout: SharedLayout<PanelKind>) -> Result<Layout, String> {- Ok(Layout {- root: match layout.root {- Some(root) => decode_node(root)?,- None => DockNode::Tabs { panels: vec![], active: 0 },- },- floating: layout.floating.into_iter().map(|group| Floating { panels: group.panels, active: group.active, rect: group.rect }).collect(),- })-}--pub(crate) fn apply(layout: &mut Layout, action: Action<PanelKind>) -> Result<(), String> {- let mut shared = encode(&layout.root, &layout.floating)?;- shared.validate().map_err(|error| error.to_string())?;- check_last_docked(&shared, &action)?;- shared.apply(action).map_err(|error| error.to_string())?;- let proposed = decode(shared)?;- encode(&proposed.root, &proposed.floating)?;- *layout = proposed;- Ok(())-}--pub(crate) fn apply_tree(root: &mut DockNode, action: Action<PanelKind>) -> bool {- let Ok(mut shared) = encode(root, &[]) else { return false };- if shared.apply(action).is_err() {- return false;- }- let Ok(layout) = decode(shared) else { return false };- if encode(&layout.root, &[]).is_err() {- return false;- }- *root = layout.root;- true-}--/// Dock a panel along one edge of the whole workspace. The shared model restores a panel beside a-/// complete sibling subtree, so naming every remaining docked panel targets the root itself.-pub(crate) fn dock_at_edge(layout: &mut SharedLayout<PanelKind>, panel: PanelKind, zone: Zone) -> Result<(), String> {- let size = match zone {- Zone::Left | Zone::Top => SharedSplitSize::Ratio(0.25),- Zone::Right | Zone::Bottom => SharedSplitSize::Ratio(0.75),- Zone::Center => return Err("a workspace edge needs a left, right, top or bottom zone".into()),- };- let mut proposed = layout.clone();- proposed.apply(Action::Close { panel }).map_err(|error| error.to_string())?;- let sibling: Vec<PanelKind> = SharedLayout { root: proposed.root.clone(), floating: vec![] }.panels().into_iter().copied().collect();- let anchor = *sibling.first().ok_or("another docked panel is required to dock beside")?;- let location = Location { floating: None, anchor: Some(anchor), placement: Placement::Split(zone), size: Some(size), stack: None, sibling };- proposed.restore(panel, &location).map_err(|error| error.to_string())?;- *layout = proposed;- Ok(())-}--/// Keep one docked destination available for dragging floating panels back into the workspace.-pub(crate) fn check_last_docked(layout: &SharedLayout<PanelKind>, action: &Action<PanelKind>) -> Result<(), String> {- let panel = match action {- Action::Float { panel, .. } => Some(panel),- Action::Move { panel, anchor, .. } if layout.floating.iter().any(|group| group.panels.contains(anchor)) => Some(panel),- _ => None,- };- if let Some(panel) = panel {- let docked = SharedLayout { root: layout.root.clone(), floating: vec![] };- if docked.contains(panel) && docked.panels().len() <= 1 {- return Err("the last docked panel must remain in the workspace".into());- }- }- Ok(())-}diff --git a/crates/ui-egui/src/dock_ui.rs b/crates/ui-egui/src/dock_ui.rsindex 98951de89..3327ba4f9 100644--- a/crates/ui-egui/src/dock_ui.rs+++ b/crates/ui-egui/src/dock_ui.rs@@ -1,26 +1,32 @@-//! FilmCraft's panel chrome and document tabs over the shared docking transactions.+//! FilmCraft's panels in craft-ui's shared docking, Frame profile. craft-ui draws the frames, tab+//! strips, floating windows and drag previews and owns the gestures; FilmCraft draws the panel+//! bodies, the ≡ panel menu and the Timeline's sequence tabs, and maps its control commands onto+//! craft-ui's `DockCommand`.-use craft_ui::docking::{Action, DropTarget, Placement, Zone, resolve_drop};-use egui::{Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2};+use craft_ui::docking::{+ Action, Divider, DockArea, DockCommand, DockContent, DockEvent, DockStyle, FloatSpace, Hit, Layout, Placement, Profile, ResizeEdge, Workspace, Zone,+};+use egui::{Rect, Sense, Stroke, StrokeKind, vec2};use serde_json::{Value, json};-use crate::dock::{self, DockAction, DockNode, Group, PanelKind};+use crate::dock::{self, PanelKind, SeqAction, SeqTabs};+use crate::icons::{self, Icon};+use crate::theme::Tokens;use crate::{FilmcraftApp, panels};-/// Single source for rendering and hit testing: saved offscreen positions remain-/// reachable, and every panel has enough room for its chrome.-fn floating_rect(group: &dock::Floating, screen: Rect) -> Rect {- let rect = Rect::from_min_size(pos2(group.rect[0], group.rect[1]), vec2(group.rect[2].max(160.0), group.rect[3].max(100.0)));- rect.translate(vec2(- (screen.min.x - rect.min.x).max(0.0) + (screen.max.x - 40.0 - rect.min.x).min(0.0),- (screen.min.y - rect.min.y).max(0.0) + (screen.max.y - 30.0 - rect.min.y).min(0.0),- ))+/// The dock area's egui id; `DockArea::hit_rects` and `float_space` read by it.+pub fn area_id() -> egui::Id {+ egui::Id::new("filmcraft-docking")}-fn drag_id() -> egui::Id {- egui::Id::new("dock-panel-drag")+/// Where each panel body was drawn last frame, and on which layer.+fn bodies_id() -> egui::Id {+ area_id().with("bodies")}+/// Width of the ≡ panel menu button at the end of each tab strip.+const MENU_W: f32 = 26.0;+pub(crate) fn route(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option<Result<Value, String>> {if id == "window.dockAction" {return Some((|| {@@ -30,181 +36,171 @@ pub(crate) fn route(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, paramOk(Value::Null)})());}- if !matches!(id, "window.dockPanel" | "window.floatPanel" | "window.closePanel") {- return None;+ if matches!(id, "window.dockPanel" | "window.floatPanel" | "window.closePanel") {+ return Some(alias(app, ctx, id, params));}- Some((|| {- let panel = match params.get("panel") {- None => app.ui.focused,- Some(value) => value.as_str().and_then(PanelKind::from_name).ok_or("unknown panel")?,- };- let action = match id {- "window.closePanel" => Action::Close { panel },- "window.floatPanel" => {- let rect = match params.get("rect") {- None => default_float_rect(ctx.content_rect()),- Some(value) => serde_json::from_value::<[f32; 4]>(value.clone()).map_err(|_| "rect must contain four finite numbers")?,- };- Action::Float { panel, rect }+ if id.starts_with("window.panel.") && DockCommand::<PanelKind>::IDS.contains(&id) {+ return Some((|| {+ let mut params = if params.is_object() { params.clone() } else { json!({}) };+ params["command"] = json!(id);+ let command: DockCommand<PanelKind> = serde_json::from_value(params).map_err(|error| format!("invalid docking command: {error}"))?;+ app.run_dock_command(ctx, command)?;+ Ok(Value::Null)+ })());+ }+ None+}++/// FilmCraft's own docking commands, as craft-ui `window.panel.*` commands. `panel` defaults to+/// the focused panel.+fn alias(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Result<Value, String> {+ let panel = match params.get("panel") {+ None => app.ui.focused,+ Some(value) => value.as_str().and_then(PanelKind::from_name).ok_or("unknown panel")?,+ };+ let command = match id {+ "window.closePanel" => json!({"command": "window.panel.close", "panel": panel}),+ "window.floatPanel" => match params.get("rect") {+ None => json!({"command": "window.panel.float", "panel": panel}),+ Some(value) => {+ let rect = serde_json::from_value::<[f32; 4]>(value.clone()).map_err(|_| "rect must contain four finite numbers")?;+ json!({"command": "window.panel.layout", "action": Action::Float { panel, rect }})}- _ => {- let zone_name = match params.get("zone") {- None => "center",- Some(value) => value.as_str().ok_or("zone must be a string")?,- };- let zone = match zone_name.to_ascii_lowercase().as_str() {- "left" => Zone::Left,- "right" => Zone::Right,- "top" => Zone::Top,- "bottom" => Zone::Bottom,- "center" | "tab" => Zone::Center,- _ => return Err("unknown docking zone".into()),- };- let Some(anchor) = params.get("anchor") else {- if params.get("before").is_some() {- return Err("before needs an anchor panel".into());+ },+ _ => {+ let zone = match params.get("zone") {+ None => "center",+ Some(value) => value.as_str().ok_or("zone must be a string")?,+ };+ match params.get("anchor") {+ Some(anchor) => {+ let anchor = anchor.as_str().and_then(PanelKind::from_name).ok_or("a known anchor panel is required")?;+ let mut command = json!({"command": "window.panel.dock", "panel": panel, "anchor": anchor, "zone": zone.to_ascii_lowercase()});+ if let Some(before) = params.get("before") {+ command["before"] = json!(before.as_str().and_then(PanelKind::from_name).ok_or("unknown before panel")?);+ }+ command+ }+ None if params.get("before").is_some() => return Err("before needs an anchor panel".into()),+ // Without an anchor a side zone docks along that edge of the whole workspace.+ None => {+ let edge = match zone.to_ascii_lowercase().as_str() {+ "left" => Some(Zone::Left),+ "right" => Some(Zone::Right),+ "top" => Some(Zone::Top),+ "bottom" => Some(Zone::Bottom),+ "center" | "tab" => None,+ _ => return Err("unknown docking zone".into()),+ };+ match edge {+ None => json!({"command": "window.panel.dock", "panel": panel}),+ Some(edge) => {+ let docked = Layout { root: app.ui.dock.root.clone(), floating: vec![] };+ let anchor =+ docked.panels().into_iter().copied().find(|other| *other != panel).ok_or("another docked panel is required to dock beside")?;+ json!({"command": "window.panel.layout", "action": Action::Move { panel, anchor, placement: Placement::Edge(edge) }})+ }}- app.dock_to_edge(panel, zone)?;- return Ok(json!({"panel": panel.id()}));- };- let anchor = anchor.as_str().and_then(PanelKind::from_name).ok_or("a known anchor panel is required")?;- let placement = match params.get("before") {- Some(value) => Placement::Tab { before: Some(value.as_str().and_then(PanelKind::from_name).ok_or("unknown before panel")?) },- None => Placement::Split(zone),- };- Action::Move { panel, anchor, placement }+ }}- };- app.apply_dock(action)?;- Ok(json!({"panel": panel.id()}))- })())+ }+ };+ let command: DockCommand<PanelKind> = serde_json::from_value(command).map_err(|error| format!("invalid docking command: {error}"))?;+ app.run_dock_command(ctx, command)?;+ Ok(json!({"panel": panel.id()}))}-pub(crate) fn default_float_rect(screen: Rect) -> [f32; 4] {- let center = screen.center();- [center.x - 210.0, center.y - 160.0, 420.0, 320.0]+/// Keep one docked destination available for dragging floating panels back into the workspace.+fn check_last_docked(layout: &Layout<PanelKind>, action: &Action<PanelKind>) -> Result<(), String> {+ let panel = match action {+ Action::Float { panel, .. } => Some(panel),+ Action::Move { panel, anchor, .. } if layout.floating.iter().any(|window| window.contains(anchor)) => Some(panel),+ _ => None,+ };+ if let Some(panel) = panel {+ let docked = Layout { root: layout.root.clone(), floating: vec![] };+ if docked.contains(panel) && docked.panels().len() <= 1 {+ return Err("the last docked panel must remain in the workspace".into());+ }+ }+ Ok(())}impl FilmcraftApp {+ /// A layout action from the dock area, through the command path the control channel uses.fn dock_command(&mut self, ctx: &egui::Context, action: Action<PanelKind>) -> Result<(), String> {let value = serde_json::to_value(action).map_err(|error| error.to_string())?;crate::menus::invoke(self, ctx, "window.dockAction", json!({"action": value})).map(|_| ())}+ /// Run a craft-ui docking command on the current layout, all or nothing. Workspaces are+ /// FilmCraft's own (Window ▸ Workspaces).+ pub(crate) fn run_dock_command(&mut self, ctx: &egui::Context, command: DockCommand<PanelKind>) -> Result<(), String> {+ if command.is_app_owned() {+ return Err("use the window.workspace.* commands for workspaces".into());+ }+ let space = craft_ui::docking::float_space(ctx, area_id()).unwrap_or_else(|| FloatSpace::new(ctx.content_rect()));+ let actions = command.to_actions(&Workspace::new(self.ui.dock.clone()), false, &space).map_err(|error| error.to_string())?;+ self.apply_dock_all(actions)+ }+pub fn apply_dock(&mut self, action: Action<PanelKind>) -> Result<(), String> {- let relocating = matches!(&action, Action::Move { .. } | Action::Float { .. });- let reveal = match &action {- Action::Activate { panel } => Some(*panel),- _ => None,- };- // a panel closed while floating remembers where; closed while docked, it forgets (#1985)- let closing = match &action {- Action::Close { panel } => Some((*panel, self.ui.floating.iter().find(|g| g.panels.contains(panel)).map(|g| g.rect))),- _ => None,- };- self.commit_dock(|shared| {- crate::dock_shared::check_last_docked(shared, &action)?;- shared.apply(action).map_err(|error| error.to_string())- })?;+ self.apply_dock_all(vec![action])+ }++ fn apply_dock_all(&mut self, actions: Vec<Action<PanelKind>>) -> Result<(), String> {+ let mut layout = self.ui.dock.clone();+ let mut relocating = false;+ let mut reveal = None;+ let mut closed_floating = self.ui.closed_floating.clone();+ for action in actions {+ relocating |= matches!(&action, Action::Move { .. } | Action::Float { .. } | Action::MoveGroup { .. } | Action::MoveWindow { .. });+ if let Action::Activate { panel } = &action {+ reveal = Some(*panel);+ }+ // a panel closed while floating remembers where; closed while docked, it forgets (#1985)+ for panel in layout.closed_by(&action).map_err(|error| error.to_string())? {+ closed_floating.retain(|(p, _)| *p != panel);+ if let Some(window) = layout.floating.iter().find(|window| window.contains(&panel)) {+ closed_floating.push((panel, window.rect));+ }+ }+ check_last_docked(&layout, &action)?;+ layout.apply(action).map_err(|error| error.to_string())?;+ }+ self.ui.dock = layout;+ self.ui.closed_floating = closed_floating;if let Some(panel) = reveal {self.pending_panel_raise = Some(panel);}- if let Some((panel, rect)) = closing {- self.ui.closed_floating.retain(|(p, _)| *p != panel);- if let Some(rect) = rect {- self.ui.closed_floating.push((panel, rect));- }- }- if relocating- || self.ui.keys.maximized.is_some_and(|panel| !self.ui.dock.contains(panel) && !self.ui.floating.iter().any(|group| group.panels.contains(&panel)))- {+ if relocating || self.ui.keys.maximized.is_some_and(|panel| !self.ui.dock.contains(&panel)) {self.ui.keys.maximized = None;}Ok(())}- /// Dock a panel along an edge of the whole workspace rather than beside one group.- pub fn dock_to_edge(&mut self, panel: PanelKind, zone: Zone) -> Result<(), String> {- self.commit_dock(|shared| crate::dock_shared::dock_at_edge(shared, panel, zone))?;- self.ui.keys.maximized = None;- Ok(())- }-- fn commit_dock(&mut self, change: impl FnOnce(&mut craft_ui::docking::Layout<PanelKind>) -> Result<(), String>) -> Result<(), String> {- let mut shared = crate::dock_shared::encode(&self.ui.dock, &self.ui.floating)?;- shared.validate().map_err(|error| error.to_string())?;- change(&mut shared)?;- let layout = crate::dock_shared::decode(shared)?;- crate::dock_shared::encode(&layout.root, &layout.floating)?;- self.ui.dock = layout.root;- self.ui.floating = layout.floating;- Ok(())- }-- fn panel_body(&mut self, ui: &mut egui::Ui, panel: PanelKind, content: Rect) {- self.auto.add(&format!("panel.{}", panel.id()), content, panel.title());- let mut child = ui.new_child(egui::UiBuilder::new().max_rect(content).id_salt(("panel", panel.id())));- child.set_clip_rect(content.intersect(ui.clip_rect()));- panels::show(self, &mut child, panel, content);- }-- /// OS drag positions come from the host cursor hook, so egui pointer capture alone- /// cannot decide whether a Timeline is covered. Use the same geometry and layer- /// ordering as our renderer before any panel can dispatch an edit.+ /// OS drag positions come from the host cursor hook, so egui pointer capture alone cannot+ /// decide whether a Timeline is covered: the Timeline body drawn last frame must hold `pos`,+ /// with no floating window above it there.pub(crate) fn timeline_drop_target(&self, ctx: &egui::Context, pos: egui::Pos2) -> bool {if !ctx.content_rect().contains(pos) {return false;}- if let Some(panel) =- self.ui.keys.maximized.filter(|panel| self.ui.dock.contains(*panel) || self.ui.floating.iter().any(|group| group.panels.contains(panel)))- {- return panel == PanelKind::Timeline;- }- for index in self.floating_order(ctx).into_iter().rev() {- if let Some(group) = self.ui.floating.get(index)- && floating_rect(group, ctx.content_rect()).contains(pos)- {- return group.panels.get(group.active) == Some(&PanelKind::Timeline);- }- }- true- }-- fn floating_order(&self, ctx: &egui::Context) -> Vec<usize> {+ let Some(bodies) = ctx.data(|data| data.get_temp::<Vec<(PanelKind, Rect, egui::LayerId)>>(bodies_id())) else { return true };+ let Some((_, _, timeline)) = bodies.iter().find(|(panel, rect, _)| *panel == PanelKind::Timeline && rect.contains(pos)) else { return false };let layers = ctx.memory(|memory| memory.layer_ids().collect::<Vec<_>>());- let mut order: Vec<_> = (0..self.ui.floating.len()).collect();- order.sort_by_key(|index| {- self.ui- .floating- .get(*index)- .and_then(|group| group.panels.first())- .and_then(|panel| {- let id = egui::Id::new(("floating-panel", panel.id()));- layers.iter().position(|layer| layer.id == id)- })- .unwrap_or(usize::MAX)- });- order+ let rank = |layer: &egui::LayerId| layers.iter().position(|other| other == layer);+ !self.ui.dock.floating.iter().any(|window| {+ let Some(first) = window.panels().next() else { return false };+ let layer = egui::LayerId::new(egui::Order::Middle, area_id().with(("floating", *first)));+ layer != *timeline && rank(&layer) > rank(timeline) && ctx.memory(|memory| memory.area_rect(layer.id)).is_some_and(|rect| rect.contains(pos))+ })}pub(crate) fn dock_area(&mut self, ui: &mut egui::Ui, body: Rect) {let t = self.tokens;let ctx = ui.ctx().clone();- if let Some(panel) = self.pending_panel_raise.take()- && let Some(owner) = self.ui.floating.iter().find(|group| group.panels.contains(&panel)).and_then(|group| group.panels.first())- {- ctx.move_to_top(egui::LayerId::new(egui::Order::Middle, egui::Id::new(("floating-panel", owner.id()))));- }- let maximized =- self.ui.keys.maximized.filter(|panel| self.ui.dock.contains(*panel) || self.ui.floating.iter().any(|group| group.panels.contains(panel)));- let mut dock = match maximized {- Some(panel) => DockNode::Tabs { panels: vec![panel], active: 0 },- None => std::mem::replace(&mut self.ui.dock, DockNode::Tabs { panels: vec![], active: 0 }),- };- let mut groups = vec![];- let mut layout_actions = Vec::new();- dock::layout_with_actions(ui, &mut dock, body, &t, "", &mut groups, &mut self.auto, &mut layout_actions);- let seqs = dock::SeqTabs {+ let seqs = SeqTabs {open: self.session.state@@ -220,253 +216,251 @@ impl FilmcraftApp {.collect(),active: self.session.state.active_sequence.map(|id| id.0),};- let mut actions = vec![];- let mut targets = vec![];- for group in &groups {- let chrome = dock::draw_group_chrome_details(ui, group, &seqs, &t, &mut self.auto);- if let Some(target) = target(group, chrome.tabs, true) {- targets.push(target);- }- actions.extend(chrome.actions);+ let style = dock_style(ui, &t);+ let mut area = DockArea::new(area_id()).maximized(self.ui.keys.maximized.filter(|panel| self.ui.dock.contains(panel)));+ if let Some(panel) = self.pending_panel_raise.take() {+ area = area.raise_panel(panel);}- if maximized.is_none() {- self.ui.dock = dock;+ let layout = self.ui.dock.clone();+ let mut child = ui.new_child(egui::UiBuilder::new().max_rect(body).id_salt("filmcraft-dock-area"));+ child.set_clip_rect(body.intersect(ui.clip_rect()));+ let seq_width = dock::sequence_tabs_width(ui, &seqs);+ let mut content = FilmContent { app: self, seqs, seq_width, tokens: t, seq_actions: Vec::new(), menu: None, bodies: Vec::new() };+ let output = area.show_content(&mut child, &layout, &style, &mut content);+ let FilmContent { seq_actions, mut menu, bodies, .. } = content;+ ctx.data_mut(|data| data.insert_temp(bodies_id(), bodies));+ if let Some(panel) = output.focused {+ self.ui.focused = panel;}- for group in &groups {- if let Some(panel) = group.panels.get(group.active).copied() {- self.panel_body(ui, panel, group.content);- }- }- for group in &groups {- dock::paint_group_focus(ui, group, self.ui.focused, &t);+ if let Some(error) = output.error {+ self.ui.status = error.to_string();}- let floating_order = self.floating_order(&ctx);- for index in floating_order.into_iter().filter(|_| maximized.is_none()) {- if let Some(target) = self.floating_group(&ctx, index, &seqs, &mut actions) {- targets.push(target);+ for event in output.events {+ if let DockEvent::ToggleMaximize { panel } = event {+ panels::keyboard::toggle_maximize(self, panel);}}- for action in layout_actions {- let _ = self.dock_command(&ctx, action);+ for action in output.actions {+ if let Err(error) = self.dock_command(&ctx, action) {+ self.ui.status = error;+ }}- for action in actions {- match action {- DockAction::Activate(panel) => {- let _ = self.dock_command(&ctx, Action::Activate { panel });- }- DockAction::Close(panel) => {- let _ = self.dock_command(&ctx, Action::Close { panel });- }- DockAction::Focus(panel) => self.ui.focused = panel,- DockAction::BeginDrag(panel) => {- ctx.data_mut(|data| data.insert_temp(drag_id(), panel));- }- DockAction::OpenSequence(id) => {- let _ = self.dock_command(&ctx, Action::Activate { panel: PanelKind::Timeline });- if self.session.state.active_sequence.map(|item| item.0) != Some(id)- && let Err(error) = self.session.execute("sequence.open", json!({"item": id}))- {- self.ui.status = error.to_string();+ for action in seq_actions {+ let result = match action {+ SeqAction::Open(id) => {+ let _ = self.apply_dock(Action::Activate { panel: PanelKind::Timeline });+ self.ui.focused = PanelKind::Timeline;+ if self.session.state.active_sequence.map(|item| item.0) == Some(id) {+ Ok(Value::Null)+ } else {+ self.session.execute("sequence.open", json!({"item": id}))}}- DockAction::CloseSequence(id) => {- if let Err(error) = self.session.execute("sequence.close", json!({"item": id})) {- self.ui.status = error.to_string();+ SeqAction::Close(id) => self.session.execute("sequence.close", json!({"item": id})),+ SeqAction::Move(id, index) => self.session.execute("sequence.moveTab", json!({"item": id, "index": index})),+ SeqAction::Menu(id, pos) => {+ menu = Some((PanelKind::Timeline, pos));+ self.ui.focused = PanelKind::Timeline;+ if self.session.state.active_sequence.map(|item| item.0) == Some(id) {+ Ok(Value::Null)+ } else {+ self.session.execute("sequence.open", json!({"item": id}))}}- DockAction::MoveSequence(id, index) => {- if let Err(error) = self.session.execute("sequence.moveTab", json!({"item": id, "index": index})) {- self.ui.status = error.to_string();- }- }- DockAction::PanelMenu(panel, pos) => {- let frame = ctx.cumulative_frame_nr();- ctx.data_mut(|data| {- data.insert_temp(egui::Id::new("panel-menu"), (panel, pos));- data.insert_temp(egui::Id::new("panel-menu-opened"), frame);- });- }+ };+ if let Err(error) = result {+ self.ui.status = error.to_string();}}- self.panel_drag(&ctx, body, &targets);+ if let Some((panel, pos)) = menu {+ let frame = ctx.cumulative_frame_nr();+ ctx.data_mut(|data| {+ data.insert_temp(egui::Id::new("panel-menu"), (panel, pos));+ data.insert_temp(egui::Id::new("panel-menu-opened"), frame);+ });+ }+ let hits = DockArea::<PanelKind>::hit_rects(&ctx, area_id());+ self.tab_strip_pointer(&ctx, &hits);+ self.register_dock_hits(&hits);panels::panel_menu_popup(self, ui);self.cancel_value_drag(ui.ctx());}- fn floating_group(&mut self, ctx: &egui::Context, index: usize, seqs: &dock::SeqTabs, actions: &mut Vec<DockAction>) -> Option<DropTarget<PanelKind>> {- let floating = self.ui.floating.get(index)?.clone();- let panel = *floating.panels.first()?;- let rect = floating_rect(&floating, ctx.content_rect());- let t = self.tokens;- let id = egui::Id::new(("floating-panel", panel.id()));- let mut output = None;- egui::Area::new(id).order(egui::Order::Middle).fixed_pos(rect.min).constrain(false).interactable(true).show(ctx, |ui| {- let (rect, _) = ui.allocate_exact_size(rect.size(), Sense::hover());- let compact = floating.panels.len() == 1 && panel.compact();- let header = if compact { 8.0 } else { t.tab_h };- let strip = Rect::from_min_size(rect.min, vec2(rect.width(), header));- let response = ui.interact(strip, id.with("move"), Sense::drag());- self.auto.add_response(&format!("panel.float.{index}.move"), &response, "Move floating panel");- let mut next = if response.dragged() { rect.translate(response.drag_delta()) } else { rect };- let group = Group {- path: format!("f{index}"),- rect,- content: Rect::from_min_max(pos2(rect.min.x, rect.min.y + header), rect.max),- panels: floating.panels.clone(),- active: floating.active,+ /// Automation ids for craft-ui's gesture sources: `panel.tab.<Panel>`, `panel.drag.<Panel>`+ /// (the group's drag bar), `panel.tabs.more.<Panel>`, `panel.float.<n>.move` and `.resize`,+ /// and `dock.gutter.<path>` (`a`/`b` per split level).+ fn register_dock_hits(&mut self, hits: &[(Hit<PanelKind>, Rect)]) {+ let window = |panel: &PanelKind| self.ui.dock.floating.iter().position(|window| window.contains(panel));+ let mut found = Vec::new();+ for (hit, rect) in hits {+ let entry = match hit {+ Hit::Tab(panel) => (format!("panel.tab.{}", panel.id()), panel.title()),+ Hit::DragBar(panel) => (format!("panel.drag.{}", panel.id()), "Move panel"),+ Hit::Overflow(panel) => (format!("panel.tabs.more.{}", panel.id()), "more tabs"),+ Hit::Title(panel) => match window(panel) {+ Some(index) => (format!("panel.float.{index}.move"), "Move floating panel"),+ None => continue,+ },+ Hit::Resize(panel, ResizeEdge::BottomRight) => match window(panel) {+ Some(index) => (format!("panel.float.{index}.resize"), "Resize floating panel"),+ None => continue,+ },+ Hit::Divider(Divider::Split(path)) => {+ (format!("dock.gutter.{}", path.iter().map(|second| if *second { 'b' } else { 'a' }).collect::<String>()), "gutter")+ }+ _ => continue,};- let chrome = dock::draw_group_chrome_details(ui, &group, seqs, &t, &mut self.auto);- actions.extend(chrome.actions);- if let Some(active) = group.panels.get(group.active).copied() {- self.panel_body(ui, active, group.content);- }- ui.painter().rect_stroke(rect, t.radius, Stroke::new(1.0, t.focus), StrokeKind::Outside);- let grip = Rect::from_min_max(rect.max - vec2(14.0, 14.0), rect.max);- let response = ui.interact(grip, id.with("resize"), Sense::click_and_drag());- response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, response.enabled(), tl!("Resize floating panel")));- self.auto.add_response(&format!("panel.float.{index}.resize"), &response, "Resize floating panel");- for step in 0..3 {- let offset = 4.0 + step as f32 * 4.0;- ui.painter()- .line_segment([pos2(rect.max.x - offset, rect.max.y - 2.0), pos2(rect.max.x - 2.0, rect.max.y - offset)], Stroke::new(1.0, t.text_faint));- }- if response.hovered() || response.dragged() {- ctx.set_cursor_icon(egui::CursorIcon::ResizeNwSe);- }- let delta = floating_resize_delta(ui, &response);- if response.has_focus() {- ui.painter().rect_stroke(grip, 2.0, Stroke::new(1.5, t.focus), StrokeKind::Inside);- }- if delta != egui::Vec2::ZERO {- next = Rect::from_min_size(next.min, (next.size() + delta).max(vec2(160.0, 100.0)));- }- if next != rect {- let _ = self.dock_command(ctx, Action::MoveFloating { panel, rect: [next.min.x, next.min.y, next.width(), next.height()] });- }- dock::paint_group_focus(ui, &group, self.ui.focused, &t);- output = target(&group, chrome.tabs, false);- });- output- }-- fn panel_drag(&mut self, ctx: &egui::Context, body: Rect, targets: &[DropTarget<PanelKind>]) {- let Some(panel) = ctx.data(|data| data.get_temp::<PanelKind>(drag_id())) else { return };- let canceled =- ctx.input(|input| input.key_pressed(egui::Key::Escape) || !input.focused || (!input.pointer.primary_down() && !input.pointer.primary_released()));- if canceled || (!self.ui.dock.contains(panel) && !self.ui.floating.iter().any(|group| group.panels.contains(&panel))) {- ctx.data_mut(|data| data.remove::<PanelKind>(drag_id()));- return;- }- let Some(pos) = ctx.pointer_latest_pos() else { return };- let force_float = ctx.input(|input| input.modifiers.command);- let edge = (!force_float).then(|| workspace_edge(body, pos, targets)).flatten();- let proposal = (!force_float && edge.is_none()).then(|| resolve_drop(&panel, pos, targets)).flatten();- let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::new("dock-drop")));- let t = self.tokens;- if let Some((_, _, preview)) = edge {- painter.rect_filled(preview.shrink(2.0), t.radius, t.focus.gamma_multiply(0.2));- painter.rect_stroke(preview.shrink(2.0), t.radius, Stroke::new(2.0, t.focus), StrokeKind::Inside);+ found.push((entry, *rect));}- if let Some(proposal) = &proposal {- painter.rect_filled(proposal.preview.shrink(2.0), t.radius, t.focus.gamma_multiply(0.2));- painter.rect_stroke(proposal.preview.shrink(2.0), t.radius, Stroke::new(2.0, t.focus), StrokeKind::Inside);- if let Some(mark) = proposal.insertion {- painter.rect_filled(mark, 0.0, t.focus);- }+ for ((id, label), rect) in found {+ self.auto.add(&id, rect, label);}- let title = painter.layout_no_wrap(panel.title().to_owned(), crate::theme::Tokens::ui(12.0), Color32::WHITE);- let ghost = Rect::from_min_size(pos + vec2(12.0, 10.0), title.size() + vec2(16.0, 8.0));- painter.rect_filled(ghost, 4.0, t.focus.gamma_multiply(0.85));- painter.galley(ghost.min + vec2(8.0, 4.0), title, Color32::WHITE);- ctx.set_cursor_icon(egui::CursorIcon::Grabbing);- ctx.request_repaint();- if ctx.input(|input| input.pointer.primary_released()) {- ctx.data_mut(|data| data.remove::<PanelKind>(drag_id()));- if let Some((_, zone, _)) = edge {- if crate::menus::invoke(self, ctx, "window.dockPanel", json!({"panel": panel.id(), "zone": zone})).is_ok() {- self.ui.focused = panel;- }- return;+ }+}++impl FilmcraftApp {+ /// Over a tab strip the wheel steps through the group's tabs (down = next, one tab per notch,+ /// trackpad scrolling adding up to a notch, stopping at the ends), and a middle click on a tab+ /// closes it; on the Timeline's tab it closes the active sequence and keeps the panel.+ fn tab_strip_pointer(&mut self, ctx: &egui::Context, hits: &[(Hit<PanelKind>, Rect)]) {+ let wheel_id = area_id().with("tab-wheel");+ let pos = ctx.pointer_hover_pos();+ let over = hits.iter().find_map(|(hit, rect)| match hit {+ Hit::Tab(panel) | Hit::DragBar(panel) | Hit::Overflow(panel) if pos.is_some_and(|pos| rect.contains(pos)) => {+ Some((matches!(hit, Hit::Tab(_)), *panel))}- let action = match proposal {- Some(proposal) => Some(Action::Move { panel, anchor: proposal.anchor, placement: proposal.placement }),- None if force_float || !targets.iter().any(|target| target.rect.contains(pos)) => {- Some(Action::Float { panel, rect: [pos.x - 40.0, pos.y - 12.0, 420.0, 320.0] })- }- None => None,+ _ => None,+ });+ let Some((on_tab, panel)) = over else {+ ctx.data_mut(|data| data.remove::<f32>(wheel_id));+ return;+ };+ if on_tab && ctx.input(|input| input.pointer.button_clicked(egui::PointerButton::Middle)) {+ let result = if panel == PanelKind::Timeline && self.session.state.active_sequence.is_some() {+ self.session.execute("sequence.close", json!({})).map(drop).map_err(|error| error.to_string())+ } else {+ self.dock_command(ctx, Action::Close { panel })};- if let Some(action) = action- && self.dock_command(ctx, action).is_ok()- {- self.ui.focused = panel;+ if let Err(error) = result {+ self.ui.status = error;}+ return;+ }+ let Some((panels, active)) = group_of(&self.ui.dock, panel) else { return };+ const NOTCH: f32 = 40.0;+ let total = ctx.data(|data| data.get_temp::<f32>(wheel_id)).unwrap_or(0.0) + panels::timeline::wheel_input(ctx).delta.y;+ let steps = (total / NOTCH).trunc();+ ctx.data_mut(|data| data.insert_temp(wheel_id, total - steps * NOTCH));+ let to = (active as i64).saturating_sub(steps as i64).clamp(0, (panels.len() as i64 - 1).max(0)) as usize;+ if let Some(next) = panels.get(to).filter(|_| to != active).copied() {+ let _ = self.dock_command(ctx, Action::Activate { panel: next });+ self.ui.focused = next;}}}-/// Width of the band along the workspace border that docks beside the whole layout.-const EDGE_BAND: f32 = 8.0;--/// The outermost drop zone: near the workspace border a drop splits the root, not the group-/// under the pointer. A floating group over the border (it rejects splits) keeps the drop.-fn workspace_edge(body: Rect, pos: egui::Pos2, targets: &[DropTarget<PanelKind>]) -> Option<(Zone, &'static str, Rect)> {- if !body.is_finite() || !body.contains(pos) || targets.iter().any(|target| !target.allow_splits && target.rect.contains(pos)) {- return None;- }- let band = EDGE_BAND.min(body.width() / 4.0).min(body.height() / 4.0);- let edges = [- (pos.x - body.left(), Zone::Left, "left"),- (body.right() - pos.x, Zone::Right, "right"),- (pos.y - body.top(), Zone::Top, "top"),- (body.bottom() - pos.y, Zone::Bottom, "bottom"),- ];- let (distance, zone, name) = edges.into_iter().min_by(|a, b| a.0.total_cmp(&b.0))?;- if distance > band {- return None;+/// The panels of the tab group holding `panel`, and its active index.+fn group_of(layout: &Layout<PanelKind>, panel: PanelKind) -> Option<(Vec<PanelKind>, usize)> {+ fn find(node: &craft_ui::docking::Node<PanelKind>, panel: PanelKind) -> Option<(Vec<PanelKind>, usize)> {+ match node {+ craft_ui::docking::Node::Tabs { panels, active } if panels.contains(&panel) => Some((panels.clone(), *active)),+ craft_ui::docking::Node::Split { first, second, .. } => find(first, panel).or_else(|| find(second, panel)),+ _ => None,+ }}- let size = body.size() * 0.25;- let preview = match zone {- Zone::Left => Rect::from_min_size(body.min, vec2(size.x, body.height())),- Zone::Right => Rect::from_min_max(pos2(body.right() - size.x, body.top()), body.max),- Zone::Top => Rect::from_min_size(body.min, vec2(body.width(), size.y)),- Zone::Bottom | Zone::Center => Rect::from_min_max(pos2(body.left(), body.bottom() - size.y), body.max),- };- Some((zone, name, preview))+ layout.root.as_ref().and_then(|root| find(root, panel)).or_else(|| {+ layout.floating.iter().flat_map(|window| &window.groups).find(|group| group.panels.contains(&panel)).map(|group| (group.panels.clone(), group.active))+ })}-fn target(group: &Group, mut tabs: Vec<(PanelKind, Rect)>, allow_splits: bool) -> Option<DropTarget<PanelKind>> {- let strip = Rect::from_min_max(group.rect.min, pos2(group.rect.max.x, group.content.min.y));- // A compact grip still identifies the source group to the shared resolver.- for panel in &group.panels {- if !tabs.iter().any(|(candidate, _)| candidate == panel) {- tabs.push((*panel, Rect::NOTHING));+fn dock_style(ui: &egui::Ui, t: &Tokens) -> DockStyle {+ let mut style = DockStyle::from_ui(ui);+ style.profile = Profile::Frame;+ style.tab_height = t.tab_h;+ style.gap = t.gap;+ style.background = t.panel_bg;+ style.tab_background = t.tab_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+}++/// FilmCraft's side of the dock area for one frame.+struct FilmContent<'a> {+ app: &'a mut FilmcraftApp,+ seqs: SeqTabs,+ /// The width the sequence tabs take in the Timeline's tab strip.+ seq_width: f32,+ tokens: Tokens,+ seq_actions: Vec<SeqAction>,+ /// The ≡ button clicked: its panel and where its menu opens.+ menu: Option<(PanelKind, egui::Pos2)>,+ bodies: Vec<(PanelKind, Rect, egui::LayerId)>,+}++impl DockContent<PanelKind> for FilmContent<'_> {+ fn body(&mut self, ui: &mut egui::Ui, panel: &PanelKind) {+ let t = self.tokens;+ let rect = ui.max_rect();+ self.bodies.push((*panel, rect, ui.layer_id()));+ self.app.auto.add(&format!("panel.{}", panel.id()), rect, panel.title());+ let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect).id_salt(("panel", panel.id())));+ child.set_clip_rect(rect.intersect(ui.clip_rect()));+ panels::show(self.app, &mut child, *panel, rect);+ // Painted after the body so child backgrounds cannot hide the focus outline (#1075).+ if self.app.ui.focused == *panel {+ ui.painter().rect_stroke(rect, 0.0, Stroke::new(1.0, t.focus), StrokeKind::Inside);}}- Some(DropTarget { anchor: *group.panels.get(group.active)?, rect: group.rect, tab_strip: Some(strip), tabs, allow_splits, accepts_tabs: true })-}-/// A corner is a two-axis resize control; focused arrows belong to it and Tab moves on.-fn floating_resize_delta(ui: &mut egui::Ui, response: &egui::Response) -> egui::Vec2 {- if response.drag_started() {- response.request_focus();+ fn logical_label(&self, panel: &PanelKind) -> String {+ crate::i18n::t(panel.title()).to_string()}- let mut delta = if response.dragged() { response.drag_delta() } else { egui::Vec2::ZERO };- if response.has_focus() {- ui.memory_mut(|memory| {- memory.set_focus_lock_filter(response.id, egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() })- });- ui.input_mut(|input| {- for (key, amount) in [- (egui::Key::ArrowLeft, vec2(-8.0, 0.0)),- (egui::Key::ArrowRight, vec2(8.0, 0.0)),- (egui::Key::ArrowUp, vec2(0.0, -8.0)),- (egui::Key::ArrowDown, vec2(0.0, 8.0)),- ] {- if input.consume_key(egui::Modifiers::NONE, key) {- delta += amount;- }- }- });++ /// With no sequence open, the Timeline's tab says so.+ fn label(&mut self, _ui: &egui::Ui, panel: &PanelKind, logical: &str, _font: &egui::FontId, _color: egui::Color32) -> egui::WidgetText {+ if *panel == PanelKind::Timeline && self.seqs.open.is_empty() { self.seqs.label().into() } else { logical.into() }+ }++ /// A floated panel is at most 420 by 320 points: panel bodies fill their frame, so their+ /// drawn height says nothing about the size they need.+ fn floating_size(&self, _panel: &PanelKind) -> Option<egui::Vec2> {+ Some(vec2(420.0, 320.0))+ }++ /// Tools and the audio meters are narrow strips without a tab strip.+ fn bare(&self, panel: &PanelKind) -> bool {+ panel.compact()+ }++ /// The ≡ menu, and the Timeline's sequence tabs before it while the Timeline is shown.+ fn group_header_width(&self, _panels: &[PanelKind], active: &PanelKind, _floating: bool) -> f32 {+ if *active == PanelKind::Timeline && !self.seqs.open.is_empty() { self.seq_width + MENU_W } else { MENU_W }+ }++ /// The ≡ panel menu of the group's shown panel; for the Timeline, its sequence tabs first.+ 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(egui::pos2((header.max.x - MENU_W).max(header.min.x), header.min.y), header.max);+ if *active == PanelKind::Timeline && !self.seqs.open.is_empty() {+ let strip = Rect::from_min_max(header.min, egui::pos2(menu.min.x, header.max.y));+ self.seq_actions.extend(dock::sequence_tabs(ui, strip, &self.seqs, &t, &mut self.app.auto));+ }+ let rect = Rect::from_center_size(menu.center(), vec2(18.0, 18.0));+ let response = ui.interact(rect, egui::Id::new(("panel-menu-button", active.id())), Sense::click());+ response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::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);+ dock::paint_widget_focus(ui.painter(), &response, &t);+ if response.clicked() {+ self.app.ui.focused = *active;+ self.menu = Some((*active, rect.left_bottom()));+ }}- if response.enabled() { delta } else { egui::Vec2::ZERO }}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex c838e6fe9..2db18de6f 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -37,7 +37,6 @@ pub mod control;pub mod crash;pub mod credits;pub mod dock;-mod dock_shared;mod dock_ui;/// Thumbnail textures kept before the least recently used are freed (each is up to 320 px wide).const MAX_THUMB_TEXTURES: usize = 512;@@ -73,7 +72,7 @@ use filmcraft_time::Tick;use serde_json::{Value, json};pub use control::ControlRequest;-use dock::PanelKind;+use dock::{LayoutExt as _, PanelKind};use frames::{FrameKey, FrameServer, Target};use native_dialogs::FileDialog;use state::UiState;@@ -854,9 +853,7 @@ impl FilmcraftApp {pub fn set_workspace(&mut self, name: &str) {self.ui.workspace = name.to_string();- let layout = dock::saved_docking(&self.workspaces, name);- self.ui.dock = layout.root;- self.ui.floating = layout.floating;+ self.ui.dock = dock::saved_docking(&self.workspaces, name);self.pending_panel_raise = None;self.ui.keys.maximized = None;if self.workspaces.current != name {@@ -874,20 +871,20 @@ impl FilmcraftApp {pub fn show_panel(&mut self, p: PanelKind) {// closed while floating: it floats again where it was (#1985); taken before the Timeline's// own restore below docks it- let open = self.ui.dock.contains(p) || self.ui.floating.iter().any(|group| group.panels.contains(&p));+ let open = self.ui.dock.contains(&p);let refloat = match self.ui.closed_floating.iter().position(|(k, _)| *k == p) {Some(i) if !open => Some(self.ui.closed_floating.remove(i).1),_ => None,};- if p == PanelKind::Timeline && !self.ui.floating.iter().any(|group| group.panels.contains(&p)) {+ if p == PanelKind::Timeline {self.ui.dock.restore_timeline();}- if !self.ui.dock.contains(p) && !self.ui.floating.iter().any(|group| group.panels.contains(&p)) {+ if !self.ui.dock.contains(&p) {let near = match p {// a side panel beside Properties (or Essential Sound), never over the Program monitorPanelKind::TextToSpeech => [PanelKind::Properties, PanelKind::EssentialSound, PanelKind::EssentialGraphics].into_iter()- .find(|k| self.ui.dock.contains(*k))+ .find(|k| self.ui.dock.contains(k)).unwrap_or(PanelKind::Program),PanelKind::LumetriColor | PanelKind::EssentialGraphics | PanelKind::EssentialSound | PanelKind::Properties => PanelKind::Program,PanelKind::Source@@ -1804,9 +1801,7 @@ impl FilmcraftApp {filmcraft_engine::Event::OpenSequence(_) => {// show the sequence with its own view (or fitted, the first time)self.timeline_view_of = None;- if !self.ui.floating.iter().any(|group| group.panels.contains(&PanelKind::Timeline)) {- self.ui.dock.restore_timeline();- }+ self.ui.dock.restore_timeline();let _ = self.apply_dock(craft_ui::docking::Action::Activate { panel: PanelKind::Timeline });}filmcraft_engine::Event::OpenSource(_) => {diff --git a/crates/ui-egui/src/panels/keyboard.rs b/crates/ui-egui/src/panels/keyboard.rsindex bdf744196..91ce44441 100644--- a/crates/ui-egui/src/panels/keyboard.rs+++ b/crates/ui-egui/src/panels/keyboard.rs@@ -235,7 +235,7 @@ pub fn route(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, params: &Val/// Maximize `p`, or restore the layout when a panel is maximized (also the panel menu's Maximize //// Restore Frame). A maximized panel that has since been closed counts as restored.pub(crate) fn toggle_maximize(app: &mut FilmcraftApp, p: PanelKind) -> Value {- let current = app.ui.keys.maximized.filter(|q| app.ui.dock.contains(*q) || app.ui.floating.iter().any(|g| g.panels.contains(q)));+ let current = app.ui.keys.maximized.filter(|q| app.ui.dock.contains(q));app.ui.keys.maximized = if current.is_some() { None } else { Some(p) };if let Some(p) = app.ui.keys.maximized {let _ = app.apply_dock(craft_ui::docking::Action::Activate { panel: p });@@ -255,11 +255,8 @@ fn panel_under_pointer(app: &FilmcraftApp, ctx: &egui::Context) -> Option<PanelK/// Visible panels in layout order (the active tab of each frame).fn visible_panels(app: &FilmcraftApp) -> Vec<PanelKind> {- let mut all = Vec::new();- app.ui.dock.panels(&mut all);- let mut visible: Vec<_> = all.into_iter().filter(|p| app.ui.dock.is_visible(*p) && !p.compact()).collect();- visible.extend(app.ui.floating.iter().filter_map(|group| group.panels.get(group.active).copied()).filter(|panel| !panel.compact()));- visible+ use crate::dock::LayoutExt as _;+ app.ui.dock.visible_panels().into_iter().filter(|p| !p.compact()).collect()}fn cycle_panel(app: &mut FilmcraftApp, next: bool) -> Value {diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rsindex ff18ab0f2..3b7d33dfe 100644--- a/crates/ui-egui/src/panels/mod.rs+++ b/crates/ui-egui/src/panels/mod.rs@@ -309,7 +309,7 @@ pub fn panel_menu_popup(app: &mut FilmcraftApp, ui: &mut egui::Ui) {let _ = crate::menus::invoke(app, ui.ctx(), "window.floatPanel", serde_json::json!({"panel": p.id()}));close = true;}- let maximized = app.ui.keys.maximized.is_some_and(|q| app.ui.dock.contains(q) || app.ui.floating.iter().any(|g| g.panels.contains(&q)));+ let maximized = app.ui.keys.maximized.is_some_and(|q| app.ui.dock.contains(&q));let r = ui.button(if maximized { tl!("Restore Frame") } else { tl!("Maximize Frame") });app.auto.add(&format!("panel.menu.{}.maximize", p.id()), r.rect, if maximized { "Restore Frame" } else { "Maximize Frame" });if r.clicked() {diff --git a/crates/ui-egui/src/panels/workspaces.rs b/crates/ui-egui/src/panels/workspaces.rsindex 5678bd171..89ac924a1 100644--- a/crates/ui-egui/src/panels/workspaces.rs+++ b/crates/ui-egui/src/panels/workspaces.rs@@ -56,17 +56,14 @@ pub fn route(app: &mut FilmcraftApp, id: &str, params: &Value) -> Option<Result</// Save the current layout as the saved layout of `name`.fn save(app: &mut FilmcraftApp, name: &str) -> Result<(), String> {- crate::dock::Layout { root: app.ui.dock.clone(), floating: app.ui.floating.clone() }.validate()?;- let layout = serde_json::to_value(&app.ui.dock).map_err(|e| e.to_string())?;- let floating = if app.ui.floating.is_empty() { serde_json::Value::Null } else { serde_json::to_value(&app.ui.floating).map_err(|e| e.to_string())? };+ let workspace = crate::dock::Workspace::new(app.ui.dock.clone());+ workspace.validate().map_err(|e| e.to_string())?;+ let workspace = serde_json::to_value(&workspace).map_err(|e| e.to_string())?;let mut next = app.workspaces.clone();let saved = &mut next.saved;match saved.iter_mut().find(|s| s.name == name) {- Some(s) => {- s.layout = layout;- s.floating = floating;- }- None => saved.push(dock::SavedWorkspace { name: name.to_string(), layout, floating }),+ Some(s) => *s = dock::SavedWorkspace { name: name.to_string(), workspace, ..Default::default() },+ None => saved.push(dock::SavedWorkspace { name: name.to_string(), workspace, ..Default::default() }),}next.current = name.to_string();app.set_workspaces(next)diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rsindex e0710236c..212a60a78 100644--- a/crates/ui-egui/src/state.rs+++ b/crates/ui-egui/src/state.rs@@ -3,7 +3,7 @@use serde::{Deserialize, Serialize};-use crate::dock::{DockNode, PanelKind};+use crate::dock::PanelKind;use crate::icons::Icon;#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]@@ -433,9 +433,8 @@ pub struct UiState {pub tool: Tool,pub mode: Mode,pub workspace: String,- pub dock: DockNode,- #[serde(default)]- pub floating: Vec<crate::dock::Floating>,+ /// The panel arrangement in use: craft-ui's frame tree and floating windows.+ pub dock: crate::dock::Layout,/// Where each panel closed while floating was ([x, y, width, height]): opening it again/// brings it back there, floating, instead of docked (#1985).#[serde(default)]@@ -963,7 +962,6 @@ impl Default for UiState {tool: Tool::Selection,mode: Mode::Edit,workspace: "Editing".into(),- floating: vec![],closed_floating: vec![],dock: crate::dock::workspace("Editing"),focused: PanelKind::Timeline,diff --git a/crates/ui-egui/tests/meters_ui.rs b/crates/ui-egui/tests/meters_ui.rsindex 8d835ecfb..cbd24fd7e 100644--- a/crates/ui-egui/tests/meters_ui.rs+++ b/crates/ui-egui/tests/meters_ui.rs@@ -5,10 +5,12 @@use std::sync::mpsc::{Sender, channel};use std::sync::{Arc, Mutex};+use craft_ui::docking::Node;+use craft_ui::layout::SplitSize;use egui_kittest::Harness;use filmcraft_engine::Session;use filmcraft_ui_egui::control::ControlRequest;-use filmcraft_ui_egui::dock::{DockNode, PanelKind, SplitSize};+use filmcraft_ui_egui::dock::PanelKind;use filmcraft_ui_egui::{AudioOut, FilmcraftApp};use serde_json::{Value, json};@@ -90,17 +92,17 @@ impl Driver {/// Give the Audio Meters panel `width` points (it sits in a fixed-width split beside the/// Timeline).fn meters_width(&mut self, width: f32) {- fn set(n: &mut DockNode, width: f32) -> bool {+ fn set(n: &mut Node<PanelKind>, width: f32) -> bool {match n {- DockNode::Split { size, b, .. } if matches!(&**b, DockNode::Tabs { panels, .. } if panels.as_slice() == [PanelKind::AudioMeters]) => {- *size = SplitSize::FixedB(width);+ Node::Split { size, second, .. } if matches!(&**second, Node::Tabs { panels, .. } if panels.as_slice() == [PanelKind::AudioMeters]) => {+ *size = SplitSize::FixedSecond(width);true}- DockNode::Split { a, b, .. } => set(a, width) || set(b, width),- DockNode::Tabs { .. } => false,+ Node::Split { first, second, .. } => set(first, width) || set(second, width),+ _ => false,}}- assert!(set(&mut self.harness.state_mut().ui.dock, width));+ assert!(self.harness.state_mut().ui.dock.root.as_mut().is_some_and(|root| set(root, width)));self.frames(3);}/// The level the left bar shows, in dB.diff --git a/crates/ui-egui/tests/monitor_geometry.rs b/crates/ui-egui/tests/monitor_geometry.rsindex 700657e19..6ecaa81d4 100644--- a/crates/ui-egui/tests/monitor_geometry.rs+++ b/crates/ui-egui/tests/monitor_geometry.rs@@ -6,7 +6,7 @@ use egui_kittest::kittest::{NodeT, Queryable};use filmcraft_engine::Session;use filmcraft_ui_egui::{FilmcraftApp,- dock::{self, DockNode, PanelKind, SeqTabs},+ dock::PanelKind,panels::monitor::{self, Which},theme::{self, ThemeKind},};@@ -25,14 +25,12 @@ fn harness_at_scale(width: f32, kind: ThemeKind, which: Which, scale: f32) -> Haapp.set_theme(ui.ctx(), kind);app.auto.begin_frame();let panel = if which == Which::Source { PanelKind::Source } else { PanelKind::Program };- let mut node = DockNode::Tabs { panels: vec![panel], active: 0 };- let mut groups = Vec::new();- dock::layout(ui, &mut node, ui.max_rect(), &app.tokens, "monitor", &mut groups, &mut app.auto);- for group in groups {- // Exercise the actual parent chrome, including its themed panel background.- dock::draw_group_chrome(ui, &group, panel, &SeqTabs::default(), &app.tokens, &mut app.auto);- monitor::show(app, ui, group.content, which);- }+ // The panel frame as docking draws it: a tab strip over the themed panel background.+ let frame = ui.max_rect();+ ui.painter().rect_filled(frame, 0.0, app.tokens.panel_bg);+ let content = egui::Rect::from_min_max(egui::pos2(frame.min.x, frame.min.y + app.tokens.tab_h), frame.max);+ let _ = panel;+ monitor::show(app, ui, content, which);let source = filmcraft_ui_egui::panels::dragged_source(ui);ui.ctx().data_mut(|data| data.insert_temp(egui::Id::new("observed-source-drag"), source));},diff --git a/crates/ui-egui/tests/nest_editing_ui.rs b/crates/ui-egui/tests/nest_editing_ui.rsindex 4ad6e6abb..33394004b 100644--- a/crates/ui-egui/tests/nest_editing_ui.rs+++ b/crates/ui-egui/tests/nest_editing_ui.rs@@ -97,14 +97,14 @@ fn reveal_in_project_shows_the_clips_item_in_the_project_panel() {};let bin = d.app().session.project.root.parent_of(item).expect("the demo keeps its footage in a bin").0;// the Project panel is closed, its bins are collapsed and a search hides everything- d.app().ui.dock.close(PanelKind::Project);+ d.app().ui.dock.apply(craft_ui::docking::Action::Close { panel: PanelKind::Project }).unwrap();d.app().ui.expanded_bins.clear();d.app().ui.project_search = "no such thing".into();d.frames(2);assert!(!d.has(&format!("project.item.{}", item.0)));d.exec("clip.revealInProject", json!({"clip": clip}));d.frames(3);- assert!(d.app().ui.dock.is_visible(PanelKind::Project), "{mode:?}");+ assert!(filmcraft_ui_egui::dock::LayoutExt::is_visible(&d.app().ui.dock, PanelKind::Project), "{mode:?}");assert!(d.app().ui.project_search.is_empty());assert_eq!(d.app().session.state.project_selection, vec![item]);if mode == ViewMode::List {diff --git a/crates/ui-egui/tests/panels_ui.rs b/crates/ui-egui/tests/panels_ui.rsindex 483bee1c9..de79a9fba 100644--- a/crates/ui-egui/tests/panels_ui.rs+++ b/crates/ui-egui/tests/panels_ui.rs@@ -183,7 +183,7 @@ fn every_panel_opens_from_the_window_menu() {/// and closing every panel still leaves a dock that Window ▸ can reopen panels into.#[test]fn panel_menu_maximize_restores_and_an_empty_dock_reopens() {- use filmcraft_ui_egui::dock::{DockNode, PanelKind};+ use filmcraft_ui_egui::dock::PanelKind;let mut d = Driver::demo();let layout = d.app().ui.dock.clone();d.click("panel.menu.Program");@@ -198,12 +198,10 @@ fn panel_menu_maximize_restores_and_an_empty_dock_reopens() {assert_eq!(d.app().ui.dock, layout, "the layout survives maximize / restore");assert!(d.has("panel.Timeline"));- let mut all = Vec::new();- layout.panels(&mut all);- for p in all {+ for p in layout.panels() {d.ok("ui.panel.close", json!({"panel": p.id()}));}- assert_eq!(d.app().ui.dock, DockNode::Tabs { panels: vec![], active: 0 });+ assert_eq!(d.app().ui.dock.root, None);d.ok("ui.menu.invoke", json!({"id": "window.panel.Program"}));d.ok("ui.menu.invoke", json!({"id": "window.panel.Timeline"}));d.frames(3);@@ -215,16 +213,17 @@ fn panel_menu_maximize_restores_and_an_empty_dock_reopens() {/// content the wheel leaves the tabs alone.#[test]fn wheel_over_a_tab_strip_switches_tabs() {- use filmcraft_ui_egui::dock::{DockNode, PanelKind};+ use craft_ui::docking::Node;+ use filmcraft_ui_egui::dock::PanelKind;fn shown(d: &mut Driver) -> PanelKind {- fn find(n: &DockNode) -> Option<PanelKind> {+ fn find(n: &Node<PanelKind>) -> Option<PanelKind> {match n {- DockNode::Tabs { panels, active } if panels.contains(&PanelKind::Project) => panels.get(*active).copied(),- DockNode::Tabs { .. } => None,- DockNode::Split { a, b, .. } => find(a).or_else(|| find(b)),+ Node::Tabs { panels, active } if panels.contains(&PanelKind::Project) => panels.get(*active).copied(),+ Node::Split { first, second, .. } => find(first).or_else(|| find(second)),+ _ => None,}}- find(&d.app().ui.dock).unwrap()+ d.app().ui.dock.root.as_ref().and_then(find).unwrap()}fn wheel(d: &mut Driver, dy: f64) {let id = format!("panel.tab.{}", shown(d).id());diff --git a/crates/ui-egui/tests/sequence_tabs_ui.rs b/crates/ui-egui/tests/sequence_tabs_ui.rsindex d2f73b675..a2702c2ac 100644--- a/crates/ui-egui/tests/sequence_tabs_ui.rs+++ b/crates/ui-egui/tests/sequence_tabs_ui.rs@@ -91,7 +91,7 @@ impl Driver {}fn has_timeline(&mut self) -> bool {- self.app().ui.dock.contains(filmcraft_ui_egui::dock::PanelKind::Timeline)+ self.app().ui.dock.contains(&filmcraft_ui_egui::dock::PanelKind::Timeline)}}@@ -170,7 +170,7 @@ fn timeline_has_a_tab_per_open_sequence() {assert!(d.has_timeline(), "closing the last sequence keeps the Timeline panel");assert!(d.has("panel.tab.Timeline"));// reopening from the project brings it back, even if the panel itself was closed- d.app().ui.dock.close(filmcraft_ui_egui::dock::PanelKind::Timeline);+ d.app().ui.dock.apply(craft_ui::docking::Action::Close { panel: filmcraft_ui_egui::dock::PanelKind::Timeline }).unwrap();d.frames(2);assert!(!d.has_timeline());d.exec("sequence.open", json!({"item": main}));diff --git a/crates/ui-egui/tests/shared_docking_ui.rs b/crates/ui-egui/tests/shared_docking_ui.rsindex 7d087bcb4..95ce475ec 100644--- a/crates/ui-egui/tests/shared_docking_ui.rs+++ b/crates/ui-egui/tests/shared_docking_ui.rs@@ -1,34 +1,55 @@//! Shared docking preserves FilmCraft document state and legacy workspace files.-use craft_ui::docking::{Action, Placement, Zone};+use craft_ui::docking::{Action, Node, Placement, Zone};+use craft_ui::layout::{SplitAxis, SplitSize};use egui::{Event, Modifiers, PointerButton, Rect, pos2, vec2};use egui_kittest::Harness;use egui_kittest::kittest::{NodeT, Queryable};use filmcraft_engine::Session;use filmcraft_ui_egui::{FilmcraftApp,- dock::{self, DockNode, Layout, PanelKind, SplitSize},+ dock::{self, Layout, LayoutExt, PanelKind},menus,};use serde_json::json;-fn layout() -> Layout {- Layout {- root: DockNode::Split {- vertical: false,- size: SplitSize::FixedA(400.0),- a: Box::new(DockNode::Tabs { panels: vec![PanelKind::Project, PanelKind::Info, PanelKind::History], active: 1 }),- b: Box::new(DockNode::Tabs { panels: vec![PanelKind::Source, PanelKind::Program], active: 1 }),- },- floating: vec![],+fn tabs(panels: &[PanelKind], active: usize) -> Node<PanelKind> {+ Node::Tabs { panels: panels.to_vec(), active }+}++fn split(vertical: bool, size: SplitSize, a: Node<PanelKind>, b: Node<PanelKind>) -> Node<PanelKind> {+ Node::Split { axis: if vertical { SplitAxis::Vertical } else { SplitAxis::Horizontal }, size, first: Box::new(a), second: Box::new(b) }+}++fn root(node: Node<PanelKind>) -> Layout {+ Layout { root: Some(node), floating: vec![] }+}++/// Whether a panel is in the docked frame tree (not a floating window).+trait Docked {+ fn docked(&self, panel: PanelKind) -> bool;+}++impl Docked for Layout {+ fn docked(&self, panel: PanelKind) -> bool {+ Layout { root: self.root.clone(), floating: vec![] }.contains(&panel)}}+fn layout() -> Layout {+ root(split(+ false,+ SplitSize::FixedFirst(400.0),+ tabs(&[PanelKind::Project, PanelKind::Info, PanelKind::History], 1),+ tabs(&[PanelKind::Source, PanelKind::Program], 1),+ ))+}+#[test]fn shared_transactions_keep_selection_and_reject_invalid_moves_atomically() {let mut layout = layout();layout.apply(Action::Close { panel: PanelKind::Project }).unwrap();- assert!(layout.root.is_visible(PanelKind::Info));+ assert!(layout.is_visible(PanelKind::Info));let before = layout.clone();for action in [Action::Move { panel: PanelKind::Info, anchor: PanelKind::Tools, placement: Placement::Split(Zone::Left) },@@ -41,20 +62,22 @@ fn shared_transactions_keep_selection_and_reject_invalid_moves_atomically() {layout.apply(Action::Float { panel: PanelKind::Info, rect: [50.0, 50.0, 400.0, 300.0] }).unwrap();layout.apply(Action::Move { panel: PanelKind::Info, anchor: PanelKind::Program, placement: Placement::Split(Zone::Bottom) }).unwrap();assert!(layout.floating.is_empty());- assert!(layout.root.is_visible(PanelKind::Info));+ assert!(layout.is_visible(PanelKind::Info));}#[test]fn builtin_and_legacy_workspace_shapes_roundtrip_and_save_floating() {for name in dock::WORKSPACES {- let root = dock::workspace(name);- let before = serde_json::to_value(&root).unwrap();- let prefs: dock::WorkspacePrefs = serde_json::from_value(json!({"saved": [{"name": name, "layout": before}], "current": name})).unwrap();- let loaded = dock::saved_docking(&prefs, name);- loaded.validate().unwrap();- assert_eq!(loaded.root, root);- assert!(loaded.floating.is_empty());- assert!(serde_json::to_value(&prefs).unwrap()["saved"][0].get("floating").is_none());+ let layout = dock::workspace(name);+ for entry in+ [json!({"name": name, "workspace": dock::Workspace::new(layout.clone())}), json!({"name": name, "layout": legacy(layout.root.as_ref().unwrap())})]+ {+ let prefs: dock::WorkspacePrefs = serde_json::from_value(json!({"saved": [entry], "current": name})).unwrap();+ let loaded = dock::saved_docking(&prefs, name);+ loaded.validate().unwrap();+ assert_eq!(loaded, layout);+ assert!(serde_json::to_value(&prefs).unwrap()["saved"][0].get("floating").is_none());+ }}let dir = std::env::temp_dir().join(format!("filmcraft-shared-dock-{}", std::process::id()));std::fs::create_dir_all(&dir).unwrap();@@ -62,13 +85,13 @@ fn builtin_and_legacy_workspace_shapes_roundtrip_and_save_floating() {session.prefs_path = Some(dir.join("preferences.json"));let mut app = FilmcraftApp::new(session);let ctx = egui::Context::default();- app.ui.dock = layout().root;+ app.ui.dock = layout();menus::invoke(&mut app, &ctx, "window.floatPanel", json!({"panel": "Info", "rect": [45, 65, 420, 320]})).unwrap();menus::invoke(&mut app, &ctx, "window.workspace.saveAs", json!({"name": "Floating test"})).unwrap();let prefs = dock::WorkspacePrefs::load(&dir.join(dock::WORKSPACES_FILE));let restored = dock::saved_docking(&prefs, "Floating test");- assert_eq!(restored.floating, app.ui.floating);- assert_eq!(restored.root, app.ui.dock);+ assert_eq!(restored, app.ui.dock);+ assert!(prefs.saved[0].layout.is_null() && !prefs.saved[0].workspace.is_null());let mut restarted_session = Session::default();restarted_session.prefs_path = Some(dir.join("preferences.json"));let restarted = FilmcraftApp::new(restarted_session);@@ -76,32 +99,49 @@ fn builtin_and_legacy_workspace_shapes_roundtrip_and_save_floating() {for _ in 0..4 {step(&mut h);}- assert_eq!(h.state().ui.dock, restored.root);- assert_eq!(h.state().ui.floating, restored.floating);+ assert_eq!(h.state().ui.dock, restored);std::fs::remove_dir_all(dir).unwrap();}#[test]fn legacy_effects_workspace_drops_only_the_known_inactive_duplicate() {let expected = dock::workspace("Effects");- let mut legacy = expected.clone();- fn duplicate(node: &mut DockNode) {+ let mut legacy_tree = expected.root.clone().unwrap();+ fn duplicate(node: &mut Node<PanelKind>) {match node {- DockNode::Tabs { panels, active } if panels.as_slice() == [PanelKind::EssentialGraphics] => {+ Node::Tabs { panels, active } if panels.as_slice() == [PanelKind::EssentialGraphics] => {panels.insert(0, PanelKind::EffectControls);*active = 1;}- DockNode::Split { a, b, .. } => {- duplicate(a);- duplicate(b);+ Node::Split { first, second, .. } => {+ duplicate(first);+ duplicate(second);}- DockNode::Tabs { .. } => {}+ _ => {}}}- duplicate(&mut legacy);+ duplicate(&mut legacy_tree);let prefs: dock::WorkspacePrefs =- serde_json::from_value(json!({"saved": [{"name": "Historical Effects", "layout": legacy}], "current": "Historical Effects"})).unwrap();- assert_eq!(dock::saved_docking(&prefs, "Historical Effects").root, expected);+ serde_json::from_value(json!({"saved": [{"name": "Historical Effects", "layout": legacy(&legacy_tree)}], "current": "Historical Effects"})).unwrap();+ assert_eq!(dock::saved_docking(&prefs, "Historical Effects"), expected);+}++/// The frame tree as FilmCraft wrote it before its workspaces were craft-ui workspaces.+fn legacy(node: &Node<PanelKind>) -> serde_json::Value {+ match node {+ Node::Tabs { panels, active } => json!({"Tabs": {"panels": panels, "active": active}}),+ Node::Split { axis, size, first, second } => json!({"Split": {+ "vertical": *axis == SplitAxis::Vertical,+ "size": match size {+ SplitSize::Ratio(v) => json!({"Ratio": v}),+ SplitSize::FixedFirst(v) => json!({"FixedA": v}),+ SplitSize::FixedSecond(v) => json!({"FixedB": v}),+ },+ "a": legacy(first),+ "b": legacy(second),+ }}),+ _ => unreachable!(),+ }}fn step(h: &mut Harness<'_, FilmcraftApp>) {@@ -159,12 +199,7 @@ fn real_panel_drag_merges_splits_floats_and_redocks_without_editing_documents()for _ in 0..4 {step(&mut h);}- h.state_mut().ui.dock = DockNode::Split {- vertical: true,- size: SplitSize::Ratio(0.62),- a: Box::new(layout().root),- b: Box::new(DockNode::Tabs { panels: vec![PanelKind::Timeline], active: 0 }),- };+ h.state_mut().ui.dock = root(split(true, SplitSize::Ratio(0.62), layout().root.unwrap(), tabs(&[PanelKind::Timeline], 0)));for _ in 0..3 {step(&mut h);}@@ -197,26 +232,28 @@ fn real_panel_drag_merges_splits_floats_and_redocks_without_editing_documents()assert!(h.state().auto.find("program.transport.playhead.stepForward").is_some());let from = rect(&h, "panel.tab.Info").center();drag(&mut h, from, pos2(700.0, 400.0), Modifiers::COMMAND);- assert_eq!(h.state().ui.floating.len(), 1);- assert_eq!(h.get_by_label("Resize floating panel").accesskit_node().role(), egui::accesskit::Role::Button);+ assert_eq!(h.state().ui.dock.floating.len(), 1);+ assert_eq!(h.query_all_by_label("Resize panel window").next().unwrap().accesskit_node().role(), egui::accesskit::Role::Button);action_log.push(action_state(&h, "floated"));- let original = h.state().ui.floating[0].rect;+ let original = h.state().ui.dock.floating[0].rect;let grip = rect(&h, "panel.float.0.resize").center();drag(&mut h, grip, grip + vec2(36.0, 24.0), Modifiers::NONE);- assert!(h.state().ui.floating[0].rect[2] > original[2] + 25.0);- assert!(h.state().ui.floating[0].rect[3] > original[3] + 15.0);+ assert!(h.state().ui.dock.floating[0].rect[2] > original[2] + 25.0);+ assert!(h.state().ui.dock.floating[0].rect[3] > original[3] + 15.0);action_log.push(action_state(&h, "resized"));- let grip_id = egui::Id::new(("floating-panel", PanelKind::Info.id())).with("resize");+ let grip_id = egui::Id::new("filmcraft-docking").with(("floating", PanelKind::Info)).with("resize");+ h.ctx.memory_mut(|memory| memory.request_focus(grip_id));+ step(&mut h);assert_eq!(h.ctx.memory(|memory| memory.focused()), Some(grip_id));- let before_keys = h.state().ui.floating[0].rect;+ let before_keys = h.state().ui.dock.floating[0].rect;for key in [egui::Key::ArrowRight, egui::Key::ArrowDown] {for pressed in [true, false] {h.event(Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE });step(&mut h);}}- assert_eq!(h.state().ui.floating[0].rect[2], before_keys[2] + 8.0);- assert_eq!(h.state().ui.floating[0].rect[3], before_keys[3] + 8.0);+ assert_eq!(h.state().ui.dock.floating[0].rect[2], before_keys[2] + 8.0);+ assert_eq!(h.state().ui.dock.floating[0].rect[3], before_keys[3] + 8.0);h.event(Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });step(&mut h);h.event(Event::Key { key: egui::Key::Tab, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE });@@ -225,29 +262,31 @@ fn real_panel_drag_merges_splits_floats_and_redocks_without_editing_documents()}assert_ne!(h.ctx.memory(|memory| memory.focused()), Some(grip_id));action_log.push(action_state(&h, "keyboard-resized"));- let resized = h.state().ui.floating[0].rect;+ let resized = h.state().ui.dock.floating[0].rect;let header = rect(&h, "panel.float.0.move");let from = pos2(header.right() - 24.0, header.center().y);drag(&mut h, from, from - vec2(24.0, 18.0), Modifiers::NONE);- assert!(h.state().ui.floating[0].rect[0] < resized[0] - 15.0);- assert!(h.state().ui.floating[0].rect[1] < resized[1] - 10.0);+ assert!(h.state().ui.dock.floating[0].rect[0] < resized[0] - 15.0);+ assert!(h.state().ui.dock.floating[0].rect[1] < resized[1] - 10.0);action_log.push(action_state(&h, "moved"));let saved_root = h.state().ui.dock.clone();- let saved_floating = h.state().ui.floating.clone();+ let saved_floating = h.state().ui.dock.floating.clone();let ctx = h.ctx.clone();+ // Maximize Frame fills the area with a docked frame+ h.state_mut().ui.focused = PanelKind::Program;menus::invoke(h.state_mut(), &ctx, "window.maximizeFrame", json!({})).unwrap();for _ in 0..3 {step(&mut h);}- assert!(rect(&h, "panel.Info").width() > 1000.0);+ assert!(rect(&h, "panel.Program").width() > 1000.0);action_log.push(action_state(&h, "maximized"));assert_eq!(h.state().ui.dock, saved_root);- assert_eq!(h.state().ui.floating, saved_floating);+ assert_eq!(h.state().ui.dock.floating, saved_floating);menus::invoke(h.state_mut(), &ctx, "window.maximizeFrame", json!({})).unwrap();for _ in 0..3 {step(&mut h);}- assert_eq!(h.state().ui.floating, saved_floating);+ assert_eq!(h.state().ui.dock.floating, saved_floating);if let Some(directory) = &snapshots {std::fs::create_dir_all(directory).unwrap();@@ -256,7 +295,7 @@ fn real_panel_drag_merges_splits_floats_and_redocks_without_editing_documents()let from = rect(&h, "panel.tab.Info").center();let to = rect(&h, "panel.History").center();drag(&mut h, from, to, Modifiers::NONE);- assert!(h.state().ui.floating.is_empty());+ assert!(h.state().ui.dock.floating.is_empty());action_log.push(action_state(&h, "redocked"));assert!(std::sync::Arc::ptr_eq(&project, &h.state().session.project));assert_eq!(playheads, h.state().session.state.playheads);@@ -278,7 +317,7 @@ fn real_panel_drag_merges_splits_floats_and_redocks_without_editing_documents()#[test]fn dropping_on_the_window_edge_docks_beside_the_whole_workspace() {let mut app = FilmcraftApp::new(Session::default());- app.ui.dock = layout().root;+ app.ui.dock = layout();let mut h = Harness::builder().with_size(vec2(1200.0, 760.0)).build_eframe(move |_| app);for _ in 0..4 {step(&mut h);@@ -289,60 +328,59 @@ fn dropping_on_the_window_edge_docks_beside_the_whole_workspace() {drag(&mut h, from, pos2(leftmost.left() + 2.0, leftmost.center().y), Modifiers::NONE);assert_eq!(h.state().ui.dock,- DockNode::Split {- vertical: false,- size: SplitSize::Ratio(0.25),- a: Box::new(DockNode::Tabs { panels: vec![PanelKind::Info], active: 0 }),- b: Box::new(DockNode::Split {- vertical: false,- size: SplitSize::FixedA(400.0),- a: Box::new(DockNode::Tabs { panels: vec![PanelKind::Project, PanelKind::History], active: 1 }),- b: Box::new(DockNode::Tabs { panels: vec![PanelKind::Source, PanelKind::Program], active: 1 }),- }),- }+ root(split(+ false,+ SplitSize::Ratio(0.25),+ tabs(&[PanelKind::Info], 0),+ split(false, SplitSize::FixedFirst(400.0), tabs(&[PanelKind::Project, PanelKind::History], 1), tabs(&[PanelKind::Source, PanelKind::Program], 1)),+ )));}#[test]fn dock_panel_without_anchor_docks_along_a_workspace_edge() {let mut app = FilmcraftApp::new(Session::default());- app.ui.dock = layout().root;+ app.ui.dock = layout();let ctx = egui::Context::default();menus::invoke(&mut app, &ctx, "window.dockPanel", json!({"panel": "Program", "zone": "bottom"})).unwrap();- let DockNode::Split { vertical: true, size: SplitSize::Ratio(ratio), a, b } = &app.ui.dock else { panic!("root not split: {:?}", app.ui.dock) };+ let Some(Node::Split { axis: SplitAxis::Vertical, size: SplitSize::Ratio(ratio), first, second }) = &app.ui.dock.root else {+ panic!("root not split: {:?}", app.ui.dock)+ };assert_eq!(*ratio, 0.75);- assert_eq!(**b, DockNode::Tabs { panels: vec![PanelKind::Program], active: 0 });- assert!(!a.contains(PanelKind::Program) && a.contains(PanelKind::Source) && a.contains(PanelKind::Info));+ assert_eq!(**second, tabs(&[PanelKind::Program], 0));+ let a = root((**first).clone());+ assert!(!a.contains(&PanelKind::Program) && a.contains(&PanelKind::Source) && a.contains(&PanelKind::Info));+ // without an anchor or a side, a docked panel stays where it islet before = app.ui.dock.clone();- assert!(menus::invoke(&mut app, &ctx, "window.dockPanel", json!({"panel": "Info", "zone": "center"})).is_err());+ let _ = menus::invoke(&mut app, &ctx, "window.dockPanel", json!({"panel": "Info", "zone": "center"}));assert_eq!(app.ui.dock, before);- app.ui.dock = DockNode::Tabs { panels: vec![PanelKind::Project], active: 0 };+ app.ui.dock = root(tabs(&[PanelKind::Project], 0));assert!(menus::invoke(&mut app, &ctx, "window.dockPanel", json!({"panel": "Project", "zone": "left"})).is_err());- assert_eq!(app.ui.dock, DockNode::Tabs { panels: vec![PanelKind::Project], active: 0 });+ assert_eq!(app.ui.dock, root(tabs(&[PanelKind::Project], 0)));}-fn same_group(root: &DockNode, first: PanelKind, second: PanelKind) -> bool {- match root {- DockNode::Tabs { panels, .. } => panels.contains(&first) && panels.contains(&second),- DockNode::Split { a, b, .. } => same_group(a, first, second) || same_group(b, first, second),- }+fn same_group(layout: &Layout, first: PanelKind, second: PanelKind) -> bool {+ tabs_containing(layout, first).contains(&second)}-fn tabs_containing(root: &DockNode, panel: PanelKind) -> Vec<PanelKind> {- match root {- DockNode::Tabs { panels, .. } if panels.contains(&panel) => panels.clone(),- DockNode::Split { a, b, .. } => {- let first = tabs_containing(a, panel);- if first.is_empty() { tabs_containing(b, panel) } else { first }+fn tabs_containing(layout: &Layout, panel: PanelKind) -> Vec<PanelKind> {+ fn find(node: &Node<PanelKind>, panel: PanelKind) -> Vec<PanelKind> {+ match node {+ Node::Tabs { panels, .. } if panels.contains(&panel) => panels.clone(),+ Node::Split { first, second, .. } => {+ let found = find(first, panel);+ if found.is_empty() { find(second, panel) } else { found }+ }+ _ => vec![],}- _ => vec![],}+ layout.root.as_ref().map(|node| find(node, panel)).unwrap_or_default()}#[test]fn docking_commands_reject_bad_geometry_and_targets_without_partial_changes() {let mut app = FilmcraftApp::new(Session::default());- app.ui.dock = layout().root;+ app.ui.dock = layout();let ctx = egui::Context::default();let before = app.ui.dock.clone();for (id, params) in [@@ -355,25 +393,20 @@ fn docking_commands_reject_bad_geometry_and_targets_without_partial_changes() {] {assert!(menus::invoke(&mut app, &ctx, id, params.clone()).is_err(), "{id} accepted {params}");assert_eq!(app.ui.dock, before);- assert!(app.ui.floating.is_empty());+ assert!(app.ui.dock.floating.is_empty());}- app.ui.dock = DockNode::Tabs { panels: vec![PanelKind::Project], active: 0 };+ app.ui.dock = root(tabs(&[PanelKind::Project], 0));assert!(menus::invoke(&mut app, &ctx, "window.floatPanel", json!({"panel": "Project", "rect": [1, 2, 300, 200]})).is_err());}fn action_state(h: &Harness<'_, FilmcraftApp>, action: &str) -> serde_json::Value {- json!({"action": action, "dock": h.state().ui.dock, "floating": h.state().ui.floating, "focused": h.state().ui.focused})+ json!({"action": action, "dock": h.state().ui.dock, "floating": h.state().ui.dock.floating, "focused": h.state().ui.focused})}#[test]fn catalog_docking_action_supports_resize_reorder_and_floating_geometry() {let mut app = FilmcraftApp::new(Session::default());- app.ui.dock = DockNode::Split {- vertical: false,- size: SplitSize::FixedA(300.0),- a: Box::new(DockNode::Tabs { panels: vec![PanelKind::Project, PanelKind::Info], active: 1 }),- b: Box::new(DockNode::Tabs { panels: vec![PanelKind::Program], active: 0 }),- };+ app.ui.dock = root(split(false, SplitSize::FixedFirst(300.0), tabs(&[PanelKind::Project, PanelKind::Info], 1), tabs(&[PanelKind::Program], 0)));let ctx = egui::Context::default();for action in [Action::ResizeSplit { path: vec![], size: craft_ui::layout::SplitSize::FixedFirst(360.0) },@@ -383,10 +416,10 @@ fn catalog_docking_action_supports_resize_reorder_and_floating_geometry() {] {filmcraft_ui_egui::menus::invoke(&mut app, &ctx, "window.dockAction", json!({"action": action})).unwrap();}- assert_eq!(app.ui.floating[0].rect, [45.0, 65.0, 330.0, 240.0]);- let DockNode::Split { size, .. } = &app.ui.dock else { panic!("split lost") };- assert_eq!(*size, SplitSize::FixedA(360.0));- let before = json!({"dock": app.ui.dock, "floating": app.ui.floating});+ assert_eq!(app.ui.dock.floating[0].rect, [45.0, 65.0, 330.0, 240.0]);+ let Some(Node::Split { size, .. }) = &app.ui.dock.root else { panic!("split lost") };+ assert_eq!(*size, SplitSize::FixedFirst(360.0));+ let before = json!({"dock": app.ui.dock, "floating": app.ui.dock.floating});assert!(filmcraft_ui_egui::menus::invoke(&mut app,@@ -398,13 +431,13 @@ fn catalog_docking_action_supports_resize_reorder_and_floating_geometry() {).is_err());- assert_eq!(json!({"dock": app.ui.dock, "floating": app.ui.floating}), before);+ assert_eq!(json!({"dock": app.ui.dock, "floating": app.ui.dock.floating}), before);}#[test]fn unreadable_floating_workspace_does_not_erase_valid_workspaces_or_current_name() {- let root = DockNode::Tabs { panels: vec![PanelKind::Project], active: 0 };- let valid = json!({"name": "Valid", "layout": root, "floating": [{+ let tree = json!({"Tabs": {"panels": ["Project"], "active": 0}});+ let valid = json!({"name": "Valid", "layout": tree, "floating": [{"panels": ["TextToSpeech", "Timeline"], "active": 0, "rect": [80, 90, 420, 320]}]});for (index, bad) in [@@ -416,16 +449,16 @@ fn unreadable_floating_workspace_does_not_erase_valid_workspaces_or_current_name.enumerate(){let path = std::env::temp_dir().join(format!("filmcraft-floating-isolation-{}-{index}.json", std::process::id()));- let prefs = json!({"saved": [valid.clone(), {"name": "Broken", "layout": root, "floating": bad}], "current": "Valid"});+ let prefs = json!({"saved": [valid.clone(), {"name": "Broken", "layout": tree, "floating": bad}], "current": "Valid"});std::fs::write(&path, serde_json::to_vec(&prefs).unwrap()).unwrap();let loaded = dock::WorkspacePrefs::load(&path);assert_eq!(loaded.current, "Valid");assert_eq!(loaded.saved.len(), 2);let restored = dock::saved_docking(&loaded, "Valid");restored.validate().unwrap();- assert_eq!(restored.root, root);- assert_eq!(restored.floating[0].panels, vec![PanelKind::TextToSpeech, PanelKind::Timeline]);- assert_eq!(dock::saved_docking(&loaded, "Broken").root, dock::workspace("Broken"));+ assert_eq!(restored.root, Some(tabs(&[PanelKind::Project], 0)));+ assert_eq!(restored.floating[0].panels().copied().collect::<Vec<_>>(), vec![PanelKind::TextToSpeech, PanelKind::Timeline]);+ assert_eq!(dock::saved_docking(&loaded, "Broken"), dock::workspace("Broken"));loaded.save(&path).unwrap();assert_eq!(dock::WorkspacePrefs::load(&path), loaded, "saving preserves the unreadable entry for a future version");std::fs::remove_file(path).unwrap();@@ -455,10 +488,10 @@ fn floating_tts_and_timeline_reveal_keeps_one_owner_and_draft_without_project_ed.unwrap();app.show_panel(PanelKind::TextToSpeech);app.show_panel(PanelKind::Timeline);- assert!(!app.ui.dock.contains(PanelKind::TextToSpeech));- assert!(!app.ui.dock.contains(PanelKind::Timeline));- assert_eq!(app.ui.floating.iter().flat_map(|group| &group.panels).filter(|panel| **panel == PanelKind::TextToSpeech).count(), 1);- assert_eq!(app.ui.floating.iter().flat_map(|group| &group.panels).filter(|panel| **panel == PanelKind::Timeline).count(), 1);+ assert!(!app.ui.dock.docked(PanelKind::TextToSpeech));+ assert!(!app.ui.dock.docked(PanelKind::Timeline));+ assert_eq!(app.ui.dock.floating.iter().flat_map(|group| group.panels()).filter(|panel| **panel == PanelKind::TextToSpeech).count(), 1);+ assert_eq!(app.ui.dock.floating.iter().flat_map(|group| group.panels()).filter(|panel| **panel == PanelKind::Timeline).count(), 1);assert_eq!(serde_json::to_value(&app.ui.tts).unwrap(), draft);assert!(std::sync::Arc::ptr_eq(&project, &app.session.project));assert_eq!(serde_json::to_value(&app.session.state).unwrap(), state);@@ -502,7 +535,7 @@ fn narration_selection_reveals_covered_floating_tts_once_without_editing_the_prostep(&mut h);}}- let layer = |panel: PanelKind| egui::LayerId::new(egui::Order::Middle, egui::Id::new(("floating-panel", panel.id())));+ let layer = |panel: PanelKind| egui::LayerId::new(egui::Order::Middle, egui::Id::new("filmcraft-docking").with(("floating", panel)));let covered = rect(&h, "panel.TextToSpeech").center();assert!(rect(&h, "panel.Info").contains(covered));ctx.move_to_top(layer(PanelKind::Info));@@ -520,8 +553,8 @@ fn narration_selection_reveals_covered_floating_tts_once_without_editing_the_proassert_eq!(draft.loaded_from, Some((clip.id.0, clip.item.0)));assert_eq!(ctx.layer_id_at(covered), Some(layer(PanelKind::TextToSpeech)), "narration selection must bring its floating editor forward");assert_eq!(h.state().ui.focused, PanelKind::TextToSpeech);- assert!(!h.state().ui.dock.contains(PanelKind::TextToSpeech));- assert_eq!(h.state().ui.floating.iter().flat_map(|group| &group.panels).filter(|panel| **panel == PanelKind::TextToSpeech).count(), 1);+ assert!(!h.state().ui.dock.docked(PanelKind::TextToSpeech));+ assert_eq!(h.state().ui.dock.floating.iter().flat_map(|group| group.panels()).filter(|panel| **panel == PanelKind::TextToSpeech).count(), 1);assert!(std::sync::Arc::ptr_eq(&project, &h.state().session.project));// A reveal is one-shot: drawing the selected narration must not steal stacking// from another pane that the user subsequently brings forward.@@ -546,8 +579,8 @@ fn narration_selection_reveals_covered_floating_tts_once_without_editing_the_pro}let saved = dock::SavedWorkspace {name: "Reveal cancellation".into(),- layout: serde_json::to_value(&h.state().ui.dock).unwrap(),- floating: serde_json::to_value(&h.state().ui.floating).unwrap(),+ workspace: serde_json::to_value(dock::Workspace::new(h.state().ui.dock.clone())).unwrap(),+ ..Default::default()};h.state_mut().workspaces.saved.push(saved);h.state_mut().show_panel(PanelKind::TextToSpeech);@@ -567,46 +600,63 @@ fn a_panel_closed_while_floating_reopens_floating_where_it_was() {let mut app = FilmcraftApp::new(Session::default());let ctx = egui::Context::default();menus::invoke(&mut app, &ctx, "window.floatPanel", json!({"panel": "Info", "rect": [45, 65, 420, 320]})).unwrap();- let rect = app.ui.floating.iter().find(|g| g.panels.contains(&PanelKind::Info)).unwrap().rect;+ let rect = app.ui.dock.floating.iter().find(|g| g.contains(&PanelKind::Info)).unwrap().rect;menus::invoke(&mut app, &ctx, "window.closePanel", json!({"panel": "Info"})).unwrap();- assert!(!app.ui.dock.contains(PanelKind::Info) && !app.ui.floating.iter().any(|g| g.panels.contains(&PanelKind::Info)));+ assert!(!app.ui.dock.docked(PanelKind::Info) && !app.ui.dock.floating.iter().any(|g| g.contains(&PanelKind::Info)));menus::invoke(&mut app, &ctx, &menus::panel_command_id(PanelKind::Info), json!({})).unwrap();- let back = app.ui.floating.iter().find(|g| g.panels.contains(&PanelKind::Info)).expect("Info floats again");+ let back = app.ui.dock.floating.iter().find(|g| g.contains(&PanelKind::Info)).expect("Info floats again");assert_eq!(back.rect, rect, "where it was");- assert!(!app.ui.dock.contains(PanelKind::Info));+ assert!(!app.ui.dock.docked(PanelKind::Info));// docked, then closed: it opens dockedmenus::invoke(&mut app, &ctx, "window.dockPanel", json!({"panel": "Info", "anchor": "Project"})).unwrap();menus::invoke(&mut app, &ctx, "window.closePanel", json!({"panel": "Info"})).unwrap();menus::invoke(&mut app, &ctx, &menus::panel_command_id(PanelKind::Info), json!({})).unwrap();- assert!(app.ui.dock.contains(PanelKind::Info));- assert!(!app.ui.floating.iter().any(|g| g.panels.contains(&PanelKind::Info)));+ assert!(app.ui.dock.docked(PanelKind::Info));+ assert!(!app.ui.dock.floating.iter().any(|g| g.contains(&PanelKind::Info)));// the Timeline too, though reopening it first puts it back in its own place in the dockmenus::invoke(&mut app, &ctx, "window.floatPanel", json!({"panel": "Timeline", "rect": [60, 80, 700, 300]})).unwrap();- let rect = app.ui.floating.iter().find(|g| g.panels.contains(&PanelKind::Timeline)).unwrap().rect;+ let rect = app.ui.dock.floating.iter().find(|g| g.contains(&PanelKind::Timeline)).unwrap().rect;menus::invoke(&mut app, &ctx, "window.closePanel", json!({"panel": "Timeline"})).unwrap();menus::invoke(&mut app, &ctx, &menus::panel_command_id(PanelKind::Timeline), json!({})).unwrap();- let back = app.ui.floating.iter().find(|g| g.panels.contains(&PanelKind::Timeline)).expect("the Timeline floats again");+ let back = app.ui.dock.floating.iter().find(|g| g.contains(&PanelKind::Timeline)).expect("the Timeline floats again");assert_eq!(back.rect, rect);- assert!(!app.ui.dock.contains(PanelKind::Timeline));+ assert!(!app.ui.dock.docked(PanelKind::Timeline));// with nothing else docked, a reopened panel has to stay docked (the workspace keeps one// docked panel); its floating place is kept, not lost (#2482 review)let mut app = FilmcraftApp::new(Session::default());menus::invoke(&mut app, &ctx, "window.floatPanel", json!({"panel": "Info", "rect": [45, 65, 420, 320]})).unwrap();- let rect = app.ui.floating.iter().find(|g| g.panels.contains(&PanelKind::Info)).unwrap().rect;+ let rect = app.ui.dock.floating.iter().find(|g| g.contains(&PanelKind::Info)).unwrap().rect;for _ in 0..64 {- let Some(p) = PanelKind::ALL.iter().copied().find(|p| app.ui.dock.contains(*p)) else { break };+ let Some(p) = PanelKind::ALL.iter().copied().find(|p| app.ui.dock.docked(*p)) else { break };if menus::invoke(&mut app, &ctx, "window.closePanel", json!({"panel": p.id()})).is_err() {break;}}- let docked = PanelKind::ALL.iter().filter(|p| app.ui.dock.contains(**p)).count();+ let docked = PanelKind::ALL.iter().filter(|p| app.ui.dock.docked(**p)).count();if docked > 0 {eprintln!("SKIPPED: the dock cannot be emptied ({docked} panels stay)");return;}menus::invoke(&mut app, &ctx, "window.closePanel", json!({"panel": "Info"})).unwrap();menus::invoke(&mut app, &ctx, &menus::panel_command_id(PanelKind::Info), json!({})).unwrap();- assert!(app.ui.dock.contains(PanelKind::Info), "the only panel stays docked");+ assert!(app.ui.dock.docked(PanelKind::Info), "the only panel stays docked");assert!(app.ui.closed_floating.iter().any(|(p, r)| *p == PanelKind::Info && *r == rect), "{:?}", app.ui.closed_floating);}++/// craft-ui's `window.panel.*` commands and FilmCraft's own docking commands share one path.+#[test]+fn shared_dock_commands_and_filmcraft_names_move_panels() {+ let mut app = FilmcraftApp::new(Session::default());+ app.ui.dock = layout();+ let ctx = egui::Context::default();+ menus::invoke(&mut app, &ctx, "window.panel.move", json!({"panel": "Info", "anchor": "Program", "zone": "right"})).unwrap();+ assert!(app.ui.dock.is_visible(PanelKind::Info) && !same_group(&app.ui.dock, PanelKind::Info, PanelKind::Program));+ menus::invoke(&mut app, &ctx, "window.dockPanel", json!({"panel": "Info", "anchor": "Program", "before": "Source"})).unwrap();+ assert_eq!(tabs_containing(&app.ui.dock, PanelKind::Info), vec![PanelKind::Info, PanelKind::Source, PanelKind::Program]);+ menus::invoke(&mut app, &ctx, "window.floatPanel", json!({"panel": "Info"})).unwrap();+ assert!(app.ui.dock.floating.iter().any(|window| window.contains(&PanelKind::Info)));+ menus::invoke(&mut app, &ctx, "window.panel.close", json!({"panel": "Info"})).unwrap();+ assert!(!app.ui.dock.contains(&PanelKind::Info));+ assert!(menus::invoke(&mut app, &ctx, "window.panel.move", json!({"panel": "Info", "anchor": "Nowhere"})).is_err());+}diff --git a/crates/ui-egui/tests/timeline_drop_ui.rs b/crates/ui-egui/tests/timeline_drop_ui.rsindex 5b1940f72..1a5ec11b5 100644--- a/crates/ui-egui/tests/timeline_drop_ui.rs+++ b/crates/ui-egui/tests/timeline_drop_ui.rs@@ -287,7 +287,7 @@ fn offscreen_float_uses_rendered_clamp_and_maximized_timeline_ignores_hidden_flo// The very wide offscreen float is clamped back to x=0, over this row.float_panel(&mut h, "Info", [-5000.0, at.y - 60.0, 1500.0, 200.0]);let visible = control_rect(&h, "panel.Info");- assert!(visible.contains(at), "rendered={visible:?}, drop={at:?}, floats={:?}", h.state().ui.floating);+ assert!(visible.contains(at), "rendered={visible:?}, drop={at:?}, floats={:?}", h.state().ui.dock.floating);assert!(!hover_at(&mut h, at));drop_at(&mut h, at, &still("drop_clamped_occlusion.png"));assert_eq!(clip_counts(&h), (0, 0));@@ -320,7 +320,7 @@ fn os_cursor_hook_selects_destination_when_egui_pointer_has_no_motion() {h.input_mut().dropped_files.clear();step(&mut h);assert_eq!(clip_counts(&h), (0, 0));- h.state_mut().ui.floating.clear();+ h.state_mut().ui.dock.floating.clear();h.input_mut().dropped_files.push(std::sync::Arc::new(OsFile(still("drop_os_hook_visible.png"))));step(&mut h);h.input_mut().dropped_files.clear();diff --git a/crates/ui-egui/tests/ui_control_input.rs b/crates/ui-egui/tests/ui_control_input.rsindex 773b451dd..aa04b8f23 100644--- a/crates/ui-egui/tests/ui_control_input.rs+++ b/crates/ui-egui/tests/ui_control_input.rs@@ -8,11 +8,7 @@ use std::sync::{use egui::{Event, Id, Key, Modifiers, vec2};use egui_kittest::Harness;use filmcraft_engine::Session;-use filmcraft_ui_egui::{- FilmcraftApp,- control::ControlRequest,- dock::{DockNode, PanelKind, SplitSize},-};+use filmcraft_ui_egui::{FilmcraftApp, control::ControlRequest, dock::PanelKind};use serde_json::{Value, json};struct Driver {@@ -99,21 +95,27 @@ fn ordinary_control_input_also_resizes_a_background_divider() {fn background_divider(isolated: bool) {let mut d = Driver::new(isolated);- d.h.state_mut().ui.dock = DockNode::Split {- vertical: false,- size: SplitSize::FixedA(400.0),- a: Box::new(DockNode::Tabs { panels: vec![PanelKind::Project], active: 0 }),- b: Box::new(DockNode::Tabs { panels: vec![PanelKind::Timeline], active: 0 }),+ d.h.state_mut().ui.dock = craft_ui::docking::Layout {+ root: Some(craft_ui::docking::Node::Split {+ axis: craft_ui::layout::SplitAxis::Horizontal,+ size: craft_ui::layout::SplitSize::FixedFirst(400.0),+ first: Box::new(craft_ui::docking::Node::Tabs { panels: vec![PanelKind::Project], active: 0 }),+ second: Box::new(craft_ui::docking::Node::Tabs { panels: vec![PanelKind::Timeline], active: 0 }),+ }),+ floating: vec![],};d.frames(3, true);let before_project = d.h.state().session.project.clone();let before_playheads = d.h.state().session.state.playheads.clone();- let divider = Id::new(("dock-gutter", String::new()));+ let divider = Id::new("filmcraft-docking").with(("split", &Vec::<bool>::new()));d.h.ctx.memory_mut(|memory| memory.request_focus(divider));d.frames(2, true);d.h.input_mut().events.push(Event::WindowFocused(false));d.ok("ui.key", json!({"key":"ArrowRight"}), false);- assert!(matches!(d.h.state().ui.dock, DockNode::Split { size: SplitSize::FixedA(408.0), .. }), "control input must work without native activation");+ assert!(+ matches!(d.h.state().ui.dock.root, Some(craft_ui::docking::Node::Split { size: craft_ui::layout::SplitSize::FixedFirst(408.0), .. })),+ "control input must work without native activation"+ );assert_eq!(d.h.state().session.state.playheads, before_playheads);assert!(Arc::ptr_eq(&d.h.state().session.project, &before_project));assert!(!d.h.state().playback.playing);diff --git a/crates/ui-egui/tests/ui_dock_resize.rs b/crates/ui-egui/tests/ui_dock_resize.rsindex 2057ce262..00e3a8379 100644--- a/crates/ui-egui/tests/ui_dock_resize.rs+++ b/crates/ui-egui/tests/ui_dock_resize.rs@@ -4,7 +4,7 @@ use egui::{Event, Id, Key, Modifiers, PointerButton, Rect, pos2, vec2};use egui_kittest::Harness;use filmcraft_engine::Session;use filmcraft_ui_egui::FilmcraftApp;-use filmcraft_ui_egui::dock::{DockNode, PanelKind, SplitSize};+use filmcraft_ui_egui::dock::PanelKind;use filmcraft_ui_egui::theme::ThemeKind;use serde_json::json;@@ -34,8 +34,8 @@ fn snapshots(h: &mut Harness<'_, FilmcraftApp>, directory: Option<&std::path::Pa}fn first_size(h: &Harness<'_, FilmcraftApp>) -> f32 {- match h.state().ui.dock {- DockNode::Split { size: SplitSize::FixedA(value), .. } => value,+ match h.state().ui.dock.root {+ Some(craft_ui::docking::Node::Split { size: craft_ui::layout::SplitSize::FixedFirst(value), .. }) => value,ref other => panic!("fixed-size mode changed: {other:?}"),}}@@ -55,16 +55,19 @@ fn focused_dock_resize_owns_arrows_and_keeps_pointer_dragging() {frames(&mut h, 4);snapshots(&mut h, directory.as_deref(), "workspace");h.state_mut().ui.focused = PanelKind::Timeline;- h.state_mut().ui.dock = DockNode::Split {- vertical: false,- size: SplitSize::FixedA(400.0),- a: Box::new(DockNode::Tabs { panels: vec![PanelKind::Project], active: 0 }),- b: Box::new(DockNode::Tabs { panels: vec![PanelKind::Timeline], active: 0 }),+ h.state_mut().ui.dock = craft_ui::docking::Layout {+ root: Some(craft_ui::docking::Node::Split {+ axis: craft_ui::layout::SplitAxis::Horizontal,+ size: craft_ui::layout::SplitSize::FixedFirst(400.0),+ first: Box::new(craft_ui::docking::Node::Tabs { panels: vec![PanelKind::Project], active: 0 }),+ second: Box::new(craft_ui::docking::Node::Tabs { panels: vec![PanelKind::Timeline], active: 0 }),+ }),+ floating: vec![],};frames(&mut h, 3);let before_project = h.state().session.project.clone();let before_playheads = h.state().session.state.playheads.clone();- let id = Id::new(("dock-gutter", String::new()));+ let id = Id::new("filmcraft-docking").with(("split", &Vec::<bool>::new()));h.ctx.memory_mut(|memory| memory.request_focus(id));frames(&mut h, 2);assert_eq!(h.ctx.memory(|memory| memory.focused()), Some(id));@@ -110,11 +113,14 @@ fn space_plays_after_a_pane_is_resized_with_the_pointer() {let mut h = Harness::builder().with_size(vec2(1400.0, 900.0)).build_eframe(move |_| app);frames(&mut h, 4);h.state_mut().ui.focused = PanelKind::Timeline;- h.state_mut().ui.dock = DockNode::Split {- vertical: false,- size: SplitSize::FixedA(400.0),- a: Box::new(DockNode::Tabs { panels: vec![PanelKind::Project], active: 0 }),- b: Box::new(DockNode::Tabs { panels: vec![PanelKind::Timeline], active: 0 }),+ h.state_mut().ui.dock = craft_ui::docking::Layout {+ root: Some(craft_ui::docking::Node::Split {+ axis: craft_ui::layout::SplitAxis::Horizontal,+ size: craft_ui::layout::SplitSize::FixedFirst(400.0),+ first: Box::new(craft_ui::docking::Node::Tabs { panels: vec![PanelKind::Project], active: 0 }),+ second: Box::new(craft_ui::docking::Node::Tabs { panels: vec![PanelKind::Timeline], active: 0 }),+ }),+ floating: vec![],};frames(&mut h, 3);let element = h.state().auto.find("dock.gutter.").unwrap();@@ -131,7 +137,7 @@ fn space_plays_after_a_pane_is_resized_with_the_pointer() {frames(&mut h, 3);assert_eq!(first_size(&h), 420.0);// The divider keeps keyboard focus so arrows can nudge it; that must not cost the editor its shortcuts.- assert_eq!(h.ctx.memory(|memory| memory.focused()), Some(Id::new(("dock-gutter", String::new()))));+ assert_eq!(h.ctx.memory(|memory| memory.focused()), Some(Id::new("filmcraft-docking").with(("split", &Vec::<bool>::new()))));press(&mut h, Key::Space);assert!(h.state().playback.playing, "Space must start playback after resizing a pane (#1482)");press(&mut h, Key::Space);diff --git a/crates/ui-egui/tests/ui_keyboard_focus.rs b/crates/ui-egui/tests/ui_keyboard_focus.rsindex 8685d4933..02d48ba9a 100644--- a/crates/ui-egui/tests/ui_keyboard_focus.rs+++ b/crates/ui-egui/tests/ui_keyboard_focus.rs@@ -5,11 +5,7 @@ use std::sync::Arc;use egui::{Event, Id, Key, Modifiers, vec2};use egui_kittest::Harness;use filmcraft_engine::Session;-use filmcraft_ui_egui::{- FilmcraftApp,- dock::{DockNode, PanelKind},- state::Tool,-};+use filmcraft_ui_egui::{FilmcraftApp, dock::PanelKind, state::Tool};use serde_json::json;fn key(h: &mut Harness<'_, FilmcraftApp>, key: Key, modifiers: Modifiers) {@@ -30,7 +26,8 @@ fn tab_traversal_and_space_select_only_the_focused_tool_with_visible_focus() {let app = FilmcraftApp::new(session);let mut h = Harness::builder().with_size(vec2(1200.0, 800.0)).build_eframe(move |_| app);h.run_steps(4);- h.state_mut().ui.dock = DockNode::Tabs { panels: vec![PanelKind::Tools], active: 0 };+ h.state_mut().ui.dock =+ craft_ui::docking::Layout { root: Some(craft_ui::docking::Node::Tabs { panels: vec![PanelKind::Tools], active: 0 }), floating: vec![] };h.run_steps(3);let first = Id::new(("tool", "Selection".to_string()));let second = Id::new(("tool", "TrackSelectForward".to_string()));@@ -74,10 +71,13 @@ fn dock_tab_traversal_and_enter_change_the_visible_panel_without_editing() {h.run_steps(4);h.state_mut().ui.show_header = false;h.state_mut().ui.show_status_bar = false;- h.state_mut().ui.dock = DockNode::Tabs { panels: vec![PanelKind::Project, PanelKind::Effects], active: 0 };+ h.state_mut().ui.dock = craft_ui::docking::Layout {+ root: Some(craft_ui::docking::Node::Tabs { panels: vec![PanelKind::Project, PanelKind::Effects], active: 0 }),+ floating: vec![],+ };h.run_steps(3);- let first = Id::new(("tab", String::new(), 0usize));- let second = Id::new(("tab", String::new(), 1usize));+ let first = Id::new("filmcraft-docking").with(("tab", PanelKind::Project));+ let second = Id::new("filmcraft-docking").with(("tab", PanelKind::Effects));for _ in 0..128 {key(&mut h, Key::Tab, Modifiers::NONE);if h.ctx.memory(|m| m.focused()) == Some(second) {@@ -85,7 +85,7 @@ fn dock_tab_traversal_and_enter_change_the_visible_panel_without_editing() {}}assert_eq!(h.ctx.memory(|m| m.focused()), Some(second));- assert!(matches!(h.state().ui.dock, DockNode::Tabs { active: 0, .. }));+ assert!(matches!(h.state().ui.dock.root, Some(craft_ui::docking::Node::Tabs { active: 0, .. })));let response = h.ctx.read_response(second).unwrap();assert!(h.output().shapes.iter().any(|shape| matches!(&shape.shape,@@ -94,12 +94,12 @@ fn dock_tab_traversal_and_enter_change_the_visible_panel_without_editing() {"the focused dock tab needs a visible focus outline");key(&mut h, Key::Space, Modifiers::NONE);- assert!(matches!(h.state().ui.dock, DockNode::Tabs { active: 1, .. }));+ assert!(matches!(h.state().ui.dock.root, Some(craft_ui::docking::Node::Tabs { active: 1, .. })));assert_eq!(h.state().ui.focused, PanelKind::Effects);key(&mut h, Key::Tab, Modifiers::SHIFT);assert_eq!(h.ctx.memory(|m| m.focused()), Some(first));key(&mut h, Key::Enter, Modifiers::NONE);- assert!(matches!(h.state().ui.dock, DockNode::Tabs { active: 0, .. }));+ assert!(matches!(h.state().ui.dock.root, Some(craft_ui::docking::Node::Tabs { active: 0, .. })));assert_eq!(h.state().ui.focused, PanelKind::Project);assert!(Arc::ptr_eq(&h.state().session.project, &project));assert_eq!(h.state().session.state.playheads, playheads);diff --git a/crates/ui-egui/tests/workspaces_ui.rs b/crates/ui-egui/tests/workspaces_ui.rsindex a5e4d8d9a..16d554037 100644--- a/crates/ui-egui/tests/workspaces_ui.rs+++ b/crates/ui-egui/tests/workspaces_ui.rs@@ -106,7 +106,7 @@ impl Driver {}fn shows(&mut self, p: PanelKind) -> bool {- self.app().ui.dock.contains(p)+ self.app().ui.dock.contains(&p)}/// Window ▸ Workspaces as (label, checked) in menu order.