diff --git a/crates/app/src/keyframes.rs b/crates/app/src/keyframes.rs index 38bfe6a0697514c2364c2ad50d36ad3ff8e84d8d..4d47a45bfb49a7a75cca22d1988819e4233ebf74 100644 --- a/crates/app/src/keyframes.rs +++ b/crates/app/src/keyframes.rs @@ -288,6 +288,20 @@ impl KeyframesView { true } + fn cancel_retime_drag(&mut self, comp: &mut Comp) -> bool { + let Some(drag) = self.retime_drag.take() else { return false }; + for (sname, keyframes) in drag.saved_splines { + if let Some(sp) = comp.splines.get_mut(&sname) { + sp.keyframes = keyframes; + } + } + self.selected_keys = drag.orig_selected; + if drag.moved { + comp.revision += 1; + } + drag.moved + } + fn delete_selected(&mut self, comp: &mut Comp, history: &mut CompHistory) -> bool { if self.selected_keys.is_empty() { return false; @@ -492,6 +506,11 @@ impl KeyframesView { ) { let plain = !kmod.super_key() && !kmod.control_key() && !kmod.alt_key(); match key { + Key::Named(NamedKey::Escape) => { + if self.cancel_retime_drag(comp) { + actions.push(KeyframesAction::KeyframesEdited); + } + } Key::Named(NamedKey::Delete | NamedKey::Backspace) => { if self.delete_selected(comp, history) { actions.push(KeyframesAction::KeyframesEdited); @@ -680,6 +699,28 @@ mod tests { assert!((comp.splines["XF1Size"].keyframes[1].time - 40.0).abs() < 1e-6); } + #[test] + fn escape_cancels_an_active_retime_drag() { + let mut comp = sample_animated_comp(); + let mut history = CompHistory::new(); + let mut view = KeyframesView::new(&ui::Theme::dark()); + view.resize([800.0, 300.0]); + let key = DopeKeyRef { spline: "XF1Size".to_owned(), key_idx: 0 }; + view.selected_keys.insert(key.clone()); + view.begin_retime_drag(&comp); + view.pointer_local[0] += 60.0; + assert!(view.apply_retime_drag(&mut comp)); + assert_ne!(comp.splines["XF1Size"].keyframes[0].time, 10.0); + + let mut actions = Vec::new(); + view.handle_key(&mut comp, &mut history, &Key::Named(NamedKey::Escape), ModifiersState::empty(), &mut actions); + + assert_eq!(comp.splines["XF1Size"].keyframes[0].time, 10.0); + assert!(view.retime_drag.is_none()); + assert_eq!(view.selected_keys, HashSet::from([key])); + assert_eq!(actions.len(), 1); + } + #[test] fn retime_past_a_neighbour_keeps_curve_sorted_and_selection_on_the_key() { let mut comp = sample_animated_comp(); diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 6a01c696ed640ee6e23a053ba9cb661353be668c..aaf0dbcf5f0bf0fc38e1e1c3d47285289d947a29 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -400,6 +400,9 @@ impl Studio { } self.flow.sanitize_ids(&self.comp); self.flow.viewed_nodes = self.viewers.each_ref().map(|v| v.viewed_node); + for v in &mut self.viewers { + v.selected_node = self.flow.primary; + } self.keyframes.sanitize_ids(&self.comp); self.inspector.reset(); self.renaming_node = None; @@ -775,6 +778,8 @@ impl Studio { for ev in sig.events { acts.extend(self.flow.input(&mut self.comp, &mut self.history, ev, rect, ptr, mods)); } + // Ids carried by actions predate a delete in the same batch and may now name another node. + let deleted = self.comp.nodes.len() < node_count; if self.comp.nodes.len() != node_count { self.reconcile_node_refs(prev_viewed); } @@ -783,6 +788,7 @@ impl Studio { FlowAction::SelectionChanged(sel) => { self.spline.set_target_node(&self.comp, sel); } + FlowAction::ViewNode(_, id) | FlowAction::RequestRename(id) if deleted || id.0 >= self.comp.nodes.len() => {} FlowAction::ViewNode(slot, id) => { self.viewers[slot].viewed_node = Some(id); self.viewers[slot].dirty = true; @@ -877,6 +883,10 @@ impl Studio { } } KeyframesAction::SelectNode(id) => { + // Dope sheet tracks are root-level nodes; the canvas must show the one it selects. + if !self.flow.scope_path().is_empty() { + self.flow.exit_to_depth(&self.comp, 0); + } self.flow.selected.clear(); self.flow.selected.insert(id); self.flow.primary = Some(id); @@ -890,6 +900,12 @@ impl Studio { } } + // Mutations above (add, rename, undo, drags) must not paint a frame with stale labels. + self.flow.prepare_labels(&self.comp); + self.spline.prepare_labels(&self.comp); + self.keyframes.sync_tracks(&self.comp, self.flow.primary); + self.keyframes.prepare_labels(); + // Immediately re-render any dirty visible viewer before painting this frame! self.render_visible_viewers(true); @@ -1022,6 +1038,20 @@ struct WindowHost { studio: Studio, access: Accessibility, occluded: bool, + /// When background work (export, prefetch) next gets a repaint; `None` while there is none. + next_bg_poll: Option, +} + +const BG_POLL: Duration = Duration::from_millis(100); + +/// Advances the background poll deadline; returns whether it has arrived and the next wake time. +fn poll_background(next: &mut Option, now: Instant) -> (bool, Instant) { + let due = *next.get_or_insert(now + BG_POLL); + if now < due { + return (false, due); + } + *next = Some(now + BG_POLL); + (true, now + BG_POLL) } struct App { @@ -1090,7 +1120,7 @@ impl WindowHost { let quit = proxy.clone(); ui::host::macos::quit(move || { let _ = quit.send_event(UserEvent::Quit); }); } - Ok(Self { window, surface, studio, access, occluded: false }) + Ok(Self { window, surface, studio, access, occluded: false, next_bg_poll: None }) } fn redraw(&mut self) -> Result<(), Box> { @@ -1211,25 +1241,25 @@ impl ApplicationHandler for App { } fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { - if let Some(host) = &self.host { - if !host.occluded { - if host.studio.playback.playing { - let wake = host.studio.playback.next_wake(&host.studio.comp); - event_loop.set_control_flow(ControlFlow::WaitUntil(Instant::now() + wake)); - host.window.request_redraw(); - return; - } - if host.studio.active_export.is_some() { - event_loop.set_control_flow(ControlFlow::WaitUntil(Instant::now() + Duration::from_millis(100))); - host.window.request_redraw(); - return; - } - if host.studio.prefetcher.as_ref().is_some_and(RamPrefetcher::is_busy) { - event_loop.set_control_flow(ControlFlow::WaitUntil(Instant::now() + Duration::from_millis(200))); + if let Some(host) = &mut self.host + && !host.occluded + { + if host.studio.playback.playing { + host.next_bg_poll = None; + let wake = host.studio.playback.next_wake(&host.studio.comp); + event_loop.set_control_flow(ControlFlow::WaitUntil(Instant::now() + wake)); + host.window.request_redraw(); + return; + } + if host.studio.active_export.is_some() || host.studio.prefetcher.as_ref().is_some_and(RamPrefetcher::is_busy) { + let (due, wake) = poll_background(&mut host.next_bg_poll, Instant::now()); + if due { host.window.request_redraw(); - return; } + event_loop.set_control_flow(ControlFlow::WaitUntil(wake)); + return; } + host.next_bg_poll = None; } event_loop.set_control_flow(ControlFlow::Wait); } @@ -1311,6 +1341,19 @@ mod tests { studio.comp.find_node(name).unwrap() } + #[test] + fn background_poll_repaints_at_ten_hertz_instead_of_spinning() { + let t0 = Instant::now(); + let mut next = None; + assert_eq!(poll_background(&mut next, t0), (false, t0 + BG_POLL)); + // Event-loop wakeups before the deadline neither repaint nor move it. + let early = t0 + BG_POLL / 2; + assert_eq!(poll_background(&mut next, early), (false, t0 + BG_POLL)); + let due = t0 + BG_POLL; + assert_eq!(poll_background(&mut next, due), (true, due + BG_POLL)); + assert_eq!(poll_background(&mut next, due), (false, due + BG_POLL)); + } + #[test] fn deleting_nodes_under_a_viewer_reconciles_it_by_name() { let mut studio = studio(); diff --git a/crates/app/src/menus.rs b/crates/app/src/menus.rs index 99d1e94db48893dae54367818ec4bfc55b26a0b7..22f8c73e2cb5aa7a21e39ed684eaae59846602b2 100644 --- a/crates/app/src/menus.rs +++ b/crates/app/src/menus.rs @@ -78,7 +78,7 @@ pub(crate) fn build_flow_toolbar( can_undo: bool, can_redo: bool, comp_unsaved: bool, - renaming_node: &Option, + renaming_node: &mut Option, rename_buf: &mut String, rename_needs_focus: &mut bool, ) -> FlowToolbarActions { @@ -184,6 +184,8 @@ pub(crate) fn build_flow_toolbar( if *rename_needs_focus { ui.set_focus(Some(rn_field_id)); *rename_needs_focus = false; + } else if !rn_sig.focused { + *renaming_node = None; } for ev in &rn_sig.events { if let ui::Event::Key { key, .. } = ev { @@ -275,12 +277,17 @@ pub(crate) fn handle_global_shortcut(studio: &mut Studio, event: &ui::Event) -> return true; } + // Canvas panes draw their own popups, which `popups_open` doesn't see. + let popup_open = studio.ui.popups_open() + || studio.add_tool.open + || studio.spline.is_popup_open() + || studio.viewers.iter().any(|v| v.is_context_menu_open()); // Shift+Space opens Add Tool launcher (when not typing in a text field) - if !typing { + if !typing && !popup_open { let is_shift_space = match event { ui::Event::KeyInput { key: Key::Named(NamedKey::Space), modifiers, state: ElementState::Pressed, repeat: false, .. } | ui::Event::Key { key: Key::Named(NamedKey::Space), modifiers, .. } => { - modifiers.shift_key() && !modifiers.super_key() && !modifiers.control_key() + modifiers.shift_key() && !modifiers.super_key() && !modifiers.control_key() && !modifiers.alt_key() } _ => false, }; @@ -292,21 +299,25 @@ pub(crate) fn handle_global_shortcut(studio: &mut Studio, event: &ui::Event) -> let is_space = match event { ui::Event::KeyInput { key: Key::Named(NamedKey::Space), modifiers, state: ElementState::Pressed, repeat: false, .. } | ui::Event::Key { key: Key::Named(NamedKey::Space), modifiers, .. } => { - !modifiers.shift_key() && !modifiers.super_key() && !modifiers.control_key() + !modifiers.shift_key() && !modifiers.super_key() && !modifiers.control_key() && !modifiers.alt_key() } _ => false, }; - if is_space && !studio.add_tool.open { + if is_space { studio.playback.toggle_play_with_comp(&studio.comp, Instant::now()); studio.sync_audio(true, false); return true; } let is_backquote = match event { - ui::Event::KeyInput { physical: PhysicalKey::Code(KeyCode::Backquote), state: ElementState::Pressed, repeat: false, .. } => true, - ui::Event::Key { key: Key::Character(c), .. } if c.as_str() == "`" || c.as_str() == "~" => true, + ui::Event::KeyInput { physical: PhysicalKey::Code(KeyCode::Backquote), modifiers, state: ElementState::Pressed, repeat: false, .. } => { + !modifiers.super_key() && !modifiers.control_key() && !modifiers.alt_key() + } + ui::Event::Key { key: Key::Character(c), modifiers, .. } => { + (c.as_str() == "`" || c.as_str() == "~") && !modifiers.super_key() && !modifiers.control_key() && !modifiers.alt_key() + } _ => false, }; - if is_backquote && !studio.add_tool.open { + if is_backquote { studio.clear_viewers(); return true; } @@ -427,6 +438,7 @@ impl Studio { self.reconcile_node_refs([None, None]); self.history.clear(); self.history.mark_saved(&self.comp); + self.spline.hidden_splines.clear(); self.engine.bust_all_caches(); self.playback.init_from_comp(&self.comp); @@ -440,7 +452,7 @@ impl Studio { } } self.flow.reset_for_comp(&self.comp); - self.flow.viewed_nodes = [self.viewers[0].viewed_node, None]; + self.flow.viewed_nodes = self.viewers.each_ref().map(|v| v.viewed_node); let default_sel = self .comp .nodes @@ -457,12 +469,11 @@ impl Studio { self.keyframes.cached_ranges.clear(); self.keyframes.fit_comp(&self.comp); self.keyframes.sync_tracks(&self.comp, default_sel); - self.viewers[0].audio_peaks.clear(); + for v in &mut self.viewers { + v.audio_peaks.clear(); + } self.ram_cache.clear(); - if let Some(pf) = &self.prefetcher { - pf.cancel(); - } - self.last_prefetch_sig = None; + self.cancel_prefetch(); self.loaded_audio_track = None; self.last_audio_offset = self.comp.audio_offset; self.last_fps = self.comp.fps; diff --git a/crates/app/src/playback_ui.rs b/crates/app/src/playback_ui.rs index dd128f886b8854fe6602203e0d20f5dc55cadac7..72a2f7cff458e41873b8f2509a6fcbc3394ed7a8 100644 --- a/crates/app/src/playback_ui.rs +++ b/crates/app/src/playback_ui.rs @@ -41,7 +41,9 @@ pub(crate) fn load_snapshot_audio_peaks(studio: &mut Studio) { studio.comp.render_range[0], studio.comp.render_range[1], ); - studio.viewers[0].audio_peaks = peaks.clone(); + for v in &mut studio.viewers { + v.audio_peaks = peaks.clone(); + } studio.keyframes.audio_peaks = peaks; studio.keyframes.audio_range = studio.comp.render_range; } @@ -62,7 +64,9 @@ impl Studio { self.comp.render_range[0], self.comp.render_range[1], ); - self.viewers[0].audio_peaks = peaks.clone(); + for v in &mut self.viewers { + v.audio_peaks = peaks.clone(); + } self.keyframes.audio_peaks = peaks; self.keyframes.audio_range = self.comp.render_range; } @@ -129,7 +133,9 @@ impl Studio { if self.comp.audio_filename != self.last_audio_filename { self.last_audio_filename = self.comp.audio_filename.clone(); self.loaded_audio_track = None; - self.viewers[0].audio_peaks.clear(); + for v in &mut self.viewers { + v.audio_peaks.clear(); + } self.keyframes.audio_peaks.clear(); if self.enable_audio { if let Some(player) = &mut self.audio_player { @@ -179,14 +185,19 @@ impl Studio { self.engine.bust_gpu_cache(); } self.ram_cache.invalidate_other_revisions(self.comp.revision); + self.cancel_prefetch(); + for v in &mut self.viewers { + v.cached_frames.clear(); + v.dirty = true; + } + } + + /// Aborts in-flight lookahead and forces the next sync to re-plan it. + pub(crate) fn cancel_prefetch(&mut self) { if let Some(pf) = &self.prefetcher { pf.cancel(); } self.last_prefetch_sig = None; - for v in &mut self.viewers { - v.cached_frames.clear(); - v.dirty = true; - } } pub(crate) fn sync_ram_ranges_and_prefetch(&mut self) { @@ -216,13 +227,14 @@ impl Studio { if let (Some(target), Some(pf)) = (target, &mut self.prefetcher) { if self.engine.cache.mode == CacheMode::Enabled { let cur_f = self.playback.current_frame.round() as i64; + let range = self.playback.effective_preview_range(&self.comp); let key = ( target, self.comp.revision, self.engine.proxy_scale, self.engine.hiq, self.engine.use_proxy_clips, - self.comp.render_range, + range, ); // Re-plan only when the job changes or the playhead leaves the half of the window // already being filled, so steady playback never re-clones the comp per frame. @@ -236,7 +248,7 @@ impl Studio { comp: self.comp.clone(), target, center_frame: cur_f, - range: self.comp.render_range, + range, lookahead: PREFETCH_LOOKAHEAD, proxy_scale: self.engine.proxy_scale, hiq: self.engine.hiq, @@ -360,8 +372,8 @@ impl Studio { } ViewerAction::BustFrame(f) => { self.engine.bust_frame(f); + self.cancel_prefetch(); self.ram_cache.clear(); - self.last_prefetch_sig = None; for v in &mut self.viewers { v.cached_frames.remove(&f); v.dirty = true; @@ -371,8 +383,8 @@ impl Studio { if let Some(id) = self.flow.primary.or(self.viewers[slot].viewed_node) { self.engine.bust_subtree(id); } + self.cancel_prefetch(); self.ram_cache.clear(); - self.last_prefetch_sig = None; for v in &mut self.viewers { v.cached_frames.clear(); v.dirty = true; @@ -380,8 +392,8 @@ impl Studio { } ViewerAction::BustGpu => { self.engine.bust_gpu_cache(); + self.cancel_prefetch(); self.ram_cache.clear(); - self.last_prefetch_sig = None; for v in &mut self.viewers { v.cached_frames.clear(); v.dirty = true; @@ -389,8 +401,8 @@ impl Studio { } ViewerAction::BustAll => { self.engine.bust_all_caches(); + self.cancel_prefetch(); self.ram_cache.clear(); - self.last_prefetch_sig = None; for v in &mut self.viewers { v.cached_frames.clear(); v.dirty = true; diff --git a/crates/flow/src/hit.rs b/crates/flow/src/hit.rs index fa9438bed82dec4e7a4bb8edebf5bff6172626f8..2f61e29cc7a12ef112327c030535e5c7d3a2e05f 100644 --- a/crates/flow/src/hit.rs +++ b/crates/flow/src/hit.rs @@ -100,23 +100,7 @@ impl FlowView { if !self.scope.shows(n) { continue; } let r = self.node_rect_local(n.pos); if local[0] >= r[0] - 10.0 && local[0] <= r[2] + 10.0 && local[1] >= r[1] - 10.0 && local[1] <= r[3] + 10.0 { - // Pick Background/Foreground/Mask cleanly based on approach edge for Merge/Displace! - if n.kind == "Merge" || n.kind == "Displace" || n.kind == "Dissolve" { - if local[1] < r[1] + 2.0 { - return Some((n.id, "Foreground")); - } - if local[1] > r[3] - 2.0 { - return Some((n.id, "EffectMask")); - } - return Some((n.id, "Background")); - } - if n.kind == "Merge3D" || n.kind == "Renderer3D" { - return Some((n.id, "SceneInput1")); - } - if local[1] > r[3] - 1.5 && n.kind != "PipeRouter" { - return Some((n.id, "EffectMask")); - } - return Some((n.id, default_main_input_port(&n.kind))); + return Some((n.id, drop_port(n, local[1] < r[1] + 2.0, local[1] > r[3] - 2.0))); } } None @@ -175,6 +159,65 @@ impl FlowView { } } +const SCENE_INPUTS: [&str; 32] = [ + "SceneInput1", "SceneInput2", "SceneInput3", "SceneInput4", "SceneInput5", "SceneInput6", "SceneInput7", "SceneInput8", + "SceneInput9", "SceneInput10", "SceneInput11", "SceneInput12", "SceneInput13", "SceneInput14", "SceneInput15", "SceneInput16", + "SceneInput17", "SceneInput18", "SceneInput19", "SceneInput20", "SceneInput21", "SceneInput22", "SceneInput23", "SceneInput24", + "SceneInput25", "SceneInput26", "SceneInput27", "SceneInput28", "SceneInput29", "SceneInput30", "SceneInput31", "SceneInput32", +]; + +const INPUTS: [&str; 33] = [ + "Input0", "Input1", "Input2", "Input3", "Input4", "Input5", "Input6", "Input7", "Input8", "Input9", "Input10", "Input11", + "Input12", "Input13", "Input14", "Input15", "Input16", "Input17", "Input18", "Input19", "Input20", "Input21", "Input22", + "Input23", "Input24", "Input25", "Input26", "Input27", "Input28", "Input29", "Input30", "Input31", "Input32", +]; + +/// Port a wire dropped on `n` lands on; `top`/`bottom` are the node's mask/foreground approach bands. +fn drop_port(n: &model::Node, top: bool, bottom: bool) -> &'static str { + let free = |names: &[&'static str]| { + names + .iter() + .copied() + .find(|p| n.inputs.get(*p).is_none_or(|b| b.source_op.is_none())) + .unwrap_or(names[names.len() - 1]) + }; + match n.kind.as_str() { + "Merge" | "Dissolve" | "ChannelBoolean" => { + if top { + "Foreground" + } else if bottom { + "EffectMask" + } else { + "Background" + } + } + "Displace" => { + if top { + "Foreground" + } else if bottom { + "EffectMask" + } else { + "Input" + } + } + "Renderer3D" | "Transform3D" | "ReplaceMaterial3D" | "Override3D" | "ReplaceNormals3D" | "Displace3D" | "Duplicate3D" => { + "SceneInput" + } + "Merge3D" => free(&SCENE_INPUTS), + "sMerge" | "pMerge" => free(&INPUTS[1..]), + "sBoolean" => free(&INPUTS[1..=2]), + "Fuse.Switch" => free(&INPUTS[1..]), + "Switch" => { + let zero_indexed = n.inputs.contains_key("Source") || n.inputs.contains_key("Input0") || !n.inputs.contains_key("Which"); + free(if zero_indexed { &INPUTS[..] } else { &INPUTS[1..] }) + } + "BitmapMask" => "Image", + "ImagePlane3D" | "TextureTransformOperator" => "MaterialInput", + kind if bottom && kind != "PipeRouter" => "EffectMask", + kind => default_main_input_port(kind), + } +} + /// Picks the closest node edge facing vector `(dx, dy)` accounting for thin rectangular bar aspect. fn closest_edge(dx: f32, dy: f32) -> Edge { // Nodes are 84x21 (4:1 aspect), so require a balanced X bias so horizontal rows snap Left/Right @@ -226,3 +269,63 @@ pub(crate) fn dist_to_seg(p: [f32; 2], a: [f32; 2], b: [f32; 2]) -> f32 { let q = [a[0] + ab[0] * t, a[1] + ab[1] * t]; ((p[0] - q[0]).powi(2) + (p[1] - q[1]).powi(2)).sqrt() } + +#[cfg(test)] +mod tests { + use super::*; + + fn port(comp: &Comp, name: &str) -> &'static str { + drop_port(comp.node(comp.find_node(name).unwrap()), false, false) + } + + fn comp(src: &str) -> Comp { + Comp::from_fusion_str(&format!("Composition {{ Tools = ordered() {{ {src} }} }}")).expect("parse comp") + } + + #[test] + fn single_input_kinds_use_engine_port_names() { + let c = comp( + "R = Renderer3D { }, D = Displace { }, CB = ChannelBoolean { }, Dis = Dissolve { }, + BM = BitmapMask { }, T = Transform3D { }, Plane = ImagePlane3D { }", + ); + assert_eq!(port(&c, "R"), "SceneInput"); + assert_eq!(port(&c, "D"), "Input"); + assert_eq!(port(&c, "CB"), "Background"); + assert_eq!(port(&c, "Dis"), "Background"); + assert_eq!(port(&c, "BM"), "Image"); + assert_eq!(port(&c, "T"), "SceneInput"); + assert_eq!(port(&c, "Plane"), "MaterialInput"); + let d = c.node(c.find_node("D").unwrap()); + assert_eq!(drop_port(d, true, false), "Foreground"); + assert_eq!(drop_port(d, false, true), "EffectMask"); + let cb = c.node(c.find_node("CB").unwrap()); + assert_eq!(drop_port(cb, true, false), "Foreground"); + } + + #[test] + fn multi_input_kinds_pick_next_free_port() { + let c = comp( + r#"A = Background { }, B = Background { }, + M3 = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "A", Source = "Output" } } }, + M3b = Merge3D { }, + S = Switch { Inputs = { Input0 = Input { SourceOp = "A", Source = "Output" } } }, + SW = Switch { Inputs = { Which = Input { Value = 1 } } }, + SB = sBoolean { Inputs = { Input1 = Input { SourceOp = "A", Source = "Output" } } }, + SB0 = sBoolean { }, + FS = Fuse.Switch { }"#, + ); + assert_eq!(port(&c, "M3b"), "SceneInput1"); + assert_eq!(port(&c, "M3"), "SceneInput2"); + assert_eq!(port(&c, "S"), "Input1"); + assert_eq!(port(&c, "SW"), "Input1"); + assert_eq!(port(&c, "SB"), "Input2"); + assert_eq!(port(&c, "SB0"), "Input1"); + assert_eq!(port(&c, "FS"), "Input1"); + } + + #[test] + fn native_switch_without_which_starts_at_input0() { + let c = comp("S = Switch { }"); + assert_eq!(port(&c, "S"), "Input0"); + } +} diff --git a/crates/flow/src/lib.rs b/crates/flow/src/lib.rs index 0667f409ef3f7aba7ed95eb700d57e891cd9c2d7..596b7a0d2215e005b2b23cf25fe85d62a2ca2f30 100644 --- a/crates/flow/src/lib.rs +++ b/crates/flow/src/lib.rs @@ -509,10 +509,11 @@ impl FlowView { if (self.modal.is_some() || self.wire_drag.is_some()) && !steering { return; } + let cmd = kmod.super_key() || kmod.control_key(); + let plain = !cmd && !kmod.alt_key(); // Shift+Space: open Add Tool launcher if kmod.shift_key() - && !kmod.super_key() - && !kmod.control_key() + && plain && matches!(key, Key::Named(NamedKey::Space)) { actions.push(FlowAction::OpenAddTool); @@ -524,12 +525,12 @@ impl FlowView { return; } if physical == Some(PhysicalKey::Code(KeyCode::Backquote)) { - self.viewed_nodes = [None, None]; - actions.push(FlowAction::ClearViewers); + if plain { + self.viewed_nodes = [None, None]; + actions.push(FlowAction::ClearViewers); + } return; } - let cmd = kmod.super_key() || kmod.control_key(); - let plain = !cmd && !kmod.alt_key(); match key { Key::Named(NamedKey::Escape) => { if self.modal.is_some() || self.wire_drag.is_some() { @@ -576,7 +577,7 @@ impl FlowView { } } Key::Character(c) => match c.to_ascii_lowercase().as_str() { - "`" | "~" => { + "`" | "~" if plain => { self.viewed_nodes = [None, None]; actions.push(FlowAction::ClearViewers); } diff --git a/crates/spline/src/lib.rs b/crates/spline/src/lib.rs index 7f982503427441f6b4e555f444bd73c58e894b9d..b91a87be5709efbe48bb6fdf9b4aa02a06f074fe 100644 --- a/crates/spline/src/lib.rs +++ b/crates/spline/src/lib.rs @@ -583,14 +583,16 @@ impl SplineView { let Some(kf) = sp.keyframes.get_mut(pref.key_idx) else { continue }; match pref.part { HandlePart::Key => { - kf.time = snap_t(piv[0] + (kf.time - piv[0]) * st); + let raw_t = piv[0] + (kf.time - piv[0]) * st; + kf.time = snap_t(raw_t); + let snap = kf.time - raw_t; kf.value = piv_val + (kf.value - piv_val) * sv; if let Some(lh) = &mut kf.lh { - lh[0] = piv[0] + (lh[0] - piv[0]) * st; + lh[0] = (piv[0] + (lh[0] - piv[0]) * st + snap).min(kf.time - 0.01); lh[1] = piv_val + (lh[1] - piv_val) * sv; } if let Some(rh) = &mut kf.rh { - rh[0] = piv[0] + (rh[0] - piv[0]) * st; + rh[0] = (piv[0] + (rh[0] - piv[0]) * st + snap).max(kf.time + 0.01); rh[1] = piv_val + (rh[1] - piv_val) * sv; } } @@ -648,8 +650,13 @@ impl SplineView { kf.flags.linear = false; } else { let nk = rot([kf.time, kf.value], sp_px, bounds); + let lh = kf.lh.map(|h| rot(h, sp_px, bounds)); + let rh = kf.rh.map(|h| rot(h, sp_px, bounds)); kf.time = snap_t(nk[0]); + let snap = kf.time - nk[0]; kf.value = nk[1]; + kf.lh = lh.map(|h| [(h[0] + snap).min(kf.time - 0.01), h[1]]); + kf.rh = rh.map(|h| [(h[0] + snap).max(kf.time + 0.01), h[1]]); } } HandlePart::LeftHandle => { @@ -716,6 +723,10 @@ impl SplineView { } } + pub fn is_popup_open(&self) -> bool { + self.popup.is_some() + } + fn popup_rect(&self, popup: &PopupMenu) -> [f32; 4] { let count = match popup.kind { PopupKind::HandleType => HANDLE_MENU_ITEMS.len(), @@ -900,7 +911,7 @@ impl SplineView { } } Key::Named(NamedKey::Delete | NamedKey::Backspace) => { - if self.delete_selected(comp, history) { + if self.modal.is_none() && self.delete_selected(comp, history) { actions.push(SplineAction::SplineEdited); } } @@ -987,7 +998,7 @@ impl SplineView { actions.push(SplineAction::SplineEdited); } } - "a" if plain => { + "a" if plain && self.modal.is_none() => { if !self.selected.is_empty() { self.selected.clear(); } else { @@ -1007,7 +1018,7 @@ impl SplineView { } } } - "l" if plain => { + "l" if plain && self.modal.is_none() => { let by_spline = self.selected_keys_by_spline(comp); if !by_spline.is_empty() { if let Some(h) = history.as_deref_mut() { @@ -1694,4 +1705,69 @@ mod tests { } assert_eq!(comp.splines["Gain"].keyframes.len(), 3); } + + #[test] + fn multi_key_rotate_carries_handles_with_their_keys() { + let mut comp = test_comp(); + { + let kfs = &mut comp.splines.get_mut("Gain").unwrap().keyframes; + kfs[0].lh = Some([-10.0, 10.0]); + kfs[0].rh = Some([10.0, 10.0]); + kfs[1].lh = Some([40.0, 110.0]); + kfs[1].rh = Some([60.0, 110.0]); + } + let orig = comp.splines["Gain"].keyframes.clone(); + let mut view = SplineView::new(&ui::Theme::dark()); + view.resize([800.0, 360.0]); + view.set_target_node(&comp, None); + view.selected.insert(key_ref(0, HandlePart::Key)); + view.selected.insert(key_ref(1, HandlePart::Key)); + + let bounds = (10.0, 110.0); + let pivot_data = [25.0, 60.0]; + let piv = view.spline_to_local(pivot_data[0], pivot_data[1], bounds); + view.pointer_local = [piv[0] + 100.0, piv[1]]; + view.begin_modal(&comp, false, TransformMode::Rotate); + let theta = 0.1_f32; + view.pointer_local = [piv[0] + 100.0 * theta.cos(), piv[1] + 100.0 * theta.sin()]; + assert!(view.apply_modal(&mut comp, true)); + + let rotated = |pt: [f64; 2]| { + let p = view.spline_to_local(pt[0], pt[1], bounds); + let (rx, ry) = (p[0] - piv[0], p[1] - piv[1]); + let np = [piv[0] + rx * theta.cos() - ry * theta.sin(), piv[1] + rx * theta.sin() + ry * theta.cos()]; + let d = view.local_to_data(np); + [d[0], display_to_value(d[1], bounds, false)] + }; + let kfs = &comp.splines["Gain"].keyframes; + for (i, o) in orig.iter().take(2).enumerate() { + for (got, want) in [(kfs[i].lh, o.lh), (kfs[i].rh, o.rh)] { + let want = rotated(want.unwrap()); + let got = got.unwrap(); + assert!((got[0] - want[0]).abs() < 1e-2 && (got[1] - want[1]).abs() < 1e-2, "key {i}: {got:?} vs {want:?}"); + } + } + } + + #[test] + fn destructive_keys_are_ignored_while_a_modal_is_active() { + let mut comp = test_comp(); + let mut view = SplineView::new(&ui::Theme::dark()); + view.resize([800.0, 360.0]); + view.set_target_node(&comp, None); + view.selected.insert(key_ref(1, HandlePart::Key)); + view.begin_modal(&comp, false, TransformMode::Grab); + let rect = [0.0, 0.0, 800.0, 360.0]; + let revision = comp.revision; + let linear = comp.splines["Gain"].keyframes[1].flags.linear; + let named = |k| ui::Event::Key { key: Key::Named(k), modifiers: ModifiersState::empty(), text: None }; + for ev in [named(NamedKey::Delete), named(NamedKey::Backspace), key_event("l"), key_event("a")] { + view.input(&mut comp, 5.0, ev, rect, [300.0, 150.0], ModifiersState::empty()); + } + assert!(view.modal.is_some()); + assert_eq!(comp.splines["Gain"].keyframes.len(), 3); + assert_eq!(view.selected, HashSet::from([key_ref(1, HandlePart::Key)])); + assert_eq!(comp.splines["Gain"].keyframes[1].flags.linear, linear); + assert_eq!(comp.revision, revision); + } } diff --git a/crates/viewer/src/gizmos.rs b/crates/viewer/src/gizmos.rs index dd642268b041d8bb7d472afa0d3b2153baf2a831..6931fb627c8f5b9a4791e8875d6b8384780f1b61 100644 --- a/crates/viewer/src/gizmos.rs +++ b/crates/viewer/src/gizmos.rs @@ -498,13 +498,14 @@ impl GizmoState { let poly_col = [0.34, 0.88, 0.98, 0.90]; let handle_col = [0.88, 0.56, 0.98, 0.75]; if pts.len() >= 2 { + let place = |dx: f64, dy: f64| rotate_about(Self::fu_to_local([p.center[0] + dx, p.center[1] + dy], img_rect), c, rad); for i in 0..pts.len() { let a = &pts[i]; let b = &pts[(i + 1) % pts.len()]; - let p0 = Self::fu_to_local([p.center[0] + a.x, p.center[1] + a.y], img_rect); - let p1 = Self::fu_to_local([p.center[0] + a.x + a.rx, p.center[1] + a.y + a.ry], img_rect); - let p2 = Self::fu_to_local([p.center[0] + b.x + b.lx, p.center[1] + b.y + b.ly], img_rect); - let p3 = Self::fu_to_local([p.center[0] + b.x, p.center[1] + b.y], img_rect); + let p0 = place(a.x, a.y); + let p1 = place(a.x + a.rx, a.y + a.ry); + let p2 = place(b.x + b.lx, b.y + b.ly); + let p3 = place(b.x, b.y); let curved = a.rx.abs() + a.ry.abs() + b.lx.abs() + b.ly.abs() > 1e-5; if curved { let mut prev = p0; @@ -526,7 +527,7 @@ impl GizmoState { push_handle_dot(&mut out, p1, 2.8, handle_col, false); } if a.lx.abs() + a.ly.abs() > 1e-4 { - let pl = Self::fu_to_local([p.center[0] + a.x + a.lx, p.center[1] + a.y + a.ly], img_rect); + let pl = place(a.x + a.lx, a.y + a.ly); out.push(Primitive::Segment { from: p0, to: pl, width: 1.0, color: handle_col }); push_handle_dot(&mut out, pl, 2.8, handle_col, false); } @@ -551,6 +552,12 @@ struct NodeGizmoParams { height: f64, } +/// Rotates screen point `p` about `c` counter-clockwise as Fusion sees it (screen Y points down). +fn rotate_about(p: [f32; 2], c: [f32; 2], rad: f32) -> [f32; 2] { + let (rx, ry) = (p[0] - c[0], p[1] - c[1]); + [c[0] + rx * rad.cos() + ry * rad.sin(), c[1] - rx * rad.sin() + ry * rad.cos()] +} + fn extract_polyline_points(comp: &Comp, node: &Node, time: f64) -> Vec { if let Some(src) = node.connected_node("Polyline") { if let Some(pts) = comp.eval_polyline_spline(src, time) { @@ -783,4 +790,10 @@ mod tests { assert!((full - 0.5).abs() < 1e-4, "full = {full}"); assert!((fine - 0.42).abs() < 1e-4, "fine = {fine}"); } + + #[test] + fn polyline_rotation_is_counter_clockwise_on_screen() { + let r = rotate_about([110.0, 50.0], [100.0, 50.0], 90.0_f32.to_radians()); + assert!((r[0] - 100.0).abs() < 1e-4 && (r[1] - 40.0).abs() < 1e-4, "{r:?}"); + } } diff --git a/crates/viewer/src/lib.rs b/crates/viewer/src/lib.rs index eff7211383fc3b415c2d7fcd4d4b7349e12e9140..5affb1c257296d2021c6fe47a7e8b4433f7e77ef 100644 --- a/crates/viewer/src/lib.rs +++ b/crates/viewer/src/lib.rs @@ -419,47 +419,42 @@ impl ViewerState { } return; } + let bare = !kmod.super_key() && !kmod.control_key() && !kmod.alt_key(); if physical == Some(PhysicalKey::Code(KeyCode::NumpadDecimal)) { self.fit(); return; } if physical == Some(PhysicalKey::Code(KeyCode::Backquote)) { - actions.push(ViewerAction::ClearViewers); + if bare { + actions.push(ViewerAction::ClearViewers); + } return; } - if physical == Some(PhysicalKey::Code(KeyCode::KeyX)) - && kmod.alt_key() - && !kmod.super_key() - && !kmod.control_key() - { + if physical == Some(PhysicalKey::Code(KeyCode::KeyX)) && kmod.alt_key() && !kmod.super_key() && !kmod.control_key() { actions.push(ViewerAction::ClearInOut); return; } match key { - Key::Named(NamedKey::Space) => actions.push(ViewerAction::TogglePlay), - Key::Named(NamedKey::ArrowLeft) => actions.push(ViewerAction::SetFrame(clock.current_frame - 1.0)), - Key::Named(NamedKey::ArrowRight) => actions.push(ViewerAction::SetFrame(clock.current_frame + 1.0)), + Key::Named(NamedKey::Space) if bare => actions.push(ViewerAction::TogglePlay), + Key::Named(NamedKey::ArrowLeft) if bare => actions.push(ViewerAction::SetFrame(clock.current_frame - 1.0)), + Key::Named(NamedKey::ArrowRight) if bare => actions.push(ViewerAction::SetFrame(clock.current_frame + 1.0)), Key::Character(c) => match c.to_ascii_lowercase().as_str() { - "`" | "~" => actions.push(ViewerAction::ClearViewers), - "i" if !kmod.super_key() && !kmod.control_key() && !kmod.alt_key() => { - actions.push(ViewerAction::SetInPoint); - } - "o" if !kmod.super_key() && !kmod.control_key() && !kmod.alt_key() => { - actions.push(ViewerAction::SetOutPoint); - } + "`" | "~" if bare => actions.push(ViewerAction::ClearViewers), + "i" if bare => actions.push(ViewerAction::SetInPoint), + "o" if bare => actions.push(ViewerAction::SetOutPoint), "x" | "≈" if kmod.alt_key() && !kmod.super_key() && !kmod.control_key() => { actions.push(ViewerAction::ClearInOut); } "f" if kmod.super_key() => self.fit(), - "f" | "." if !kmod.super_key() => self.fit(), - "0" => { + "f" | "." if !kmod.super_key() && !kmod.control_key() && !kmod.alt_key() => self.fit(), + "0" if bare => { self.fit_mode = false; self.zoom = 1.0; self.pan = [0.0, 0.0]; self.dirty = true; } - "[" => actions.push(ViewerAction::SetFrame(clock.current_frame - 1.0)), - "]" => actions.push(ViewerAction::SetFrame(clock.current_frame + 1.0)), + "[" if bare => actions.push(ViewerAction::SetFrame(clock.current_frame - 1.0)), + "]" if bare => actions.push(ViewerAction::SetFrame(clock.current_frame + 1.0)), _ => {} }, _ => {} @@ -576,7 +571,9 @@ impl ViewerState { let factor = (1.0 + delta).clamp(0.7, 1.4); self.zoom_at(comp, factor, self.pointer_local); } - ui::Event::KeyInput { physical, key, state: ElementState::Pressed, repeat: false, modifiers: kmod, .. } => { + ui::Event::KeyInput { physical, key, state: ElementState::Pressed, repeat, modifiers: kmod, .. } + if !repeat || matches!(key, Key::Named(NamedKey::ArrowLeft | NamedKey::ArrowRight)) => + { self.handle_key(clock, Some(physical), &key, kmod, &mut actions); } ui::Event::Key { key, modifiers: kmod, .. } => { @@ -775,4 +772,34 @@ mod tests { assert!(matches!(run(&mut viewer, false).as_slice(), [ViewerAction::SetInPoint])); assert!(run(&mut viewer, true).is_empty()); } + + #[test] + fn arrows_repeat_and_modified_keys_do_not_trigger_single_key_bindings() { + let comp = test_comp(); + let mut clock = PlaybackClock::new(); + clock.init_from_comp(&comp); + let theme = ui::Theme::new(&theme::KNIFE, true); + let mut viewer = ViewerState::new(0, &theme); + let ev = |physical, key: Key, modifiers, repeat| ui::Event::KeyInput { + physical: PhysicalKey::Code(physical), + key: key.clone(), + text: None, + unshifted: key, + modifiers, + state: ElementState::Pressed, + repeat, + }; + let rect = [0.0, 0.0, 640.0, 400.0]; + let mut run = |e| viewer.input(&comp, &clock, e, rect, [0.0, 0.0], ModifiersState::empty()); + let right = Key::Named(NamedKey::ArrowRight); + assert_eq!(run(ev(KeyCode::ArrowRight, right, ModifiersState::empty(), true)).len(), 1); + let cmd = ModifiersState::SUPER; + assert!(run(ev(KeyCode::Backquote, Key::Character("`".into()), cmd, false)).is_empty()); + assert!(run(ev(KeyCode::Space, Key::Named(NamedKey::Space), cmd, false)).is_empty()); + let bare = ModifiersState::empty(); + assert!(matches!( + run(ev(KeyCode::Backquote, Key::Character("`".into()), bare, false)).as_slice(), + [ViewerAction::ClearViewers] + )); + } }