FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
UI.9: use craft-ui's tab wheel, middle click, edge dock and widget ids
aiongg8466f6d8e001
diff --git a/Cargo.lock b/Cargo.lockindex e2eb13f25..1fedda6ef 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=787b70627461a3c988157ed776e8f6051cbc94c3#787b70627461a3c988157ed776e8f6051cbc94c3"+source = "git+https://github.com/storytold/craft-libs?rev=3600104e7632336be5312b6e6f62b5acf2ea37e7#3600104e7632336be5312b6e6f62b5acf2ea37e7"dependencies = ["egui","serde",diff --git a/Cargo.toml b/Cargo.tomlindex dfa2509bb..aea89196d 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 = "787b70627461a3c988157ed776e8f6051cbc94c3", features = ["serde"] }+craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3600104e7632336be5312b6e6f62b5acf2ea37e7", features = ["serde"] }egui = "0.36"eframe = { version = "0.36", default-features = false }egui_kittest = "0.36"diff --git a/crates/ui-egui/src/dock_ui.rs b/crates/ui-egui/src/dock_ui.rsindex 3327ba4f9..50d39d17b 100644--- a/crates/ui-egui/src/dock_ui.rs+++ b/crates/ui-egui/src/dock_ui.rs@@ -3,9 +3,7 @@//! 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, Divider, DockArea, DockCommand, DockContent, DockEvent, DockStyle, FloatSpace, Hit, Layout, Placement, Profile, ResizeEdge, Workspace, Zone,-};+use craft_ui::docking::{Action, Divider, DockArea, DockCommand, DockContent, DockEvent, DockStyle, FloatSpace, Hit, Layout, Profile, ResizeEdge, Workspace};use egui::{Rect, Sense, Stroke, StrokeKind, vec2};use serde_json::{Value, json};@@ -83,25 +81,11 @@ fn alias(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, params: &Value)}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) }})- }- }- }+ None => match zone.to_ascii_lowercase().as_str() {+ "center" | "tab" => json!({"command": "window.panel.dock", "panel": panel}),+ edge @ ("left" | "right" | "top" | "bottom") => json!({"command": "window.panel.dock", "panel": panel, "zone": edge}),+ _ => return Err("unknown docking zone".into()),+ },}}};@@ -191,8 +175,7 @@ impl FilmcraftApp {let layers = ctx.memory(|memory| memory.layer_ids().collect::<Vec<_>>());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)));+ let Some(layer) = DockArea::floating_layer(area_id(), window) else { return false };layer != *timeline && rank(&layer) > rank(timeline) && ctx.memory(|memory| memory.area_rect(layer.id)).is_some_and(|rect| rect.contains(pos))})}@@ -240,7 +223,15 @@ impl FilmcraftApp {panels::keyboard::toggle_maximize(self, panel);}}+ let middle_click = ctx.input(|input| input.pointer.button_clicked(egui::PointerButton::Middle));for action in output.actions {+ // A middle click on the Timeline's tab closes its active sequence; the panel stays.+ if middle_click && action == (Action::Close { panel: PanelKind::Timeline }) && self.session.state.active_sequence.is_some() {+ if let Err(error) = self.session.execute("sequence.close", json!({})) {+ self.ui.status = error.to_string();+ }+ continue;+ }if let Err(error) = self.dock_command(&ctx, action) {self.ui.status = error;}@@ -280,7 +271,6 @@ impl FilmcraftApp {});}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());@@ -310,69 +300,20 @@ impl FilmcraftApp {}_ => continue,};- found.push((entry, *rect));+ found.push((entry, *rect, DockArea::hit_id(area_id(), hit)));}- for ((id, label), rect) in found {+ // The widget id lets keyboard focus on a divider or grip map to its element (shortcuts+ // stay live while one is focused).+ for ((id, label), rect, widget) in found {self.auto.add(&id, rect, label);- }- }-}--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))- }- _ => 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 Err(error) = result {- self.ui.status = error;+ if let Some(element) = self.auto.elements.last_mut() {+ element.widget_id = Some(format!("{:016x}", widget.value()));+ element.response_id = Some(widget);}- 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;}}}-/// 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,- }- }- 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 dock_style(ui: &egui::Ui, t: &Tokens) -> DockStyle {let mut style = DockStyle::from_ui(ui);style.profile = Profile::Frame;@@ -426,20 +367,16 @@ impl DockContent<PanelKind> for FilmContent<'_> {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 sequence tabs take at most two thirds of the strip, so the group's own tabs keep room;+ /// past that they scroll into their » list.+ fn group_header_width(&self, _panels: &[PanelKind], active: &PanelKind, _floating: bool, strip_width: f32) -> f32 {+ if *active == PanelKind::Timeline && !self.seqs.open.is_empty() { (self.seq_width + MENU_W).min(strip_width * 2.0 / 3.0).max(MENU_W) } else { MENU_W }}/// The ≡ panel menu of the group's shown panel; for the Timeline, its sequence tabs first.diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 2db18de6f..f194d7d63 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -38,6 +38,7 @@ pub mod crash;pub mod credits;pub mod dock;mod dock_ui;+pub use dock_ui::area_id as dock_area_id;/// Thumbnail textures kept before the least recently used are freed (each is up to 320 px wide).const MAX_THUMB_TEXTURES: usize = 512;diff --git a/crates/ui-egui/tests/shared_docking_ui.rs b/crates/ui-egui/tests/shared_docking_ui.rsindex 95ce475ec..39af6d24e 100644--- a/crates/ui-egui/tests/shared_docking_ui.rs+++ b/crates/ui-egui/tests/shared_docking_ui.rs@@ -1,6 +1,6 @@//! Shared docking preserves FilmCraft document state and legacy workspace files.-use craft_ui::docking::{Action, Node, Placement, Zone};+use craft_ui::docking::{Action, DockArea, Hit, Node, Placement, ResizeEdge, Zone};use craft_ui::layout::{SplitAxis, SplitSize};use egui::{Event, Modifiers, PointerButton, Rect, pos2, vec2};use egui_kittest::Harness;@@ -241,9 +241,7 @@ fn real_panel_drag_merges_splits_floats_and_redocks_without_editing_documents()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("filmcraft-docking").with(("floating", PanelKind::Info)).with("resize");- h.ctx.memory_mut(|memory| memory.request_focus(grip_id));- step(&mut h);+ let grip_id = DockArea::<PanelKind>::hit_id(filmcraft_ui_egui::dock_area_id(), &Hit::Resize(PanelKind::Info, ResizeEdge::BottomRight));assert_eq!(h.ctx.memory(|memory| memory.focused()), Some(grip_id));let before_keys = h.state().ui.dock.floating[0].rect;for key in [egui::Key::ArrowRight, egui::Key::ArrowDown] {@@ -535,14 +533,13 @@ 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("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));+ ctx.move_to_top(window_layer(&h, PanelKind::Info));for _ in 0..3 {step(&mut h);}- assert_eq!(ctx.layer_id_at(covered), Some(layer(PanelKind::Info)), "precondition: Info really covers TTS");+ assert_eq!(ctx.layer_id_at(covered), Some(window_layer(&h, PanelKind::Info)), "precondition: Info really covers TTS");h.state_mut().session.state.selection = vec![clip.id];for _ in 0..4 {step(&mut h);@@ -551,29 +548,29 @@ fn narration_selection_reveals_covered_floating_tts_once_without_editing_the_proassert_eq!(draft.text, narration.text);assert_eq!(draft.pace, narration.pace);assert_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!(ctx.layer_id_at(covered), Some(window_layer(&h, PanelKind::TextToSpeech)), "narration selection must bring its floating editor forward");assert_eq!(h.state().ui.focused, PanelKind::TextToSpeech);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.- ctx.move_to_top(layer(PanelKind::Info));+ ctx.move_to_top(window_layer(&h, PanelKind::Info));for _ in 0..4 {step(&mut h);}- assert_eq!(ctx.layer_id_at(covered), Some(layer(PanelKind::Info)));+ assert_eq!(ctx.layer_id_at(covered), Some(window_layer(&h, PanelKind::Info)));assert_eq!(h.state().ui.tts, draft);menus::invoke(h.state_mut(), &ctx, "window.panel.TextToSpeech", json!({})).unwrap();for _ in 0..4 {step(&mut h);}- assert_eq!(ctx.layer_id_at(covered), Some(layer(PanelKind::TextToSpeech)));+ assert_eq!(ctx.layer_id_at(covered), Some(window_layer(&h, PanelKind::TextToSpeech)));assert_eq!(h.state().ui.tts, draft);assert!(std::sync::Arc::ptr_eq(&project, &h.state().session.project));// Replacing the workspace cancels a queued reveal before the next render,// even when the destination happens to contain the same floating panel IDs.- ctx.move_to_top(layer(PanelKind::Info));+ ctx.move_to_top(window_layer(&h, PanelKind::Info));for _ in 0..3 {step(&mut h);}@@ -588,7 +585,7 @@ fn narration_selection_reveals_covered_floating_tts_once_without_editing_the_profor _ in 0..4 {step(&mut h);}- assert_eq!(ctx.layer_id_at(covered), Some(layer(PanelKind::Info)));+ assert_eq!(ctx.layer_id_at(covered), Some(window_layer(&h, PanelKind::Info)));assert_eq!(h.state().ui.tts, draft);assert!(std::sync::Arc::ptr_eq(&project, &h.state().session.project));}@@ -660,3 +657,9 @@ fn shared_dock_commands_and_filmcraft_names_move_panels() {assert!(!app.ui.dock.contains(&PanelKind::Info));assert!(menus::invoke(&mut app, &ctx, "window.panel.move", json!({"panel": "Info", "anchor": "Nowhere"})).is_err());}++/// The layer of the floating window holding `panel`.+fn window_layer(h: &Harness<'_, FilmcraftApp>, panel: PanelKind) -> egui::LayerId {+ let window = h.state().ui.dock.floating.iter().find(|window| window.contains(&panel)).unwrap();+ DockArea::floating_layer(filmcraft_ui_egui::dock_area_id(), window).unwrap()+}diff --git a/crates/ui-egui/tests/ui_control_input.rs b/crates/ui-egui/tests/ui_control_input.rsindex aa04b8f23..19851a7da 100644--- a/crates/ui-egui/tests/ui_control_input.rs+++ b/crates/ui-egui/tests/ui_control_input.rs@@ -5,7 +5,7 @@ use std::sync::{mpsc::{Sender, channel},};-use egui::{Event, Id, Key, Modifiers, vec2};+use egui::{Event, Key, Modifiers, vec2};use egui_kittest::Harness;use filmcraft_engine::Session;use filmcraft_ui_egui::{FilmcraftApp, control::ControlRequest, dock::PanelKind};@@ -107,7 +107,10 @@ fn background_divider(isolated: bool) {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("filmcraft-docking").with(("split", &Vec::<bool>::new()));+ let divider = craft_ui::docking::DockArea::<PanelKind>::hit_id(+ filmcraft_ui_egui::dock_area_id(),+ &craft_ui::docking::Hit::Divider(craft_ui::docking::Divider::Split(vec![])),+ );d.h.ctx.memory_mut(|memory| memory.request_focus(divider));d.frames(2, true);d.h.input_mut().events.push(Event::WindowFocused(false));diff --git a/crates/ui-egui/tests/ui_dock_resize.rs b/crates/ui-egui/tests/ui_dock_resize.rsindex e61a8f7a2..fd5ecb774 100644--- a/crates/ui-egui/tests/ui_dock_resize.rs+++ b/crates/ui-egui/tests/ui_dock_resize.rs@@ -1,6 +1,6 @@//! Shared pane resizing in the full application, including application shortcut ownership.-use egui::{Event, Id, Key, Modifiers, PointerButton, Rect, pos2, vec2};+use egui::{Event, Key, Modifiers, PointerButton, Rect, pos2, vec2};use egui_kittest::Harness;use filmcraft_engine::Session;use filmcraft_ui_egui::FilmcraftApp;@@ -67,7 +67,10 @@ fn focused_dock_resize_owns_arrows_and_keeps_pointer_dragging() {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("filmcraft-docking").with(("split", &Vec::<bool>::new()));+ let id = craft_ui::docking::DockArea::<PanelKind>::hit_id(+ filmcraft_ui_egui::dock_area_id(),+ &craft_ui::docking::Hit::Divider(craft_ui::docking::Divider::Split(vec![])),+ );h.ctx.memory_mut(|memory| memory.request_focus(id));frames(&mut h, 2);assert_eq!(h.ctx.memory(|memory| memory.focused()), Some(id));@@ -136,7 +139,14 @@ fn space_plays_after_a_pane_is_resized_with_the_pointer() {h.event(Event::PointerButton { pos: from + vec2(20.0, 0.0), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });frames(&mut h, 3);assert_eq!(first_size(&h), 420.0);- // Resizing a pane must not cost the editor its shortcuts.+ // 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(craft_ui::docking::DockArea::<PanelKind>::hit_id(+ filmcraft_ui_egui::dock_area_id(),+ &craft_ui::docking::Hit::Divider(craft_ui::docking::Divider::Split(vec![]))+ ))+ );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 02d48ba9a..9489ceda7 100644--- a/crates/ui-egui/tests/ui_keyboard_focus.rs+++ b/crates/ui-egui/tests/ui_keyboard_focus.rs@@ -76,8 +76,8 @@ fn dock_tab_traversal_and_enter_change_the_visible_panel_without_editing() {floating: vec![],};h.run_steps(3);- let first = Id::new("filmcraft-docking").with(("tab", PanelKind::Project));- let second = Id::new("filmcraft-docking").with(("tab", PanelKind::Effects));+ let first = craft_ui::docking::DockArea::<PanelKind>::hit_id(filmcraft_ui_egui::dock_area_id(), &craft_ui::docking::Hit::Tab(PanelKind::Project));+ let second = craft_ui::docking::DockArea::<PanelKind>::hit_id(filmcraft_ui_egui::dock_area_id(), &craft_ui::docking::Hit::Tab(PanelKind::Effects));for _ in 0..128 {key(&mut h, Key::Tab, Modifiers::NONE);if h.ctx.memory(|m| m.focused()) == Some(second) {