Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

Merge #3249 (egui 0.37) into docking-frame-trial

aiongg75e89dffff8e
diff --cc Cargo.lock
index a9f6190ca,34d78aad8..74321a89e
--- a/Cargo.lock
+++ b/Cargo.lock
@@@ -1014,12 -1010,12 +1010,12 @@@ dependencies =
[[package]]
name = "craft-docpath"
version = "0.1.0"
- source = "git+https://github.com/storytold/craft-libs?rev=5bbe9f6254de3bb9f9707ae0740ab0db8170afd5#5bbe9f6254de3bb9f9707ae0740ab0db8170afd5"
-source = "git+https://github.com/storytold/craft-libs?rev=82a24b006eefa036b43c09a67fb9a3fbd17ffe63#82a24b006eefa036b43c09a67fb9a3fbd17ffe63"
++source = "git+https://github.com/storytold/craft-libs?rev=a0916808f7d78bed8c7b90cdf937176015454a7f#a0916808f7d78bed8c7b90cdf937176015454a7f"
[[package]]
name = "craft-media"
version = "0.1.0"
- source = "git+https://github.com/storytold/craft-libs?rev=5bbe9f6254de3bb9f9707ae0740ab0db8170afd5#5bbe9f6254de3bb9f9707ae0740ab0db8170afd5"
-source = "git+https://github.com/storytold/craft-libs?rev=f0ad6c1e1d297908915f4be315b0fcfc9be7b5d4#f0ad6c1e1d297908915f4be315b0fcfc9be7b5d4"
++source = "git+https://github.com/storytold/craft-libs?rev=a0916808f7d78bed8c7b90cdf937176015454a7f#a0916808f7d78bed8c7b90cdf937176015454a7f"
dependencies = [
"thiserror 2.0.21",
]
@@@ -1027,13 -1023,9 +1023,13 @@@
[[package]]
name = "craft-ui"
version = "0.1.0"
- source = "git+https://github.com/storytold/craft-libs?rev=5bbe9f6254de3bb9f9707ae0740ab0db8170afd5#5bbe9f6254de3bb9f9707ae0740ab0db8170afd5"
-source = "git+https://github.com/storytold/craft-libs?rev=25da1314d443171b4adeaad2cd9454b273f35c6f#25da1314d443171b4adeaad2cd9454b273f35c6f"
++source = "git+https://github.com/storytold/craft-libs?rev=a0916808f7d78bed8c7b90cdf937176015454a7f#a0916808f7d78bed8c7b90cdf937176015454a7f"
dependencies = [
"egui",
+ "log",
+ "objc2 0.6.4",
+ "objc2-app-kit 0.3.2",
+ "objc2-foundation 0.3.2",
"serde",
]
diff --cc Cargo.toml
index 1de2139e4,fa7e1a71d..afaaf5401
--- a/Cargo.toml
+++ b/Cargo.toml
@@@ -72,15 -72,18 +72,18 @@@ chrono = { version = "0.4.45", default-
rayon = "1"
proptest = "1"
roxmltree = "0.21"
- craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5bbe9f6254de3bb9f9707ae0740ab0db8170afd5" }
- craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5bbe9f6254de3bb9f9707ae0740ab0db8170afd5", default-features = false }
-craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "82a24b006eefa036b43c09a67fb9a3fbd17ffe63" }
-craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "f0ad6c1e1d297908915f4be315b0fcfc9be7b5d4", default-features = false }
++craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a0916808f7d78bed8c7b90cdf937176015454a7f" }
++craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a0916808f7d78bed8c7b90cdf937176015454a7f", default-features = false }
# 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 = "5bbe9f6254de3bb9f9707ae0740ab0db8170afd5", features = ["serde", "native-windows"] }
- egui = "0.36"
- eframe = { version = "0.36", default-features = false }
- egui_kittest = "0.36"
-craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "25da1314d443171b4adeaad2cd9454b273f35c6f", features = ["serde"] }
++craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a0916808f7d78bed8c7b90cdf937176015454a7f", features = ["serde", "native-windows"] }
+ # egui 0.37: bundled fonts are opt-in, and the monochrome symbol/emoji faces moved to their own
+ # feature. FilmCraft paints ✔ ✓ ✖ ⚡ ⚠ ⚙ ♪ ☑ in panel chrome, so both features are part of the
+ # production font policy (system_fonts stays off).
+ egui = { version = "0.37", features = ["default_fonts", "monochrome_emoji_fonts"] }
+ eframe = { version = "0.37", default-features = false }
+ egui_kittest = "0.37"
rfd = "0.17"
[workspace.lints.rust]
diff --cc crates/ui-egui/src/automation.rs
index 474a86c96,b7e086130..70adc7637
--- a/crates/ui-egui/src/automation.rs
+++ b/crates/ui-egui/src/automation.rs
@@@ -61,7 -42,10 +61,10 @@@ impl Registry
}
/// Observe the widget without changing its accessibility role or input behavior.
pub fn add_response(&mut self, id: &str, response: &egui::Response, label: &str) {
+ // The automation label is also the name a screen reader and kittest use. Keep an
+ // existing visible label/placeholder; this only fills a missing name.
+ crate::widgets::accessible_name(response.clone(), label);
- self.add(id, response.rect, label);
+ self.add_in(response.ctx.viewport_id(), id, response.rect, label);
if let Some(element) = self.elements.last_mut() {
element.widget_id = Some(format!("{:016x}", response.id.value()));
element.enabled = Some(response.enabled());
diff --cc crates/ui-egui/src/dock.rs
index 9a245dda3,cd302674d..5c94516fd
--- a/crates/ui-egui/src/dock.rs
+++ b/crates/ui-egui/src/dock.rs
@@@ -563,228 -435,458 +563,228 @@@ impl LayoutExt for Layout
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)
- }
- pub fn validate(&self) -> Result<(), String> {
- crate::dock_shared::encode(&self.root, &self.floating)?.validate().map_err(|error| error.to_string())
+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 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);
- }
+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()
}
-/// 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);
+/// 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
}
-/// Recursively lay out tabs and splits with path-based automation ids, emitting gutter resize actions; groups are appended in traversal order.
-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::unique(("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);
- response.response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Splitter, response.response.enabled(), label));
- 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 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 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 list_id = egui::Id::unique("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"));
++ let resp = ui.interact(r, egui::Id::unique("timeline-tab-overflow"), Sense::click());
++ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::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;
}
}
-}
-
-/// 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
-}
-
-#[derive(Default)]
-pub struct Chrome {
- pub actions: Vec<DockAction>,
- pub tabs: Vec<(PanelKind, Rect)>,
-}
-
-/// Draw a group's frame and tab strip, register panel/tab automation ids and return its dock actions; a compact single panel gets an 8 pt grip header.
-pub fn draw_group_chrome_details(ui: &mut egui::Ui, g: &Group, seqs: &SeqTabs, t: &Tokens, reg: &mut crate::automation::Registry) -> Chrome {
- 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::unique(("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));
- }
- }
- 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");
++ let wheel_id = egui::Id::unique("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));
++ let resp = ui.interact(tab_rect, egui::Id::unique(("tab-seq", *id)), Sense::click_and_drag());
++ resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Tab, 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;
- }
- let mut last = active_at.max(first);
- while last + 1 < tabs.len() && span(first, last + 1) <= room {
- last += 1;
- }
- let list_id = egui::Id::unique(("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::unique(("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::Role::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;
- }
+ // 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));
++ let home = egui::Id::unique(("tab-seq-home", *id));
+ if resp.drag_started() {
+ ui.data_mut(|d| d.insert_temp(home, i));
}
- // 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::unique(("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));
- }
- 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::unique(("tab-seq", g.path.clone(), id)), Sense::click_and_drag()),
- None => ui.interact(tab_rect, egui::Id::unique(("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::Role::Tab, 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::unique(("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::unique(("tab-close", g.path.clone(), id)), Sense::click());
- cresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::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::unique(("tab-menu", g.path.clone())), Sense::click());
- mresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::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;
- }
- // 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)
+ 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))
{
- 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));
+ actions.push(SeqAction::Move(*id, at));
+ }
+ 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"));
++ let cresp = ui.interact(cr.expand(4.0), egui::Id::unique(("tab-close", *id)), Sense::click());
++ cresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::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));
+ }
+ if (resp.clicked() || resp.drag_started()) && !closed && !is_active {
+ actions.push(SeqAction::Open(*id));
+ }
+ if resp.middle_clicked() {
+ actions.push(SeqAction::Close(*id));
+ }
+ if resp.secondary_clicked() {
+ actions.push(SeqAction::Menu(*id, resp.interact_pointer_pos().unwrap_or(tab_rect.left_bottom())));
+ }
+ 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 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);
- }
+ }
+ // 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 }
-}
-
-/// 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);
- }
+ actions
}
-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);
}
diff --cc crates/ui-egui/src/dock_ui.rs
index 55cef1dbf,3d5761a13..82291617f
--- a/crates/ui-egui/src/dock_ui.rs
+++ b/crates/ui-egui/src/dock_ui.rs
@@@ -1,35 -1,27 +1,35 @@@
-//! FilmCraft's panel chrome and document tabs over the shared docking transactions.
+//! FilmCraft's panels in craft-ui's shared docking. craft-ui draws the frames, tab strips,
+//! floating windows and drag previews and owns the gestures; FilmCraft draws the panel
+//! bodies, the ≡ panel menu, the panel items of each tab's context 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 std::collections::HashMap;
+
+use craft_ui::docking::{
+ Action, Divider, DockArea, DockCommand, DockContent, DockEvent, DockStyle, FloatSpace, Hit, Layout, ResizeEdge, WindowKind, Workspace,
+};
+use egui::{Rect, Sense, Stroke, StrokeKind, vec2};
use serde_json::{Value, json};
-use crate::dock::{self, DockAction, DockNode, Group, PanelKind};
+use crate::dock::{self, LayoutExt as _, 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")
++ egui::Id::unique("filmcraft-docking")
}
-/// The single stable id holding an in-flight docked-panel drag across frames.
-fn drag_id() -> egui::Id {
- egui::Id::unique("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((|| {
@@@ -232,329 -224,256 +232,328 @@@ 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);
+ // No `monitors`: the monitor list comes with the egui fork's `ViewportInfo::monitors`.
+ let control_input_only = self.control_input_only;
+ let armed = std::sync::Arc::clone(&self.native_ctrl_click_armed);
+ let mut area = DockArea::new(area_id())
+ .float_bounds(self.float_bounds(&ctx))
+ .maximized(self.ui.keys.maximized.filter(|panel| self.ui.dock.is_docked(*panel)))
+ .input_blocked(self.modal_open(&ctx))
+ .native_input_hook(move |_ctx, raw_input| crate::rewrite_native_window_input(control_input_only, &armed, raw_input));
+ 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);
+ // Known before anything draws, so header elements of a native window (the ≡ menu, the
+ // Timeline's sequence tabs), drawn before its bodies, carry that window too.
+ self.auto.windows =
+ self.ui.dock.floating.iter().enumerate().map(|(index, window)| (DockArea::<PanelKind>::window_viewport(area_id(), window.id), index)).collect();
+ let mut content =
+ FilmContent { app: self, seqs, seq_width, tokens: t, seq_actions: Vec::new(), menu: None, bodies: Vec::new(), restore_workspace: false };
+ let output = area.show_content(&mut child, &layout, &style, &mut content);
+ let FilmContent { seq_actions, mut menu, bodies, restore_workspace, .. } = 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);
- }
+ self.handle_forwarded_keys(&ctx, output.forwarded_events);
+ self.window_files = output.window_files;
+ if let Some(error) = output.error {
+ self.ui.status = error.to_string();
}
- for group in &groups {
- dock::paint_group_focus(ui, group, self.ui.focused, &t);
+ for event in output.events {
+ if let DockEvent::ToggleMaximize { panel } = event {
+ panels::keyboard::toggle_maximize(self, panel);
+ }
}
- 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 action in output.actions {
+ for action in self.close_keeping_timeline(action) {
+ if let Err(error) = self.dock_command(&ctx, action) {
+ self.ui.status = error;
+ }
}
}
- for action in layout_actions {
- let _ = self.dock_command(&ctx, action);
+ if restore_workspace {
+ let workspace = self.ui.workspace.clone();
+ self.set_workspace(&workspace);
}
- 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();
- }
- }
- DockAction::CloseSequence(id) => {
- if let Err(error) = self.session.execute("sequence.close", 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::MoveSequence(id, index) => {
- if let Err(error) = self.session.execute("sequence.moveTab", json!({"item": id, "index": index})) {
- 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::PanelMenu(panel, pos) => {
- let frame = ctx.cumulative_frame_nr();
- ctx.data_mut(|data| {
- data.insert_temp(egui::Id::unique("panel-menu"), (panel, pos));
- data.insert_temp(egui::Id::unique("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);
++ data.insert_temp(egui::Id::unique("panel-menu"), (panel, pos));
++ data.insert_temp(egui::Id::unique("panel-menu-opened"), frame);
+ });
+ }
+ let hits = DockArea::<PanelKind>::hit_rects(&ctx, area_id());
+ self.register_dock_hits(&hits);
panels::panel_menu_popup(self, ui);
- self.cancel_value_drag(ui.ctx());
}
- /// Draw one floating group on the middle layer, clamped on-screen with a minimum size; register its move/resize automation ids and submit `MoveFloating`
- /// for a drag or resize.
- 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::unique(("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,
- };
- 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::Role::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
- }
-
- /// Continue a docked panel drag: cancel on Escape, focus loss or an absent press/release, discard stale panel ids, prefer workspace-edge drops, and treat
- /// Command as force-float.
- 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::unique("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);
+ /// The Timeline's tabs stand for its open sequences: a close from the dock area (a tab's
+ /// middle click or Close Panel, a group, window or Close Other Panels item) that would
+ /// remove the Timeline while a sequence is open closes the active sequence instead, and the
+ /// Timeline stays. The other panels the action covers still close.
+ fn close_keeping_timeline(&mut self, action: Action<PanelKind>) -> Vec<Action<PanelKind>> {
+ if self.session.state.active_sequence.is_none() {
+ return vec![action];
}
- 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);
- }
+ let closed = match self.ui.dock.closed_by(&action) {
+ Ok(closed) if closed.contains(&PanelKind::Timeline) => closed,
+ _ => return vec![action],
+ };
+ if let Err(error) = self.session.execute("sequence.close", json!({})) {
+ self.ui.status = error.to_string();
}
- 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;
+ closed.into_iter().filter(|panel| *panel != PanelKind::Timeline).map(|panel| Action::Close { panel }).collect()
+ }
+
+ /// 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`,
+ /// `dock.gutter.<path>` (`a`/`b` per split level), `dock.corner.<outer path>.<inner path>`
+ /// where two dividers meet, the same inside floating window `n` as `panel.float.<n>.gutter.…`
+ /// and `panel.float.<n>.corner.…`. Controls of a floating window in its own OS window are
+ /// registered in that window's viewport.
+ 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 native: HashMap<usize, egui::ViewportId> = self.auto.windows.iter().map(|(viewport, index)| (*index, *viewport)).collect();
+ let mut found = Vec::new();
+ for (hit, rect) in hits {
+ let viewport = match hit {
+ Hit::Divider(Divider::Split(_) | Divider::Intersection(..)) => None,
+ Hit::Divider(Divider::WindowSplit(panel, _) | Divider::WindowIntersection(panel, ..))
+ | Hit::Tab(panel)
+ | Hit::DragBar(panel)
+ | Hit::Overflow(panel)
+ | Hit::Title(panel)
+ | Hit::Resize(panel, _) => window(panel).and_then(|index| native.get(&index).copied()),
+ _ => None,
}
- 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,
+ .unwrap_or(egui::ViewportId::ROOT);
+ 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, edge) => match window(panel) {
+ Some(index) if *edge == ResizeEdge::BottomRight => (format!("panel.float.{index}.resize"), "Resize floating panel"),
+ Some(index) => (format!("panel.float.{index}.resize.{edge:?}"), "Resize floating panel"),
+ None => continue,
+ },
+ Hit::Divider(Divider::Split(path)) => (format!("dock.gutter.{}", path_id(path)), "gutter"),
+ Hit::Divider(Divider::Intersection(outer, inner)) => (format!("dock.corner.{}.{}", path_id(outer), path_id(inner)), "gutter corner"),
+ Hit::Divider(Divider::WindowSplit(panel, path)) => match window(panel) {
+ Some(index) => (format!("panel.float.{index}.gutter.{}", path_id(path)), "gutter"),
+ None => continue,
+ },
+ Hit::Divider(Divider::WindowIntersection(panel, outer, inner)) => match window(panel) {
+ Some(index) => (format!("panel.float.{index}.corner.{}.{}", path_id(outer), path_id(inner)), "gutter corner"),
+ None => continue,
+ },
+ _ => continue,
};
- if let Some(action) = action
- && self.dock_command(ctx, action).is_ok()
- {
- self.ui.focused = panel;
+ found.push((entry, *rect, DockArea::hit_id(area_id(), hit), viewport));
+ }
+ // 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, viewport) in found {
+ self.auto.add_in(viewport, &id, rect, label);
+ if let Some(element) = self.auto.elements.last_mut() {
+ element.widget_id = Some(format!("{:016x}", widget.value()));
+ element.response_id = Some(widget);
}
}
}
}
-/// Width of the band along the workspace border that docks beside the whole layout.
-const EDGE_BAND: f32 = 8.0;
+/// A split path as `a`/`b` per level (first/second child).
+fn path_id(path: &[bool]) -> String {
+ path.iter().map(|second| if *second { 'b' } else { 'a' }).collect()
+}
+
+/// FilmCraft's window is all groups: drops on all four window edges, Ctrl/Cmd-drag undocks, a
+/// release over no target cancels, and a floating window's title bar only moves it.
+fn dock_style(ui: &egui::Ui, t: &Tokens) -> DockStyle {
+ let mut style = DockStyle::from_ui(ui);
+ style.side_edge_zones = true;
+ style.new_dock_zones = false;
+ style.maximize_item = true;
+ style.close_others_item = true;
+ style.command_press_floats = true;
+ style.float_on_empty_drop = false;
+ style.title_bar_docks = false;
+ style.float_hint = true;
+ style.wheel_selects_tabs = true;
+ style.middle_click_closes_tabs = true;
+ style.float_label = "Undock Panel".into();
+ style.float_group_label = "Undock Panel Group".into();
+ style.close_group_label = "Close Panel Group".into();
+ 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
+}
-/// 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;
+/// 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)>,
+ /// Restore Workspace chosen in a tab's menu; it replaces the layout after the dock area is drawn.
+ restore_workspace: bool,
+}
+
+impl DockContent<PanelKind> for FilmContent<'_> {
+ fn body(&mut self, ui: &mut egui::Ui, panel: &PanelKind) {
+ let t = self.tokens;
+ let frame = ui.max_rect();
+ let rect = frame;
+ self.bodies.push((*panel, rect, ui.layer_id()));
+ // A panel in its own OS window draws in that window's coordinates: its automation
+ // elements carry the window so they are not matched against main-window points.
+ let viewport = ui.ctx().viewport_id();
+ self.app.auto.viewport = viewport;
+ 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);
+ // FilmCraft's drag payload lives in context data, not egui's drag-and-drop, so craft-ui
+ // routes it to the native window under the pointer only when asked, each frame.
+ if panels::dragging(ui.ctx()) {
+ craft_ui::docking::route_app_drag(ui.ctx(), area_id());
+ }
+ self.app.auto.viewport = egui::ViewportId::ROOT;
+ // The body fills its frame; allocating it lets a floated panel take its full size.
+ ui.allocate_rect(ui.max_rect(), Sense::hover());
+ // Painted after the body so child backgrounds cannot hide the focus outline (#1075).
+ if self.app.ui.focused == *panel {
+ ui.painter().rect_stroke(frame, 0.0, Stroke::new(1.0, t.focus), StrokeKind::Inside);
+ }
}
- 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;
+
+ fn logical_label(&self, panel: &PanelKind) -> String {
+ crate::i18n::t(panel.title()).to_string()
}
- 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))
-}
-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));
+ /// Every floating panel gets its own OS window on desktop.
+ fn allow_native(&self, _panel: &PanelKind) -> bool {
+ true
+ }
+
+ /// The video viewers float as normal windows, say on a second display; the other panels
+ /// are palettes.
+ fn window_kind(&self, panel: &PanelKind) -> WindowKind {
+ match panel {
+ PanelKind::Program | PanelKind::Source | PanelKind::ReferenceMonitor | PanelKind::LumetriScopes => WindowKind::Normal,
+ _ => WindowKind::Palette,
}
}
- 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();
+ /// 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() }
}
- 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;
+
+ /// FilmCraft's own panel items head a tab's context menu, as in its ≡ menu; craft-ui adds
+ /// Undock, Move, Close and the group items after them.
+ fn panel_menu(&mut self, ui: &mut egui::Ui, panel: &PanelKind) {
+ let app = &mut *self.app;
+ let mut close = false;
+ if *panel == PanelKind::Timeline && app.session.state.active_sequence.is_some() {
+ let response = ui.add_enabled(app.session.state.open_sequences.len() > 1, egui::Button::new(tl!("Close Other Timeline Panels")));
+ app.auto.add_response("panel.tabMenu.Timeline.closeOthers", &response, "Close Other Timeline Panels");
+ if response.clicked() {
+ if let Err(error) = app.session.execute("sequence.closeOthers", json!({})) {
+ app.ui.status = error.to_string();
}
+ close = true;
}
- });
+ }
+ let response = ui.button(tl!("Restore Workspace"));
+ app.auto.add_response(&format!("panel.tabMenu.{}.restoreWorkspace", panel.id()), &response, "Restore Workspace");
+ if response.clicked() {
+ self.restore_workspace = true;
+ close = true;
+ }
+ close |= panels::panel_items(app, ui, *panel);
+ ui.separator();
+ if close {
+ ui.close();
+ }
+ }
+
+ /// The ≡ menu, and the Timeline's sequence tabs before it while the Timeline is shown.
+ /// 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.
+ 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"));
++ let response = ui.interact(rect, egui::Id::unique(("panel-menu-button", active.id())), Sense::click());
++ response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, response.enabled(), "panel menu"));
+ self.app.auto.add_response(&format!("panel.menu.{}", active.id()), &response, "panel menu");
+ let color = if response.hovered() { t.tab_text_active } else { t.tab_text };
+ icons::paint(ui.painter(), Rect::from_center_size(rect.center(), vec2(16.0, 16.0)), Icon::Hamburger, color);
+ 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 --cc crates/ui-egui/src/header.rs
index 9f08e2c8d,e1100c978..181de229f
--- a/crates/ui-egui/src/header.rs
+++ b/crates/ui-egui/src/header.rs
@@@ -10,9 -10,7 +10,10 @@@ use crate::icons::{self, Icon}
use crate::state::Mode;
use crate::theme::Tokens;
+/// Height of the header bar. With `integrated_titlebar` it sits in the macOS title-bar strip.
+pub const HEIGHT: f32 = 38.0;
+
+ /// Draw the header bar; dragging starts a native window move and double-click toggles maximized.
pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
let t = app.tokens;
let p = ui.painter().clone();
diff --cc crates/ui-egui/src/lib.rs
index a6545f178,01c3d57a2..37872e071
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@@ -64,9 -66,10 +66,10 @@@ mod theme_favorites
pub mod widgets;
use std::collections::HashMap;
-use std::sync::Arc;
use std::sync::mpsc::{Receiver, Sender};
+use std::sync::{Arc, Mutex};
+ use egui::ime_context::{ImeContextTracker, ImeTarget};
use egui::{TextureHandle, TextureOptions};
use filmcraft_engine::{Services, Session};
use filmcraft_time::Tick;
@@@ -582,15 -652,26 +659,27 @@@ impl FilmcraftApp
native_window_focused: None,
synthetic_modifiers: egui::Modifiers::NONE,
deferred: Vec::new(),
+ ui_requests: Vec::new(),
last_ui_time: 0.0,
synthetic: Vec::new(),
+ synthetic_pending_step: None,
+ synthetic_step_offered: false,
+ synthetic_modifiers_offered: false,
+ pasted_image: None,
+ clock_start: web_time::Instant::now(),
+ ui_clock: 0.0,
+ ui_clock_offset: None,
+ #[cfg(test)]
+ test_now: None,
mac_ctrl_click_armed: false,
+ native_ctrl_click_armed: Arc::default(),
value_press: None,
+ escape_cancel: false,
loudness: None,
status_seen: (String::new(), 0.0),
- pending_screenshots: Vec::new(),
- queued_screenshots: Vec::new(),
+ shots: capture::Shots::default(),
+ capture_geometry: None,
+ capture_epoch: 0,
monitor_inexact: false,
monitor_asked: HashMap::new(),
program_shown: None,
@@@ -1571,17 -1819,20 +1844,21 @@@
self.menu_sent = items;
}
- /// Whether keyboard focus is on a dock divider or a floating panel's resize grip, as drawn last pass.
+ /// Whether keyboard focus is on any dock divider or floating-window resize grip, as drawn last pass.
fn divider_focused(&self, ctx: &egui::Context) -> bool {
+ use craft_ui::docking::{DockArea, Hit};
let Some(focused) = ctx.memory(|m| m.focused()) else { return false };
- self.auto
- .all()
+ let area = dock_ui::area_id();
+ DockArea::<PanelKind>::hit_rects(ctx, area)
.iter()
- .any(|e| e.response_id == Some(focused) && (e.id.starts_with("dock.gutter.") || (e.id.starts_with("panel.float.") && e.id.ends_with(".resize"))))
+ .any(|(hit, _)| matches!(hit, Hit::Divider(_) | Hit::Resize(..)) && DockArea::hit_id(area, hit) == focused)
}
+ /// Per-pass shortcut handling: reset the pasted image, rebuild bindings only when the shortcut revision or workspace set changes, and leave unmodified keys
+ /// to a focused text field except dock dividers.
fn handle_shortcuts(&mut self, ctx: &egui::Context) {
+ // A paste image payload belongs to the paste event in this pass only.
+ self.pasted_image = None;
let workspaces = (dock::names(&self.workspaces), self.ui.workspace.clone());
if self.bindings_rev != self.session.shortcuts.revision || workspaces != self.menu_workspaces {
self.menu_workspaces = workspaces;
@@@ -1648,57 -1862,62 +1925,65 @@@
// Timeline's `Delete` (Clear) swallows the app-wide `Shift+Delete` (Ripple Delete) (#680).
let focused = self.ui.focused.title();
let mut fire = Vec::new();
- ctx.input_mut(|i| {
- let modifiers = i.modifiers;
- // With no text on the system clipboard, egui-winit drops the Ctrl+V press but still
- // passes its release: put the press back, so Paste can paste files or an image (#611).
- let mut swallowed = None;
- for e in &i.events {
- match e {
- egui::Event::Key { key: egui::Key::V, pressed, modifiers: m, .. } => {
- if !pressed && !self.v_down {
- swallowed = Some(*m);
- }
- self.v_down = *pressed;
+ let modifiers = i.modifiers;
+ // With no text on the system clipboard, egui-winit drops the Ctrl+V press but still
+ // passes its release: put the press back, so Paste can paste files or an image (#611).
+ let mut swallowed = None;
+ for e in &i.events {
+ match e {
+ egui::Event::Key { key: egui::Key::V, pressed, modifiers: m, .. } => {
+ if !pressed && !self.v_down {
+ swallowed = Some(*m);
}
- egui::Event::PasteImage(image) => {
- // Keep the delivered pixels; re-reading the OS clipboard later is racy and
- // the web host has no clipboard-media hook at all.
- self.pasted_image = Some(image.clone());
- if modifiers.command {
- self.v_down = true;
- }
+ self.v_down = *pressed;
+ }
++ egui::Event::PasteImage(image) => {
++ // Keep the delivered pixels; re-reading the OS clipboard later is racy and
++ // the web host has no clipboard-media hook at all.
++ self.pasted_image = Some(image.clone());
++ if modifiers.command {
++ self.v_down = true;
+ }
- egui::Event::Paste(_) if modifiers.command => self.v_down = true,
- _ => {}
+ }
+ egui::Event::Paste(_) if modifiers.command => self.v_down = true,
+ _ => {}
}
- if let Some(m) = swallowed {
- i.events.push(egui::Event::Key {
- key: egui::Key::V,
- physical_key: Some(egui::Key::V),
- pressed: true,
- repeat: false,
- modifiers: m | egui::Modifiers::COMMAND,
- });
+ }
+ if let Some(m) = swallowed {
+ i.events.push(egui::Event::Key {
+ key: egui::Key::V,
+ physical_key: Some(egui::Key::V),
+ pressed: true,
+ repeat: false,
+ modifiers: m | egui::Modifiers::COMMAND,
+ });
+ }
+ clipboard_events_as_keys(&mut i.events, modifiers);
+ let panel = self.bindings.iter().filter(|b| b.3.as_deref() == Some(focused));
+ let app_wide = self.bindings.iter().filter(|b| b.3.is_none());
+ let mut candidates: Vec<&menus::KeyBinding> = panel.chain(app_wide).collect();
+ candidates.sort_by_key(|b| std::cmp::Reverse(menus::specificity(b.0)));
+ for (m, k, id, _) in candidates {
+ // With a text field focused, an unmodified key belongs to the field (and to the input
+ // method composing in it), not to a tool shortcut: `J`, `Z`, `R`, `A`… are the keys
+ // Vietnamese Telex combines into diacritics (#243). Chords with a modifier stay:
+ // Ctrl+S and friends are not something a text field or an IME consumes.
+ if lets_text_field_keep(*m, text_focused) {
+ continue;
}
- clipboard_events_as_keys(&mut i.events, modifiers);
- let panel = self.bindings.iter().filter(|b| b.3.as_deref() == Some(focused));
- let app_wide = self.bindings.iter().filter(|b| b.3.is_none());
- let mut candidates: Vec<&menus::KeyBinding> = panel.chain(app_wide).collect();
- candidates.sort_by_key(|b| std::cmp::Reverse(menus::specificity(b.0)));
- for (m, k, id, _) in candidates {
- // With a text field focused, an unmodified key belongs to the field (and to the input
- // method composing in it), not to a tool shortcut: `J`, `Z`, `R`, `A`… are the keys
- // Vietnamese Telex combines into diacritics (#243). Chords with a modifier stay:
- // Ctrl+S and friends are not something a text field or an IME consumes.
- if lets_text_field_keep(*m, text_focused) {
- continue;
- }
- // The focused divider consumes the arrows itself (egui matches them with any Shift/Alt).
- if divider_focused && matches!(k, egui::Key::ArrowLeft | egui::Key::ArrowRight | egui::Key::ArrowUp | egui::Key::ArrowDown) {
- continue;
- }
- if i.consume_key(*m, *k) {
- fire.push(id.clone());
- }
+ // The focused divider consumes the arrows itself (egui matches them with any Shift/Alt).
+ if divider_focused && matches!(k, egui::Key::ArrowLeft | egui::Key::ArrowRight | egui::Key::ArrowUp | egui::Key::ArrowDown) {
+ continue;
}
- });
+ if i.consume_key(*m, *k) {
+ fire.push(id.clone());
+ }
+ }
+ fire
+ }
+
+ /// Run the commands of the bindings `match_shortcuts` fired, as the focused panel scopes them.
+ fn fire_shortcuts(&mut self, ctx: &egui::Context, fire: Vec<String>) {
for mut id in fire {
// Select All / Deselect All act on the Project panel's items when it has focus (#168).
// Select All takes only what the shown bin lists, not the whole project (#456).
@@@ -2133,31 -2314,6 +2380,31 @@@ impl FilmcraftApp
}
}
- /// `--control-input-only`: drop the window system's input. Screenshot responses and all
- /// viewport lifecycle and geometry data stay.
++/// `--control-input-only`: drop the window system's input. Screenshot results arrive through
++/// `ScreenshotCallback`, not raw input; all viewport lifecycle and geometry data stay.
+fn drop_native_input(raw_input: &mut egui::RawInput) {
- raw_input.events.retain(|event| matches!(event, egui::Event::Screenshot { .. }));
++ raw_input.events.clear();
+ raw_input.hovered_files.clear();
+ raw_input.dropped_files.clear();
+}
+
+/// The main window's input rewrite ([`eframe::App::raw_input_hook`]) for a dock panel in its
+/// own OS window, which eframe does not run the hook for: macOS Control+Click becomes a
+/// secondary click, and `--control-input-only` drops the window system's input. Control
+/// gestures go to the main window only, so nothing is added.
+pub(crate) fn rewrite_native_window_input(
+ control_input_only: bool,
+ #[cfg_attr(not(target_os = "macos"), allow(unused_variables))] armed: &Mutex<HashMap<egui::ViewportId, bool>>,
+ raw_input: &mut egui::RawInput,
+) {
+ if control_input_only {
+ drop_native_input(raw_input);
+ } else {
+ #[cfg(target_os = "macos")]
+ synthesize_mac_ctrl_click(armed.lock().unwrap_or_else(std::sync::PoisonError::into_inner).entry(raw_input.viewport_id).or_default(), raw_input);
+ }
+}
+
/// On macOS a Control+Click means "right click": AppKit delivers it to the view as a *primary*
/// press carrying the Control modifier (`rightMouseDown:` only fires for a real right button or
/// two-finger click), so the app translates it to a secondary click before egui computes pointer
@@@ -2270,26 -2404,115 +2495,113 @@@ impl FilmcraftApp
// keyboard focus) so the input is processed.
self.raise_for_control(ctx);
}
- if !self.synthetic.is_empty() {
+ if !self.synthetic.is_empty() || self.synthetic_pending_step.is_some() {
ctx.request_repaint();
- } else if !self.input_waiters.is_empty() {
- for w in self.input_waiters.drain(..) {
- let _ = w.send(json!({"ok": true, "result": null}));
+ // The next step is consumed by a UI pass, not by another logic tick. Native eframe
+ // honours this; the pinned web runner logs it as unhandled (a recorded fork gap).
+ ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaintWhileHidden);
+ }
+ }
+
+ /// Background queues and idempotent deadlines that are safe on every logic call.
+ fn logic_background(&mut self, ctx: &egui::Context, now: f64) {
+ self.frames.set_context(ctx);
+ self.frames.pump(std::time::Duration::from_millis(if self.playback.playing { 24 } else { 40 }));
+ self.session.poll_persistence();
+ panels::trim_monitor::advance_at(self, now);
+ if self.session.trim_play.active() {
+ ctx.request_repaint();
+ }
+ if self.session.persistence.is_some() && self.session.is_dirty() {
+ // Keep polling the auto-save worker (status, "also save the project" results) while hidden.
+ ctx.request_repaint_after(std::time::Duration::from_secs(1));
+ }
+ self.sync_pool();
+ #[cfg(not(target_arch = "wasm32"))]
+ self.tick_media_refresh(ctx, now);
+ }
+
+ /// Apply engine events that change the active sequence/view, IME target, toast or project.
+ fn logic_session_events(&mut self, now: f64) {
+ for ev in self.session.drain_events() {
+ match ev {
+ filmcraft_engine::Event::OpenSequence(_) => {
+ // A sequence switch (including opening/reverting/recovering a project, which
+ // emits this event for the newly active sequence) is a new IME owner context.
+ self.restart_ime_target();
+ // 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(_) => {
+ let _ = self.apply_dock(craft_ui::docking::Action::Activate { panel: PanelKind::Source });
+ }
+ filmcraft_engine::Event::RevealInProject(item) => self.reveal_in_project(item),
+ filmcraft_engine::Event::Toast { message, .. } => self.toast = Some((message, now)),
+ filmcraft_engine::Event::ProjectChanged { .. } => {}
}
}
- let settled = !std::mem::take(&mut self.monitor_inexact) && self.timeline_still > 0;
- self.issue_screenshots(ctx, settled);
- self.collect_screenshots(ctx);
}
- fn on_exit(&mut self) {
- // Flush the recovery journal and stop the auto-save worker; a session with nothing unsaved
- // removes its journal, one with unsaved changes keeps it for the next launch.
- self.session.shutdown();
+ /// Drain native menu/control command ids, preserving the control-only Quit exception.
+ fn logic_command_inbox(&mut self, ctx: &egui::Context) {
+ if let Some(rx) = self.command_inbox.take() {
+ while let Ok(id) = rx.try_recv() {
+ // control-only mode ignores native menu commands, but Quit stays available (#1943)
+ if self.control_input_only && id != "app.quit" {
+ continue;
+ }
+ if let Err(e) = menus::invoke(self, ctx, &id, json!({})) {
+ self.ui.status = e;
+ }
+ }
+ self.command_inbox = Some(rx);
+ }
}
- fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
+ /// Run one logic pass in order: retain the later UI clock, poll the native dialog, apply the
+ /// logic subsystems, advance playback, poll jobs, then drain completed screenshots and ask
+ /// for hidden paints. Safe on hidden logic-only callbacks.
+ pub fn logic_inner(&mut self, ctx: &egui::Context) {
+ // Remember the pass's clock before anything reads `now()`. A hidden logic-only tick keeps
+ // the last UI time (which is stale there), so `now()` never runs behind the host clock.
+ self.ui_clock = self.ui_clock.max(ctx.input(|i| i.time));
+ // a native file dialog's answer first, so the panels draw what it chose (#260)
+ self.poll_native_dialog(ctx);
+ self.logic_theme(ctx);
+ let now = self.logic_clock(ctx);
+ self.logic_control(ctx);
+ self.logic_background(ctx, now);
+ self.logic_session_events(now);
+ self.logic_command_inbox(ctx);
+ self.advance_playback(ctx);
+ self.advance_source_playback(ctx);
+ self.poll_jobs(ctx);
+ capture::drain(self, ctx);
+ capture::request_hidden_paint(self, ctx);
+ }
+
+ /// Draw one real UI pass. Establish the UI clock offset once, run first-pass input handling,
+ /// draw panels under a panic guard, drain UI requests and observe the IME editor only after
+ /// this pass's commands ran. Screenshots are offered to `capture::issue`, which issues only
+ /// on an accepted pass.
+ fn ui_inner(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
+ if self.ui_clock_offset.is_none() {
+ let egui_time = ui.ctx().input(|input| input.time);
+ if egui_time.is_finite() {
+ let host = self.clock_start.elapsed().as_secs_f64();
+ // Never move host time backwards when a harness clock starts behind it; the host
+ // clock stays authoritative in that case.
+ self.ui_clock_offset = Some((egui_time - host).max(0.0));
+ }
+ }
if !self.fonts_ready {
+ // This pass did not consume the pending synthetic input; the next hook must offer it
+ // again (the UI path does not preserve raw input across this early return).
+ self.synthetic_step_offered = false;
+ self.synthetic_modifiers_offered = false;
+ self.finish_ime_pass(ui.ctx());
ui.ctx().request_repaint();
return;
}
@@@ -2317,10 -2585,111 +2674,107 @@@
let _ = w.send(json!({"ok": true, "result": null}));
}
}
- if self.frames.queue_len() > 0 {
- ctx.request_repaint_after(std::time::Duration::from_millis(16));
+ // Only a real, accepted UI pass may issue a capture: it observes the final layout for this
+ // pass and `screenshot` itself forces the paint needed when the window is hidden.
+ capture::issue(self, &ctx);
+ }
+ }
+
+ impl eframe::App for FilmcraftApp {
+ /// Snapshot this callback's fresh surface geometry, optionally synthesize macOS ctrl-click
+ /// and agent input, and offer at most one queued synthetic step. A step already preserved by
+ /// hidden logic callbacks is not appended twice; a real UI pass clears it.
+ fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
+ self.native_window_focused = Some(raw_input.focused);
+ capture::note_raw_geometry(self, ctx, raw_input);
+ #[cfg(target_os = "macos")]
+ if !self.control_input_only {
+ synthesize_mac_ctrl_click(&mut self.mac_ctrl_click_armed, raw_input);
+ }
+ if self.control_input_only {
- // Screenshot results arrive through `ScreenshotCallback`, not raw input. Preserve all
- // viewport lifecycle/geometry metadata and drop native input only.
- raw_input.events.clear();
- raw_input.hovered_files.clear();
- raw_input.dropped_files.clear();
++ drop_native_input(raw_input);
+ }
+ if self.control_input_only || !self.synthetic.is_empty() || self.synthetic_pending_step.is_some() {
+ // Native modifiers cannot replace those requested by a control gesture. A queued
+ // reset runs in the frame after release, so clicked() still sees Shift/Alt.
+ if !self.synthetic_modifiers_offered {
+ raw_input.events.push(egui::Event::ModifiersChanged(self.synthetic_modifiers));
+ self.synthetic_modifiers_offered = true;
+ }
+ // Widget keyboard handling requires effective egui focus. Control input must work
+ // in a background window without activating it or taking the user's OS keyboard.
+ raw_input.focused = true;
+ }
+ if self.synthetic_pending_step.is_none() && !self.synthetic.is_empty() {
+ // Pointer events go one per frame so egui sees press → moves → release as a real drag
+ // (all in one frame reads as a click); key/text runs go together up to a key release.
+ let pointer = |e: &egui::Event| matches!(e, egui::Event::PointerMoved(_) | egui::Event::PointerButton { .. } | egui::Event::MouseWheel { .. });
+ let n = if pointer(&self.synthetic[0]) {
+ 1
+ } else {
+ self.synthetic
+ .iter()
+ .position(|e| pointer(e) || matches!(e, egui::Event::Key { pressed: false, .. }))
+ .map_or(self.synthetic.len(), |i| if pointer(&self.synthetic[i]) { i.max(1) } else { i + 1 })
+ };
+ let step: Vec<egui::Event> = self.synthetic.drain(..n).collect();
+ for event in &step {
+ if let egui::Event::ModifiersChanged(modifiers) = event {
+ self.synthetic_modifiers = *modifiers;
+ }
+ }
+ self.synthetic_pending_step = Some(step);
+ self.synthetic_step_offered = false;
+ }
+ if let Some(step) = &self.synthetic_pending_step {
+ // `raw_input_hook` also runs before hidden `run_logic` ticks, whose raw input egui does
+ // not feed to widgets. Keep the exact same one-step batch pending and offer it again
+ // on the next callback; a real UI pass clears it at `ui()` start. Never coalesce a
+ // press with its release and, crucially, never append a step that the integration
+ // already preserved in its pending raw input: the UI pass would then see two copies.
+ if !self.synthetic_step_offered {
+ raw_input.events.extend(step.iter().cloned());
+ self.synthetic_step_offered = true;
+ }
}
}
+
+ /// Eframe's hidden logic callback: run the logic pass, sync the IME target context, then
+ /// suspend reset state because a logic-only callback is never a UI pass.
+ fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
+ self.logic_inner(ctx);
+ self.finish_ime_reset_logic(ctx);
+ }
+
+ /// Cancel outstanding screenshots with one error reply each, end per-viewport IME tracker and
+ /// reset state, and shut the session down so its recovery journal is flushed or removed.
+ fn on_exit(&mut self) {
+ // Late screenshot callbacks now find a dropped slot and write nothing; clients get one error.
+ capture::cancel_all(self);
+ for viewport in self.ime_viewports.drain(..) {
+ self.ime_context.end_viewport(viewport);
+ self.ime_reset.end_viewport(viewport);
+ }
+ self.ime_observed_pass = None;
+ // Flush the recovery journal and stop the auto-save worker; a session with nothing unsaved
+ // removes its journal, one with unsaved changes keeps it for the next launch.
+ self.session.shutdown();
+ }
+
+ /// Eframe's UI entry: begin this pass's IME reset state, suspend custom controls when no
+ /// eligible editor owns input, draw `ui_inner`, then run end-of-pass IME reconciliation.
+ fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
+ let ctx = ui.ctx().clone();
+ self.ime_reset.begin_pass(&ctx);
+ self.ime_drawn_editor = None;
+ let focused = ctx.input(|input| input.viewport().focused.unwrap_or(input.focused));
+ let another_field = ctx.memory(|memory| memory.focused().is_some_and(|id| id != egui::Id::unique(panels::graphics::TEXT_EDIT_ID)));
+ if !self.fonts_ready || self.ui.gfx_edit.is_none() || self.ime_modal_blocks_input() || !focused || another_field {
+ self.suspended_ime_controls(&ctx);
+ }
+ self.ui_inner(ui, frame);
+ self.finish_ime_reset_ui(&ctx);
+ }
}
/// Effective sample rate for shuttle playback. The audio device still runs at `device_rate`,
@@@ -3085,91 -3474,81 +3575,168 @@@ mod native_menu_tests
assert_eq!(last(&sent, "edit.undo"), Some(false));
assert_eq!(last(&sent, "edit.redo"), Some(true), "the undone edit can be redone");
}
+}
+
+#[cfg(test)]
+mod native_window_input_tests {
+ use super::*;
+ use std::path::{Path, PathBuf};
+
+ use craft_ui::docking::WindowFiles;
+ use egui_kittest::Harness;
+ use filmcraft_engine::Session;
+
+ #[derive(Debug)]
+ struct OsFile(PathBuf);
+
+ impl egui::DroppedFile for OsFile {
+ fn path(&self) -> &Path {
+ &self.0
+ }
+
+ fn bytes(&self) -> Result<Vec<u8>, String> {
+ std::fs::read(&self.0).map_err(|e| e.to_string())
+ }
+ }
+
+ fn step(h: &mut Harness<'static, FilmcraftApp>) {
+ let ctx = h.ctx.clone();
+ let mut raw = std::mem::take(h.input_mut());
+ eframe::App::raw_input_hook(h.state_mut(), &ctx, &mut raw);
+ *h.input_mut() = raw;
+ ctx.request_repaint();
+ h.step();
+ }
+
+ fn clips(h: &Harness<'static, FilmcraftApp>) -> usize {
+ h.state().session.active_sequence().map_or(0, |q| q.video_tracks.iter().map(|t| t.items.len()).sum())
+ }
+
+ /// Files dropped on a dock panel in its own OS window are imported; on the Timeline they are
+ /// placed at the pointer, by the Timeline drawn in that window only.
+ #[test]
+ fn files_dropped_on_native_windows_import_and_reach_their_timeline() {
+ let dir = tempfile::tempdir().unwrap();
+ let still = dir.path().join("native_window_drop.png");
+ image::RgbaImage::from_pixel(64, 36, image::Rgba([40, 140, 220, 255])).save(&still).unwrap();
+ let mut s = Session::default();
+ s.execute("file.openDemoProject", json!({})).unwrap();
+ s.execute("file.newSequence", json!({"name": "Drop test", "width": 1280, "height": 720, "fps": 24})).unwrap();
+ let mut h = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).build_eframe(move |_cc| FilmcraftApp::new(s));
+ for _ in 0..4 {
+ step(&mut h);
+ }
+ let row = h.state().auto.find("timeline.track.V1.target").unwrap().rect;
+ let panel = h.state().auto.find("panel.Timeline").unwrap().rect;
+ let at = egui::pos2(panel[0] + h.state().ui.timeline.header_w + 60.0, row[1] + row[3] / 2.0);
+ let drop_files = |h: &mut Harness<'static, FilmcraftApp>, panel: PanelKind, viewport: egui::ViewportId| {
+ let files = WindowFiles { window: 1, viewport, panel, pos: Some(at), hovered: Vec::new(), dropped: vec![Arc::new(OsFile(still.clone()))] };
+ h.state_mut().window_files = vec![files];
+ step(h);
+ step(h);
+ };
+ let items = h.state().session.project.items.len();
+ // another window's Timeline: imported, and the main window's Timeline leaves it
+ drop_files(&mut h, PanelKind::Timeline, egui::ViewportId::from_hash_of("another window"));
+ assert_eq!((h.state().session.project.items.len(), clips(&h)), (items + 1, 0), "status: {}", h.state().ui.status);
+ // a panel other than the Timeline: imported to the bin only
+ drop_files(&mut h, PanelKind::Project, egui::ViewportId::ROOT);
+ assert_eq!((h.state().session.project.items.len(), clips(&h)), (items + 2, 0), "status: {}", h.state().ui.status);
+ // the Timeline drawn in the window the files were dropped on places them
+ drop_files(&mut h, PanelKind::Timeline, egui::ViewportId::ROOT);
+ assert_eq!((h.state().session.project.items.len(), clips(&h)), (items + 3, 1), "status: {}", h.state().ui.status);
+ }
+
+ /// `--control-input-only` drops a native window's own input as the main window's hook does.
+ #[test]
+ fn control_input_only_drops_native_window_input() {
+ let armed = Mutex::new(HashMap::new());
+ let mut raw = egui::RawInput { viewport_id: egui::ViewportId::from_hash_of("palette"), ..Default::default() };
+ raw.events = vec![egui::Event::Text("typing".into()), egui::Event::PointerMoved(egui::pos2(4.0, 4.0))];
+ raw.hovered_files.push(Default::default());
+ raw.dropped_files.push(Arc::new(OsFile(PathBuf::from("/unrelated-input.txt"))));
+ let mut kept = raw.clone();
+ rewrite_native_window_input(false, &armed, &mut kept);
+ assert_eq!(kept.events.len(), 2);
+ assert_eq!(kept.dropped_files.len(), 1);
+ rewrite_native_window_input(true, &armed, &mut raw);
+ assert!(raw.events.is_empty() && raw.hovered_files.is_empty() && raw.dropped_files.is_empty());
+ }
}
+
+ #[cfg(test)]
+ mod lifecycle_synthetic_tests {
+ use egui::{Event, Modifiers, PointerButton, pos2};
+ use filmcraft_engine::Session;
+
+ use super::FilmcraftApp;
+
+ /// Extract the pointer-moved positions from a raw event batch, for synthetic-input tests.
+ fn pointer_events(events: &[Event]) -> Vec<egui::Pos2> {
+ events
+ .iter()
+ .filter_map(|event| match event {
+ Event::PointerMoved(pos) => Some(*pos),
+ _ => None,
+ })
+ .collect()
+ }
+
+ /// `raw_input_hook` runs before hidden logic ticks too, but those raw events are not fed to
+ /// widgets. The same one-step batch must remain pending, instead of advancing to the next
+ /// step or being silently lost; a real UI pass consumes it.
+ #[test]
+ fn one_synthetic_step_survives_hidden_logic_callbacks() {
+ let ctx = egui::Context::default();
+ let mut app = FilmcraftApp::new(Session::default());
+ app.synthetic = vec![
+ Event::PointerMoved(pos2(10.0, 10.0)),
+ Event::PointerMoved(pos2(20.0, 20.0)),
+ Event::PointerButton { pos: pos2(20.0, 20.0), button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE },
+ Event::PointerButton { pos: pos2(20.0, 20.0), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE },
+ ];
+ let mut first = egui::RawInput::default();
+ eframe::App::raw_input_hook(&mut app, &ctx, &mut first);
+ assert_eq!(pointer_events(&first.events), vec![pos2(10.0, 10.0)]);
+ assert_eq!(app.synthetic.len(), 3, "only one step was popped");
+ assert_eq!(app.synthetic_pending_step.as_ref().map(Vec::len), Some(1));
+
+ // The integration keeps the raw input that did not reach widgets (native
+ // `pending_raw_input`, web `input.raw`) and replays it through the hook.
+ let mut hidden = first.clone();
+ eframe::App::raw_input_hook(&mut app, &ctx, &mut hidden);
+ assert_eq!(pointer_events(&hidden.events), vec![pos2(10.0, 10.0)], "the preserved step is not appended twice");
+ assert_eq!(app.synthetic.len(), 3, "a hidden callback must not advance the queue");
+
+ // A real UI pass consumes the pending step (App::ui clears it at its start).
+ app.synthetic_pending_step = None;
+ app.synthetic_step_offered = false;
+ app.synthetic_modifiers_offered = false;
+ let mut next = egui::RawInput::default();
+ eframe::App::raw_input_hook(&mut app, &ctx, &mut next);
+ assert_eq!(pointer_events(&next.events), vec![pos2(20.0, 20.0)]);
+ assert_eq!(app.synthetic.len(), 2);
+ }
+
+ /// eframe's hidden `run_logic` path saves the raw input (including our step) and hands it to
+ /// `raw_input_hook` again on the next hidden callback. The hook must not append the same step
+ /// a second time, or the eventual UI pass inserts text / clicks / runs a command more than once.
+ #[test]
+ fn hidden_callbacks_do_not_duplicate_a_step_preserved_in_raw_input() {
+ let ctx = egui::Context::default();
+ let mut app = FilmcraftApp::new(Session::default());
+ app.synthetic =
+ vec![Event::Text("once".into()), Event::Key { key: egui::Key::F35, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE }];
+ let mut first = egui::RawInput::default();
+ eframe::App::raw_input_hook(&mut app, &ctx, &mut first);
+ let texts = |events: &[Event]| events.iter().filter(|e| matches!(e, Event::Text(t) if t == "once")).count();
+ assert_eq!(texts(&first.events), 1);
+
+ // What the integration preserves as pending_raw_input, then replays through the hook on
+ // the next hidden logic tick.
+ let mut preserved = first.clone();
+ eframe::App::raw_input_hook(&mut app, &ctx, &mut preserved);
+ assert_eq!(texts(&preserved.events), 1, "the preserved raw input must keep exactly one copy");
+ assert_eq!(app.synthetic_pending_step.as_ref().map(Vec::len), Some(2), "the queue did not advance");
+ }
+ }
diff --cc crates/ui-egui/src/panels/masks.rs
index 7f51e4bbd,299852c23..1a36f6bcc
--- a/crates/ui-egui/src/panels/masks.rs
+++ b/crates/ui-egui/src/panels/masks.rs
@@@ -298,40 -299,17 +300,40 @@@ pub fn monitor_overlay(app: &mut Filmcr
let v = lin_inv.apply(Vec2::new(d.x as f64, d.y as f64));
[v.x, v.y]
};
+ // ---- vertex marquee: a drag that starts on the picture outside the shape (under every
+ // handle, so they come first; Selection tool only, the Hand pans). It sits over the graphics
+ // overlay, so it leaves graphic layers to it and takes over its click on empty space. Where the
+ // marquee started (stored for the gesture, until the button is up) keeps it registered over a
+ // layer through the release.
+ let marquee_id = egui::Id::new("mask-marquee");
+ let marquee_from = egui::Id::new("mask-marquee-from");
+ let selection_tool = app.ui.tool == crate::state::Tool::Selection;
+ if !ui.input(|i| i.pointer.primary_down() || i.pointer.primary_released()) {
+ ui.data_mut(|d| d.remove::<Pos2>(marquee_from));
+ }
+ let marquee_on = ui.data(|d| d.get_temp::<Pos2>(marquee_from)).is_some();
+ let on_layer = |p: Pos2| pic.contains(p) && crate::panels::graphics::visible_layers(app, pic, frame).iter().any(|v| v.hit(p));
+ let marquee = (selection_tool && (marquee_on || !ui.input(|i| i.pointer.hover_pos()).is_some_and(on_layer)))
+ .then(|| ui.interact(pic, marquee_id, Sense::click_and_drag()));
+ if let Some(r) = &marquee {
+ app.auto.add("program.mask.marquee", pic, "Mask vertex marquee");
+ if r.clicked() {
+ crate::panels::graphics::deselect_on_monitor(app, ui);
+ }
+ }
// ---- whole mask (drag inside)
let bb = Rect::from_points(&screen).expand(2.0).intersect(pic);
- let body = ui.interact(bb, egui::Id::new("mask-body"), Sense::click_and_drag());
+ let body = ui.interact(bb, egui::Id::unique("mask-body"), Sense::click_and_drag());
app.auto.add("program.mask.body", bb, &m.name);
let ptr_in = |p: Option<Pos2>| p.is_some_and(|p| inside(&flat, to_clip.apply(Vec2::new(p.x as f64, p.y as f64))));
if body.drag_started_by(LEFT) {
let ok = ptr_in(body.interact_pointer_pos());
ui.data_mut(|d| d.insert_temp(gesture_id.with("body"), ok));
}
+ // (inside the outline's box but outside the shape, the drag is a marquee too)
+ let body_marquee = selection_tool && !ui.data(|d| d.get_temp::<bool>(gesture_id.with("body"))).unwrap_or(false);
if body.dragged_by(LEFT) && ui.data(|d| d.get_temp::<bool>(gesture_id.with("body"))).unwrap_or(false) && body.drag_delta() != egui::Vec2::ZERO {
- let d = drag_step(ui, egui::Id::new(("mask-body-drag", gesture)), body.drag_delta());
+ let d = drag_step(ui, egui::Id::unique(("mask-body-drag", gesture)), body.drag_delta());
if d != egui::Vec2::ZERO {
actions.push(("masks.translate".into(), with(json!({"delta": clip_delta(d), "merge": format!("body-{gesture}")}))));
}
@@@ -383,14 -361,10 +385,14 @@@
// ---- corner roundness (masks with sharp corners: rectangles, polygons)
actions.extend(roundness_handle(app, ui, &painter, &path, &to_screen, &target));
// ---- tangent handles and vertices
- let sel_v_id = egui::Id::new(("mask-sel-vertex", sel.clip.0, sel.effect, sel.mask));
+ let sel_v_id = egui::Id::unique(("mask-sel-vertex", sel.clip.0, sel.effect, sel.mask));
- let sel_v: Option<usize> = ui.data(|d| d.get_temp(sel_v_id));
+ let n_v = path.vertices.len();
+ // (stored with the vertex count: once a vertex is added or deleted, by any edit or by undo, the
+ // indices name other vertices and the selection goes)
+ let mut sel_vs: Vec<usize> = ui.data(|d| d.get_temp::<(usize, Vec<usize>)>(sel_v_id)).filter(|(n, _)| *n == n_v).map(|(_, v)| v).unwrap_or_default();
let alt = ui.input(|i| i.modifiers.alt);
let cmd = ui.input(|i| i.modifiers.command);
+ let shift = ui.input(|i| i.modifiers.shift);
for (i, v) in path.vertices.iter().enumerate() {
if v.is_corner() {
continue;
@@@ -415,32 -389,22 +417,32 @@@
for (i, v) in path.vertices.iter().enumerate() {
let p = sp(&to_screen, v.p);
let vr = Rect::from_center_size(p, vec2(7.0, 7.0));
- let selected = sel_v == Some(i);
+ let selected = sel_vs.contains(&i);
painter.rect_filled(vr, 0.0, if selected { col } else { Color32::WHITE });
painter.rect_stroke(vr, 0.0, Stroke::new(1.0, col), egui::StrokeKind::Middle);
- let r = ui.interact(vr.expand(3.0), egui::Id::new(("mask-vertex", i)), Sense::click_and_drag()).on_hover_text(if cfg!(target_os = "macos") {
+ let r = ui.interact(vr.expand(3.0), egui::Id::unique(("mask-vertex", i)), Sense::click_and_drag()).on_hover_text(if cfg!(target_os = "macos") {
tl!("Drag: move · Alt-click: smooth/corner · Cmd-click: delete")
} else {
tl!("Drag: move · Alt-click: smooth/corner · Ctrl-click: delete")
});
app.auto.add(&format!("program.mask.vertex.{i}"), vr, "Mask vertex");
- if r.drag_started_by(LEFT) {
- ui.data_mut(|d| d.insert_temp(sel_v_id, i));
+ // dragging a selected vertex moves the whole selection; another one is selected first
+ // (added to it with Shift)
+ if r.drag_started_by(LEFT) && !selected {
+ if !shift {
+ sel_vs.clear();
+ }
+ sel_vs.push(i);
+ ui.data_mut(|d| d.insert_temp(sel_v_id, (n_v, sel_vs.clone())));
}
if r.dragged_by(LEFT) && r.drag_delta() != egui::Vec2::ZERO {
- let d = drag_step(ui, egui::Id::new(("mask-vertex-drag", gesture, i)), r.drag_delta());
+ let d = drag_step(ui, egui::Id::unique(("mask-vertex-drag", gesture, i)), r.drag_delta());
if d != egui::Vec2::ZERO {
- actions.push(("masks.moveVertex".into(), with(json!({"vertex": i, "delta": clip_delta(d), "merge": format!("vertex-{gesture}")}))));
+ let which = if sel_vs.len() > 1 && sel_vs.contains(&i) { json!({"vertices": sel_vs}) } else { json!({"vertex": i}) };
+ let mut p = with(which);
+ p["delta"] = json!(clip_delta(d));
+ p["merge"] = json!(format!("vertex-{gesture}"));
+ actions.push(("masks.moveVertex".into(), p));
}
}
if r.clicked() {
diff --cc crates/ui-egui/tests/it/monitor_geometry.rs
index 0b6b355cf,d8329278a..7435b8c7e
--- a/crates/ui-egui/tests/it/monitor_geometry.rs
+++ b/crates/ui-egui/tests/it/monitor_geometry.rs
@@@ -23,14 -24,17 +23,14 @@@ fn harness_at_scale(width: f32, kind: T
move |ui, app: &mut FilmcraftApp| {
app.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);
- }
+ // A stand-in for the docked frame: the themed panel background, with the body below
+ // a tab strip's height.
+ 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);
+ 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));
+ ui.ctx().data_mut(|data| data.insert_temp(egui::Id::unique("observed-source-drag"), source));
},
FilmcraftApp::new(session),
);
diff --cc crates/ui-egui/tests/it/ui_keyboard_focus.rs
index 9489ceda7,f03b01ca6..11eb818c4
--- a/crates/ui-egui/tests/it/ui_keyboard_focus.rs
+++ b/crates/ui-egui/tests/it/ui_keyboard_focus.rs
@@@ -26,12 -30,11 +26,12 @@@ fn tab_traversal_and_space_select_only_
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()));
- let third = Id::new(("tool", "Ripple".to_string()));
+ let first = Id::unique(("tool", "Selection".to_string()));
+ let second = Id::unique(("tool", "TrackSelectForward".to_string()));
+ let third = Id::unique(("tool", "Ripple".to_string()));
for _ in 0..128 {
key(&mut h, Key::Tab, Modifiers::NONE);
if h.ctx.memory(|m| m.focused()) == Some(first) {