Issue fixes: #591 GPU allocation and device loss, #553 motion-path vertex tools, #488 rename focus, #511 macOS sheet dialogs, #500 MCP file confinement, #343 desktop shortcut

This commit is contained in:
Claude
2026-10-10 23:06:04 +00:00
27 changed files with 1098 additions and 79 deletions
+82 -2
View File
@@ -98,6 +98,39 @@ pub enum Dialog {
/// winit no theme). `None` = the host does not know.
pub type SystemThemeFn = Box<dyn Fn(&egui::Context) -> Option<egui::Theme>>;
/// A file dialog a host shows without blocking the frame ([`Hooks::file_dialog_async`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FileDialog {
/// Files to open or import with these extensions; several when `many`.
Open { exts: Vec<String>, many: bool },
/// An EffectCraft project to open.
OpenProject,
/// A folder.
Folder,
/// Where to save `default` (a file name or path) with extension `ext` (empty: no filter);
/// `project`: the project save dialog, given the file name.
Save { default: String, ext: String, project: bool },
}
impl FileDialog {
/// The save dialog for `default`, as [`Hooks::save_dialog`] picks it.
pub fn save(default: &str) -> Self {
let ext = std::path::Path::new(default).extension().map(|e| e.to_string_lossy().to_string()).unwrap_or_default();
Self::Save { default: default.to_string(), project: ext.eq_ignore_ascii_case("ecproj"), ext }
}
}
/// Called with the paths a [`FileDialog`] picked (empty: cancelled), from any thread.
pub type DialogDone = Box<dyn FnOnce(Vec<String>) + Send>;
/// A non-blocking file dialog's answer for the command that asked (`menus::dialog_answered`).
pub(crate) struct DialogAnswer {
pub command: String,
pub key: &'static str,
pub params: serde_json::Value,
pub paths: Vec<String>,
}
/// Host hooks provided by the native app (file pickers etc.).
#[derive(Default)]
pub struct Hooks {
@@ -121,6 +154,11 @@ pub struct Hooks {
/// Application actions the OS performs (`app.hide`, `app.hideOthers`, `app.showAll` on
/// macOS). Returns false when the host doesn't handle the id.
pub app_action: Option<Box<dyn Fn(&str) -> bool>>,
/// Shows a command's file dialog without blocking the frame and calls `done` with the
/// answer (the host then asks for a repaint). Used in place of the blocking pickers above for
/// the commands' dialogs (File ▸ Import, Open, Save As…) where a modal dialog's nested event
/// loop inside a frame is unsafe: on macOS a drag over the window then aborted the app (#511).
pub file_dialog_async: Option<Box<dyn Fn(FileDialog, DialogDone)>>,
}
impl Hooks {
@@ -261,6 +299,11 @@ pub struct EffectcraftApp {
gpu_checked: bool,
gpu_failures: Option<gpu_failure::GpuFailureBridge>,
gpu_failure_applied: Option<bool>,
/// The graphics device was lost and the window is closing (see `close_after_device_loss`);
/// `true` keeps crash recovery for the next launch.
device_lost_close: Option<bool>,
/// Answers of file dialogs shown without blocking ([`Hooks::file_dialog_async`]).
pub(crate) dialog_answers: (Sender<DialogAnswer>, Receiver<DialogAnswer>),
/// Commands from the native menu bar.
pub command_inbox: Option<Receiver<String>>,
/// Pointer position in comp pixels (Info panel).
@@ -347,6 +390,8 @@ impl EffectcraftApp {
gpu_checked: false,
gpu_failures: None,
gpu_failure_applied: None,
device_lost_close: None,
dialog_answers: std::sync::mpsc::channel(),
command_inbox: None,
pointer_comp: None,
dialog_state: Default::default(),
@@ -643,6 +688,33 @@ impl EffectcraftApp {
ctx.request_repaint();
}
/// After the graphics device is lost, eframe's renderer cannot draw again: any mesh makes
/// egui-wgpu panic on the main thread when it cannot stage its index buffer (#591). Draw
/// nothing from then on, auto-save a project with unsaved changes (keeping the crash
/// recovery marker, so the next launch offers it) and close the window.
fn close_after_device_loss(&mut self, ctx: &egui::Context) {
if self.device_lost_close.is_some() {
return;
}
let keep_recovery = self.session.is_dirty();
if keep_recovery {
match self.session.autosave_now().and_then(|path| self.session.autosave_wait().map(|()| path)) {
Ok(path) => log::warn!("graphics device lost: auto-saved {path}; the next launch offers to recover it"),
Err(e) => log::error!("graphics device lost: {e}"),
}
}
self.device_lost_close = Some(keep_recovery);
log::warn!("graphics device lost: closing the window");
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
/// Run the commands whose non-blocking file dialogs have been answered.
pub(crate) fn run_dialog_answers(&mut self) {
while let Ok(answer) = self.dialog_answers.1.try_recv() {
menus::dialog_answered(self, answer);
}
}
/// Set up the GPU compositor on egui-wgpu's device (once). Without an adapter that runs
/// compute shaders (WebGL2, software GL) everything stays on the CPU.
pub(crate) fn init_gpu(&mut self, frame: &eframe::Frame) {
@@ -1483,6 +1555,7 @@ impl EffectcraftApp {
fn frame(&mut self, ui: &mut egui::Ui) {
let ctx = ui.ctx().clone();
self.apply_gpu_failure(&ctx);
self.run_dialog_answers();
self.auto.begin_frame();
self.frames.set_context(&ctx);
if self.session.render_job.is_some() {
@@ -1672,8 +1745,11 @@ impl EffectcraftApp {
impl eframe::App for EffectcraftApp {
fn on_exit(&mut self) {
// Clean exit: no crash recovery next launch.
self.session.end_recovery();
// Clean exit: no crash recovery next launch (unless the graphics device was lost with
// unsaved changes, which are in the auto-save it offers).
if self.device_lost_close != Some(true) {
self.session.end_recovery();
}
}
fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
@@ -1732,6 +1808,10 @@ impl eframe::App for EffectcraftApp {
}
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
if self.gpu_failure_applied == Some(true) {
self.close_after_device_loss(ui.ctx());
return;
}
self.init_gpu(frame);
if !self.fonts_ready {
ui.ctx().request_repaint();
+87 -12
View File
@@ -1200,7 +1200,31 @@ fn file_dialog(app: &mut EffectcraftApp, id: &str, params: &Value) -> Option<Res
{
return None;
}
let mut p = params.as_object().cloned().unwrap_or_default();
const MEDIA: &[&str] = &[
"mp4", "mov", "m4v", "mkv", "webm", "png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "wav", "aif", "aiff", "mp3", "flac", "ogg",
"opus", "svg", "pdf", "ai", "eps", "psd", "psb", "gltf", "glb", "obj", "json", "csv", "tsv",
];
// A host whose modal dialogs would run a nested event loop inside this frame (macOS: a
// drag over the window then re-entered winit's event handler and aborted, #511) shows the
// dialog without blocking; the command continues when the answer arrives.
if let Some(spawn) = app.hooks.file_dialog_async.as_ref() {
let request = match ask {
Ask::Folder => crate::FileDialog::Folder,
Ask::Import => crate::FileDialog::Open { exts: MEDIA.iter().map(|e| e.to_string()).collect(), many: key == "paths" },
Ask::OpenProject => crate::FileDialog::OpenProject,
Ask::Open(exts) => crate::FileDialog::Open { exts: exts.iter().map(|e| e.to_string()).collect(), many: false },
Ask::Save(default) => crate::FileDialog::save(default),
};
let tx = app.dialog_answers.0.clone();
let answer = crate::DialogAnswer { command: id.to_string(), key, params: params.clone(), paths: Vec::new() };
spawn(
request,
Box::new(move |paths| {
let _ = tx.send(crate::DialogAnswer { paths, ..answer });
}),
);
return Some(Ok(json!({"dialog": id})));
}
let picked: Option<Value> = match ask {
Ask::Folder => {
let Some(f) = app.hooks.pick_folder.as_ref() else { return Some(Err("no folder dialog available (pass `folder`)".into())) };
@@ -1208,15 +1232,7 @@ fn file_dialog(app: &mut EffectcraftApp, id: &str, params: &Value) -> Option<Res
}
Ask::Import => {
let Some(f) = app.hooks.pick_files.as_ref() else { return Some(Err("no file dialog available (pass `paths`)".into())) };
let paths = f(&[
"mp4", "mov", "m4v", "mkv", "webm", "png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "wav", "aif", "aiff", "mp3", "flac",
"ogg", "opus", "svg", "pdf", "ai", "eps", "psd", "psb", "gltf", "glb", "obj", "json", "csv", "tsv",
]);
match (paths.is_empty(), key) {
(true, _) => None,
(false, "paths") => Some(json!(paths)),
(false, _) => paths.first().map(|s| json!(s)),
}
picked_value(key, f(MEDIA))
}
Ask::OpenProject => {
let Some(f) = app.hooks.pick_open_project.as_ref() else { return Some(Err("no file dialog available (pass `path`)".into())) };
@@ -1232,6 +1248,30 @@ fn file_dialog(app: &mut EffectcraftApp, id: &str, params: &Value) -> Option<Res
}
};
let Some(v) = picked else { return Some(Ok(Value::Null)) };
Some(run_with_picked(app, id, key, params, v))
}
/// The dialog's answer as the command's `key` parameter (`None`: cancelled).
fn picked_value(key: &str, paths: Vec<String>) -> Option<Value> {
match (paths.is_empty(), key) {
(true, _) => None,
(false, "paths") => Some(json!(paths)),
(false, _) => paths.into_iter().next().map(Value::from),
}
}
/// A file dialog shown without blocking ([`crate::Hooks::file_dialog_async`]) answered: run its
/// command with the picked path (nothing when it was cancelled).
pub(crate) fn dialog_answered(app: &mut EffectcraftApp, answer: crate::DialogAnswer) {
let Some(v) = picked_value(answer.key, answer.paths) else { return };
if let Err(e) = run_with_picked(app, &answer.command, answer.key, &answer.params, v) {
app.ui.status = e;
}
}
/// Run command `id` with the path picked for it in parameter `key`.
fn run_with_picked(app: &mut EffectcraftApp, id: &str, key: &str, params: &Value, v: Value) -> Result<Value, String> {
let mut p = params.as_object().cloned().unwrap_or_default();
p.insert(key.to_string(), v);
// Picked files import in the background, with the Importing card showing progress (#270).
if matches!(id, "file.import" | "file.importMultiple") {
@@ -1243,7 +1283,7 @@ fn file_dialog(app: &mut EffectcraftApp, id: &str, params: &Value) -> Option<Res
if id == "file.import" && crate::panels::dialogs::open_form(app, id, &picked)
|| matches!(id, "file.import" | "file.importMultiple") && crate::panels::forms::open_import_sequence(app, &picked)
{
return Some(Ok(json!({"dialog": id})));
return Ok(json!({"dialog": id}));
}
// Save (untitled) becomes Save As.
let id = if id == "file.save" { "file.saveAs" } else { id };
@@ -1251,7 +1291,7 @@ fn file_dialog(app: &mut EffectcraftApp, id: &str, params: &Value) -> Option<Res
if let Err(e) = &r {
app.ui.status = e.clone();
}
Some(r)
r
}
/// A menu entry for display / `ui.menu.list`.
@@ -1981,6 +2021,41 @@ mod tests {
assert_eq!(*asked.borrow(), ["project Frame.png"]);
}
/// #511: with a host's non-blocking dialogs, a command's file dialog opens without running
/// a nested event loop inside the frame (a drag over the window then aborted the app on
/// macOS); the command runs on a later frame with the answer, and a cancelled one not at all.
#[test]
fn file_dialogs_can_answer_on_a_later_frame() {
use std::sync::{Arc, Mutex};
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
app.session.execute("comp.new", json!({"name": "A", "width": 64, "height": 36, "frameRate": 30, "duration": 1})).unwrap();
let ctx = egui::Context::default();
app.hooks.pick_save = Some(Box::new(|_: &str| panic!("the blocking dialog is not used")));
let pending: Arc<Mutex<Vec<(crate::FileDialog, crate::DialogDone)>>> = Arc::default();
let queue = pending.clone();
app.hooks.file_dialog_async = Some(Box::new(move |dialog, done| queue.lock().unwrap().push((dialog, done))));
assert_eq!(invoke(&mut app, &ctx, "file.saveAs", json!({})).unwrap(), json!({"dialog": "file.saveAs"}));
let (dialog, done) = pending.lock().unwrap().pop().expect("a dialog was shown");
assert_eq!(dialog, crate::FileDialog::Save { default: "Untitled Project.ecproj".into(), ext: "ecproj".into(), project: true });
assert!(app.session.path.is_none(), "nothing saved until the dialog answers");
let dir = std::env::temp_dir().join(format!("ec-dialog-answer-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("Answered.ecproj");
// Answered from another thread, as the host's dialog does.
std::thread::spawn(move || done(vec![path.to_string_lossy().to_string()])).join().unwrap();
app.run_dialog_answers();
assert_eq!(app.session.path.as_deref(), Some(dir.join("Answered.ecproj").to_string_lossy().as_ref()));
assert!(dir.join("Answered.ecproj").is_file());
// Cancelled: nothing runs.
invoke(&mut app, &ctx, "comp.saveFrameAs", json!({})).unwrap();
let (dialog, done) = pending.lock().unwrap().pop().expect("a dialog was shown");
assert_eq!(dialog, crate::FileDialog::Save { default: "Frame.png".into(), ext: "png".into(), project: false });
done(Vec::new());
app.run_dialog_answers();
assert!(!dir.join("Frame.png").exists());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn menu_items_cover_the_tree() {
assert_eq!(menus().last(), Some(&"Help"));
+87 -5
View File
@@ -872,6 +872,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let mut handle_hits: Vec<(LayerId, usize, Pos2, egui::CursorIcon)> = Vec::new();
let mut vertex_hits: Vec<VertexHit> = Vec::new();
let mut key_hits: Vec<ov::KeyHit> = Vec::new();
let mut motion_frames: Vec<ov::PathFrame> = Vec::new();
let mut paths: Vec<ov::PathInfo> = Vec::new();
let sel_vertices = app.session.state.selected_vertices.clone();
// Pen path in progress ends when the tool changes or its mask is gone; Esc / Enter also end
@@ -891,7 +892,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
for l in comp.layers.iter().filter(|l| selected.contains(&l.id) && l.is_active_at(time)) {
let col = if label_handles { t.label(l.label) } else { t.accent };
// Motion path of animated position (keyframes and spatial tangents are draggable).
ov::motion_path(app, &painter, &map, &ectx, l, col, &mut key_hits);
ov::motion_path(app, &painter, &map, &ectx, l, col, &mut key_hits, &mut motion_frames);
// Masks and shape paths.
if app.ui.viewer.show_masks {
let pen = ui.data(|d| d.get_temp::<(LayerId, u64)>(pen_id()));
@@ -1153,7 +1154,15 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
Tool::Orbit => egui::CursorIcon::Alias,
Tool::PanCamera => egui::CursorIcon::Move,
Tool::Dolly => egui::CursorIcon::ResizeVertical,
t if t.is_shape() || t.is_pen() => egui::CursorIcon::Crosshair,
t if t.is_pen() => {
pen_cursor(
&ctx,
hp,
pen_cursor_icon(t, ov::segment_at(&paths, &map, hp, 5.0).is_some() || ov::motion_frame_at(&motion_frames, &key_hits, hp).is_some()),
);
egui::CursorIcon::None
}
t if t.is_shape() => egui::CursorIcon::Crosshair,
_ if app.ui.viewer.roi_draw => egui::CursorIcon::Crosshair,
t if t.puppet_kind().is_some() => match super::puppet_tool::hit(&pin_hits, hp) {
Some((_, super::puppet_tool::PinPart::Ring)) => egui::CursorIcon::Alias,
@@ -1201,7 +1210,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
&& ui.input(|i| i.pointer.primary_pressed())
&& let Some(pos) = ui.input(|i| i.pointer.press_origin())
{
pen_press(app, ui, &ectx, &map, &paths, pos, mods);
pen_press(app, ui, &ectx, &map, &paths, ov::motion_frame_at(&motion_frames, &key_hits, pos), pos, mods);
}
// A pen click (press + release without a drag) ends its tangent gesture on release.
if ui.input(|i| i.pointer.primary_released())
@@ -1703,19 +1712,35 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
Tool::Type | Tool::TypeVertical => {}
Tool::Pen | Tool::MaskFeather => {}
// On a motion path (After Effects): Add Vertex adds a keyframe where it is clicked,
// Delete Vertex removes the keyframe, Convert Vertex switches it between Linear and
// Auto Bezier spatial interpolation.
Tool::PenAdd => {
if let Some((l, m, seg, tt)) = ov::segment_at(&paths, &map, pos, 6.0) {
let _ = app.session.execute("mask.insertVertex", json!({"layer": l.0, "mask": m, "segment": seg, "t": tt}));
} else if let Some(f) = ov::motion_frame_at(&motion_frames, &key_hits, pos) {
add_motion_key(app, f);
}
}
Tool::PenDelete => {
if let Some(h) = vertex_at(pos, false) {
let _ = app.session.execute("mask.deleteVertices", json!({"vertices": [{"layer": h.layer.0, "mask": h.mask, "index": h.index}]}));
} else if let Some(k) = ov::motion_key_at(&key_hits, pos)
&& select_motion_key(app, &k)
{
let _ = app.session.execute("keys.delete", json!({}));
}
}
Tool::PenConvert => {
if let Some(h) = vertex_at(pos, false) {
let _ = app.session.execute("mask.convertVertex", json!({"layer": h.layer.0, "mask": h.mask, "index": h.index}));
} else if let Some(k) = ov::motion_key_at(&key_hits, pos) {
// A key showing direction handles becomes Linear; one without, Auto Bezier.
let curved = key_hits.iter().any(|h| h.tangent.is_some() && h.layer == k.layer && h.prop == k.prop && h.time == k.time);
if select_motion_key(app, &k) {
let spatial = if curved { "linear" } else { "autoBezier" };
let _ = app.session.execute("keys.interpolation", json!({"spatial": spatial}));
}
}
}
Tool::Selection if mods.alt && vertex_at(pos, false).is_some() => {
@@ -1907,7 +1932,60 @@ fn draw_rigs(app: &mut EffectcraftApp, painter: &egui::Painter, map: &ViewerMap,
/// footage/solid layer (or shape layer, with Tool Creates Mask), a shape path (Shape n group with
/// the Tools bar's Fill and Stroke) on the selected shape layer, or a new shape layer when
/// nothing is selected. The placed point snaps.
fn pen_press(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, map: &ViewerMap, paths: &[ov::PathInfo], pos: Pos2, mods: egui::Modifiers) {
/// Add a Position keyframe at a motion path's frame, keeping the path where it is.
fn add_motion_key(app: &mut EffectcraftApp, f: ov::PathFrame) {
if let Err(e) = app.session.execute("prop.addKey", json!({"layer": f.layer.0, "prop": f.prop, "time": f.time.seconds()})) {
app.ui.status = e.to_string();
}
}
/// Select only the motion path's keyframe `k` (what the vertex tools act on).
fn select_motion_key(app: &mut EffectcraftApp, k: &ov::KeyHit) -> bool {
app.session.execute("keys.select", json!({"keys": [{"layer": k.layer.0, "prop": k.prop, "time": k.time.seconds()}]})).is_ok()
}
/// The pointer for a Pen slot tool: the tool's own pen, the Pen showing Add Vertex's over a path
/// it would add a point to (After Effects).
fn pen_cursor_icon(tool: Tool, over_path: bool) -> crate::icons::Icon {
use crate::icons::Icon;
match tool {
Tool::Pen if over_path => Icon::PenAdd,
Tool::PenAdd => Icon::PenAdd,
Tool::PenDelete => Icon::PenDelete,
Tool::PenConvert => Icon::PenConvert,
Tool::MaskFeather => Icon::MaskFeather,
_ => Icon::Pen,
}
}
/// Paint pen pointer `icon` with its tip at `at`, outlined for any background.
fn pen_cursor(ctx: &egui::Context, at: Pos2, icon: crate::icons::Icon) {
use crate::icons::Icon;
// Where each glyph's tip sits in its 16 × 16 box.
let tip = match icon {
Icon::PenAdd | Icon::PenDelete | Icon::MaskFeather => vec2(6.0, 2.5),
Icon::PenConvert => vec2(8.0, 3.5),
_ => vec2(8.0, 1.8),
};
let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("viewer-pen-cursor")));
let rect = Rect::from_min_size(at - tip, vec2(16.0, 16.0));
for d in [vec2(-1.0, 0.0), vec2(1.0, 0.0), vec2(0.0, -1.0), vec2(0.0, 1.0)] {
crate::icons::paint(&painter, rect.translate(d), icon, Color32::BLACK);
}
crate::icons::paint(&painter, rect, icon, Color32::WHITE);
}
#[allow(clippy::too_many_arguments)]
fn pen_press(
app: &mut EffectcraftApp,
ui: &mut egui::Ui,
ectx: &EvalCtx,
map: &ViewerMap,
paths: &[ov::PathInfo],
motion_frame: Option<ov::PathFrame>,
pos: Pos2,
mods: egui::Modifiers,
) {
use effectcraft_engine::project::LayerSource;
let gid = egui::Id::new("viewer-gesture");
let current: Option<(LayerId, u64)> = ui.data(|d| d.get_temp(pen_id()));
@@ -1939,7 +2017,11 @@ fn pen_press(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, map: &
}
return;
}
// On a visible path's segment the Pen adds a vertex there.
// On a visible path's segment the Pen adds a vertex there; on a motion path, a keyframe.
if let Some(f) = motion_frame {
add_motion_key(app, f);
return;
}
if let Some((l, m, seg, t)) = ov::segment_at(paths, map, pos, 5.0) {
let _ = app.session.execute("mask.insertVertex", json!({"layer": l.0, "mask": m, "segment": seg, "t": t}));
return;
+40 -2
View File
@@ -248,6 +248,32 @@ pub(crate) struct KeyHit {
pub p2c: Mat3,
}
/// A frame on a motion path (one of its dots): where the Pen and Add Vertex tools add a
/// keyframe.
#[derive(Clone, Copy)]
pub(crate) struct PathFrame {
pub layer: LayerId,
pub prop: u64,
/// Layer time of the frame.
pub time: Tick,
pub pos: Pos2,
}
/// The keyframe dot on a motion path under `pos`.
pub(crate) fn motion_key_at(hits: &[KeyHit], pos: Pos2) -> Option<KeyHit> {
hits.iter().rev().find(|h| h.tangent.is_none() && h.pos.distance(pos) < 6.0).copied()
}
/// The motion-path frame nearest `pos` (within a few points) where a keyframe can be added: not
/// on a keyframe dot already there.
pub(crate) fn motion_frame_at(frames: &[PathFrame], hits: &[KeyHit], pos: Pos2) -> Option<PathFrame> {
if motion_key_at(hits, pos).is_some() {
return None;
}
let near = frames.iter().filter(|f| f.pos.distance(pos) < 5.0).min_by(|a, b| a.pos.distance(pos).total_cmp(&b.pos.distance(pos)))?;
(!hits.iter().any(|h| h.tangent.is_none() && h.layer == near.layer && h.prop == near.prop && h.time == near.time)).then_some(*near)
}
/// Parent space → comp matrix of a 2D layer at the context time.
pub(crate) fn parent_to_comp(ectx: &EvalCtx, l: &Layer) -> Mat3 {
match l.parent.and_then(|p| ectx.comp.layer(p)) {
@@ -261,7 +287,17 @@ pub(crate) fn parent_to_comp(ectx: &EvalCtx, l: &Layer) -> Mat3 {
/// Draw the position motion path of a selected 2D layer: frame dots along the path, keyframe
/// squares (filled when selected) and spatial Bezier tangent handles. Works through parents.
pub(crate) fn motion_path(app: &mut EffectcraftApp, painter: &egui::Painter, map: &ViewerMap, ectx: &EvalCtx, l: &Layer, col: Color32, hits: &mut Vec<KeyHit>) {
#[allow(clippy::too_many_arguments)]
pub(crate) fn motion_path(
app: &mut EffectcraftApp,
painter: &egui::Painter,
map: &ViewerMap,
ectx: &EvalCtx,
l: &Layer,
col: Color32,
hits: &mut Vec<KeyHit>,
frames: &mut Vec<PathFrame>,
) {
let Some(pos) = l.transform().and_then(|tr| tr.get("position")) else { return };
if pos.keys.len() < 2 || l.is_3d() {
return;
@@ -278,7 +314,9 @@ pub(crate) fn motion_path(app: &mut EffectcraftApp, painter: &egui::Painter, map
let mut pts = vec![];
let mut lt = lt0;
while lt <= lt1 && pts.len() < 20_000 {
pts.push(to_scr(pos.value_at(lt).as_vec3()));
let q = to_scr(pos.value_at(lt).as_vec3());
frames.push(PathFrame { layer: l.id, prop: pos.uid, time: lt, pos: q });
pts.push(q);
lt += fd;
}
pts.push(to_scr(pos.value_at(lt1).as_vec3()));
+57 -4
View File
@@ -165,12 +165,24 @@ pub fn drag_value(value: egui::DragValue<'_>) -> impl egui::Widget {
}
/// Keep the keyboard on an inline editor that is open until it loses the focus. The frame it
/// opens (it has no focus yet) its whole `text` is selected, so typing replaces the value.
/// (Only then is the focus requested: a request resets what keys the field keeps for itself,
/// such as Tab with [`egui::TextEdit::lock_focus`].)
/// opens its whole `text` is selected, so typing replaces the value; after that the caret is the
/// user's (arrow keys move it), even if the field is without the focus for a frame (#488).
/// (The focus is only requested while the field doesn't have it: a request resets what keys the
/// field keeps for itself, such as Tab with [`egui::TextEdit::lock_focus`].)
pub fn keep_focus(ctx: &egui::Context, field: &Response, text: &str) {
// The editor is open in consecutive passes; a gap means it was closed and opened again.
let shown = field.id.with("keep-focus-pass");
let pass = ctx.cumulative_pass_nr();
let previous = ctx.data_mut(|d| {
let previous = d.get_temp::<u64>(shown);
d.insert_temp(shown, pass);
previous
});
let opening = previous.is_none_or(|p| p.saturating_add(1) < pass);
if !ctx.memory(|m| m.has_focus(field.id)) {
select_all(ctx, field.id, text);
if opening {
select_all(ctx, field.id, text);
}
field.request_focus();
}
}
@@ -592,6 +604,47 @@ pub(crate) fn constrained(c: &[f64], d: usize, v: f64) -> Vec<f64> {
mod tests {
use super::*;
/// #488: an inline editor selects its whole text only as it opens. Should it be without the
/// keyboard for a frame later (an input method, another handler), it takes the keyboard back
/// with the caret where the user put it instead of selecting everything again, which made
/// the arrows seem dead and Backspace erase the whole name.
#[test]
fn inline_editors_select_all_only_as_they_open() {
let ctx = egui::Context::default();
let mut text = String::from("Comp 1");
let mut id = egui::Id::NULL;
let frame = |ctx: &egui::Context, text: &mut String, id: &mut egui::Id| {
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
let r = ui.add(egui::TextEdit::singleline(text));
keep_focus(ui.ctx(), &r, text);
*id = r.id;
});
out.textures_delta.clear();
};
let range = |ctx: &egui::Context, id: egui::Id| egui::TextEdit::load_state(ctx, id).and_then(|s| s.cursor.char_range());
let ix = |n: usize| egui::text::CCursor::new(n).index;
frame(&ctx, &mut text, &mut id);
frame(&ctx, &mut text, &mut id);
let all = range(&ctx, id).unwrap();
assert_eq!((all.primary.index.min(all.secondary.index), all.primary.index.max(all.secondary.index)), (ix(0), ix(6)), "opened with all selected");
// The caret after "Co", then a frame without the keyboard.
let mut state = egui::TextEdit::load_state(&ctx, id).unwrap();
state.cursor.set_char_range(Some(egui::text::CCursorRange::one(egui::text::CCursor::new(2))));
state.store(&ctx, id);
ctx.memory_mut(|m| m.surrender_focus(id));
frame(&ctx, &mut text, &mut id);
frame(&ctx, &mut text, &mut id);
assert!(ctx.memory(|m| m.has_focus(id)), "the editor keeps the keyboard");
let r = range(&ctx, id).unwrap();
assert_eq!((r.primary.index, r.secondary.index), (ix(2), ix(2)), "the caret stays where it was");
// Closed for a frame and opened again: all selected again.
ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear();
frame(&ctx, &mut text, &mut id);
frame(&ctx, &mut text, &mut id);
let r = range(&ctx, id).unwrap();
assert_eq!((r.primary.index.min(r.secondary.index), r.primary.index.max(r.secondary.index)), (ix(0), ix(6)));
}
/// #581: a field's text edit fills it, so its text and hint sit on the field's middle line
/// (it was a row at the top of the field, its text high).
#[test]