EffectCraft: An open-source motion graphics and compositing tool written by scratch in pure Rust
Merge main into fix/1436-gradient-editor-preview
Claudede7c5760c8cd
diff --cc crates/ui-egui/src/app/frame.rsindex 000000000,d41e0a9d0..85041be2emode 000000,100644..100644--- a/crates/ui-egui/src/app/frame.rs+++ b/crates/ui-egui/src/app/frame.rs@@@ -1,0 -1,553 +1,558 @@@+ use super::clipboard::copy_image;+ use super::window::fit_window;+ use super::*;++ impl EffectcraftApp {+ /// Completed, non-discarded UI passes since launch.+ pub fn ui_passes(&self) -> u64 {+ self.ui_pass_seq+ }++ // ---------------------------------------------------------------- control channel++ pub(crate) fn raise_for_control(&mut self, ctx: &egui::Context) {+ ctx.request_repaint();+ }++ /// Handle the control channel for this tick: drain queued requests plus previously deferred ones, run each+ /// through `control::handle`, answer `Done` immediately, retry `Retry` until its three-second deadline, hold+ /// input/job/screenshot replies until their event happens and finish job waiters. Retry timeouts and refused+ /// screenshots are answered as `{"ok": false, "error": ...}`; the receiver is kept for the next tick.+ fn drain_control(&mut self, ctx: &egui::Context, now: f64) {+ let Some(rx) = self.control_rx.take() else { return };+ let mut reqs: Vec<(ControlRequest, f64)> = std::mem::take(&mut self.deferred);+ while let Ok(req) = rx.try_recv() {+ reqs.push((req, now + 3.0));+ }+ for (req, deadline) in reqs {+ let reply = req.reply.clone();+ match control::handle(self, ctx, &req, now) {+ control::Outcome::Done(v) => {+ let _ = reply.send(v);+ }+ control::Outcome::Retry(msg) => {+ if now < deadline {+ self.deferred.push((req, deadline));+ ctx.request_repaint();+ } else {+ let _ = reply.send(json!({"ok": false, "error": msg}));+ }+ }+ control::Outcome::AfterInput => {+ self.input_waiters.push(reply);+ // The reply waits for a real UI pass: a hidden window must run one.+ self.want_paint = true;+ }+ control::Outcome::AwaitJobs(w) => {+ self.job_waiters.push((w, reply));+ ctx.request_repaint();+ }+ control::Outcome::Screenshot { path, target } => {+ // A covered or minimized window presents no frames (macOS skips its redraws), so+ // a screenshot would never arrive and nothing would tick its timeout. The+ // hidden-window capture path (a pending screenshot forces a pass in 0.37) needs+ // a native platform run before this gate is removed; the web build never paints+ // a hidden tab.+ if ctx.input(|i| i.viewport().occluded == Some(true) || i.viewport().minimized == Some(true)) {+ let _ = reply.send(json!({"ok": false, "error": "window is covered or minimized: call ui.focus first (render.frame renders comp pixels without the window)"}));+ continue;+ }+ self.admit_screenshot(ctx, path, target, reply);+ }+ }+ }+ self.control_rx = Some(rx);+ self.finish_job_waiters(ctx);+ }++ /// Reply to the control requests whose offloaded jobs ended.+ fn finish_job_waiters(&mut self, ctx: &egui::Context) {+ if self.job_waiters.is_empty() {+ return;+ }+ self.session.poll_render();+ self.session.poll_offload();+ let waiters = std::mem::take(&mut self.job_waiters);+ for (w, reply) in waiters {+ if w.pending(self) {+ self.job_waiters.push((w, reply));+ } else {+ let v = w.finish(self);+ let _ = reply.send(v);+ }+ }+ if !self.job_waiters.is_empty() {+ ctx.request_repaint_after(std::time::Duration::from_millis(50));+ }+ }++ // ---------------------------------------------------------------- frame++ /// Apply the engine events drained this tick: open a comp, show a toast, open a URL, run a frontend command,+ /// purge frame caches or copy an image; command and clipboard failures go to `app.ui.status`.+ pub(super) fn handle_events(&mut self, ctx: &egui::Context) {+ for ev in self.session.drain_events() {+ match ev {+ effectcraft_engine::Event::OpenComp(c) => {+ panels::viewers::on_open_comp(self, c);+ self.ui.timeline.pps = None;+ }+ effectcraft_engine::Event::Toast { message, .. } => self.toast = Some((message, self.now)),+ effectcraft_engine::Event::OpenUrl(url) => ctx.open_url(egui::OpenUrl::new_tab(url)),+ // Frames are keyed by content: an edit keeps those of comps it doesn't touch.+ effectcraft_engine::Event::ProjectChanged { .. } => {}+ effectcraft_engine::Event::Frontend { command, params } => {+ if let Err(e) = crate::menus::frontend(self, ctx, &command, params) {+ self.ui.status = e;+ }+ }+ effectcraft_engine::Event::PurgeCaches => self.frames.clear(),+ effectcraft_engine::Event::CopyImage { width, height, rgba } => {+ if let Err(e) = copy_image(ctx, width, height, &rgba) {+ self.ui.status = e;+ }+ }+ }+ }+ }++ /// The app's only non-paint entry: one tick of background work.+ ///+ /// This runs for every eframe logic callback, including the logic-only ticks of a hidden+ /// window (which never reach [`Self::draw`]). It must therefore do no input handling, no+ /// layout and no presentation: engine/job queues, autosave, playback, audio, the control+ /// channel, screenshots and the close guard. Everything here is idempotent for a pass that+ /// `Context::request_discard` replays.+ pub fn tick(&mut self, ctx: &egui::Context, frame: &eframe::Frame) {+ self.now = self.clock.now();+ // The compositor exists before the first paint and while hidden (device-loss handling+ // must run there too).+ self.init_gpu(frame);+ self.apply_gpu_failure(ctx);+ if self.gpu_failure_applied == Some(true) {+ self.close_after_device_loss(ctx);+ return;+ }+ // Focus comes from the fresh viewport copy; a full pass's `InputState::focused` is only a+ // fallback (a logic-only tick leaves it at the previous pass's value).+ let focused = ctx.input(|i| i.viewport().focused.or(Some(i.focused)));+ self.focused = focused.unwrap_or(self.focused);+ // The interface language's fallback fonts are installed in `draw` (fonts need a pass), but+ // commands handled here use the right catalog already.+ let language = crate::i18n::language(self);+ crate::i18n::set_current(language);+ if self.styled_language != language {+ self.want_paint = true;+ }+ // Frames and worker completions wake the app even while it is hidden.+ self.frames.set_context(ctx);+ updates_ui::tick(self, ctx);+ if self.session.render_job.is_some() {+ self.session.poll_render();+ ctx.request_repaint_after(std::time::Duration::from_millis(100));+ }+ if self.session.track_job.is_some() {+ self.session.poll_track();+ ctx.request_repaint_after(std::time::Duration::from_millis(50));+ }+ if self.session.mask_job.is_some() {+ self.session.poll_mask_track();+ ctx.request_repaint_after(std::time::Duration::from_millis(50));+ }+ // Background tasks (Content-Aware Fill, Scene Edit Detection, imports).+ if !self.session.tasks.is_empty() {+ self.session.poll_jobs();+ ctx.request_repaint_after(std::time::Duration::from_millis(100));+ }+ // Analyses running in a worker (the web app).+ if !self.session.offloaded.is_empty() {+ self.session.poll_offload();+ ctx.request_repaint_after(std::time::Duration::from_millis(100));+ }+ // Warp Stabilizer: finish analyses and start queued (re-)analyses in the background.+ if self.session.warp_job.is_some() || !self.session.warp_pending.is_empty() {+ self.session.poll_warp(true);+ self.session.poll_roto(true);+ ctx.request_repaint_after(std::time::Duration::from_millis(100));+ }+ // Roto Brush propagation and Object Matte tracking / Freeze: finish jobs (a Freeze writes+ // its mattes) and start queued ones in the background.+ if self.session.roto_job.is_some() || !self.session.roto_pending.is_empty() {+ self.session.poll_roto(true);+ ctx.request_repaint_after(std::time::Duration::from_millis(100));+ }+ // 3D Camera Tracker: likewise (tracking, then solving).+ if self.session.camera_job.is_some() || !self.session.camera_pending.is_empty() {+ self.session.poll_camera(true);+ ctx.request_repaint_after(std::time::Duration::from_millis(100));+ }+ self.run_script_tasks(ctx);+ self.run_dialog_answers();+ self.handle_events(ctx);+ if let Some(rx) = self.command_inbox.take() {+ while let Ok(id) = rx.try_recv() {+ if let Err(e) = menus::invoke(self, ctx, &id, json!({})) {+ self.ui.status = e;+ }+ }+ self.command_inbox = Some(rx);+ }+ // A close request (the window's button, Quit, `app.quit`) must be answered while hidden.+ // An answered file dialog can change the project, so the answers above run first. The host+ // calls `panels::unsaved::quit_on_close` last in its `logic`.+ panels::unsaved::on_close_requested(self, ctx);+ let title = panels::unsaved::window_title(self);+ if title != self.window_title {+ ctx.send_viewport_cmd(egui::ViewportCommand::Title(title.clone()));+ self.window_title = title;+ }+ self.tick_autosave(ctx);+ self.tick_workspace_autosave(ctx);+ let now = self.now;+ prefs_live::tick(self, ctx, now);+ // Playback advances without a paint (its frames and the audio clock are background work).+ // Idle prefetch keeps its old condition: it only runs once a viewer has drawn.+ if (self.playback.playing || self.last_viewer_scale.is_some())+ && let Some(cid) = self.session.active_comp_id()+ {+ let (scale, active) = (self.last_viewer_scale.unwrap_or(1.0), self.input_active);+ self.advance_playback(ctx, scale, now, active, cid);+ }+ self.drain_control(ctx, now);+ // Screenshot completion, deadlines and issuance are app-side work: the callback only+ // stores pixels and wakes this viewport.+ self.tick_screenshots(ctx);+ // Time-based FPS readout over UI passes (a hidden logic-only tick is not a frame).+ let dt = (now - self.last_time) as f32;+ if dt > 0.0 && dt < 2.0 {+ self.fps = self.fps * 0.9 + (1.0 / dt).min(480.0) * 0.1;+ }+ self.last_time = now;+ // A hidden window paints when work needs a UI pass: queued input and waits, a settled+ // screenshot, or playback into a child viewport.+ let focused = self.focused;+ let child_viewports = !self.ui.dock.layout.floating.is_empty() || prefs_live::video_preview_active(self, focused);+ let paint = self.want_paint+ || !self.synthetic.is_empty()+ || !self.input_waiters.is_empty()+ || self.pending_screenshots.iter().any(|s| s.slot.is_none())+ || (self.playback.playing && child_viewports);+ if paint {+ self.request_hidden_paint(ctx);+ }+ }++ /// Ask the host for a UI pass even when the window is minimized or occluded.+ ///+ /// Native eframe honours `RequestPaintWhileHidden`; the shared web backend does not carry it+ /// yet (a browser does not paint a hidden tab), so the web build only requests a normal+ /// repaint and hidden web screenshots/input remain unqualified.+ fn request_hidden_paint(&mut self, ctx: &egui::Context) {+ self.want_paint = false;+ #[cfg(not(target_arch = "wasm32"))]+ ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaintWhileHidden);+ ctx.request_repaint();+ }++ /// Install the theme and fonts for the current language. Fonts need a real pass: the pass+ /// that installs them draws nothing, and the next pass draws with them (the two-pass warm-up+ /// the app has always had). Never call this from a logic-only tick.+ fn ui_setup(&mut self, ctx: &egui::Context) {+ panels::viewer_text::install_hooks(ctx);+ let language = crate::i18n::language(self);+ crate::i18n::set_current(language);+ if (!self.styled || self.styled_language != language) && self.synthetic_in_flight {+ // The install needs a pass that draws nothing, but this pass has already applied a+ // synthetic batch: defer the theme/font install by one pass instead of dropping the+ // input (feeds are only put into a pass that can draw).+ ctx.request_repaint();+ return;+ }+ if !self.styled || self.styled_language != language {+ theme::install(ctx, &self.tokens, language);+ self.styled_language = language;+ if !self.styled {+ fit_window(ctx);+ self.styled = true;+ }+ self.fonts_ready = false;+ ctx.request_repaint();+ } else if !self.fonts_ready {+ // The pass after the install draws: egui has the new font definitions by now.+ self.fonts_ready = true;+ ctx.request_repaint();+ }+ }++ /// One UI pass: setup, input-driven shortcuts, layout and painting. Called from+ /// `eframe::App::ui` and by tests with the root `Ui`.+ pub fn draw(&mut self, ui: &mut egui::Ui, frame: &eframe::Frame) {+ panels::viewer_text::begin_ui(ui.ctx());+ self.draw_inner(ui, frame);+ // All exits, including fonts/device loss, observe this pass's real custom availability.+ panels::viewer_text::finish_ime(self, ui);+ }++ /// Context creators install these hooks before the first full pass.+ pub fn install_ime_reset_hooks(ctx: &egui::Context) {+ panels::viewer_text::install_hooks(ctx);+ }++ /// Host wrappers call this after their last logic mutation, without replaying UI events.+ pub fn finish_ime_logic(&self, ctx: &egui::Context) {+ panels::viewer_text::finish_logic(self, ctx);+ }++ /// One UI pass after the IME begin hook: close on an applied GPU failure, run `ui_setup`, skip drawing until+ /// fonts are ready, draw the frame, finish pointer wrapping, pump queued wasm frames, record input activity,+ /// publish the completed pass's geometry and pass sequence, acknowledge applied synthetic input and answer+ /// `AfterInput` replies only after a non-discarded pass. Requests repaints while frames are in flight.+ fn draw_inner(&mut self, ui: &mut egui::Ui, frame: &eframe::Frame) {+ let ctx = ui.ctx().clone();+ if self.gpu_failure_applied == Some(true) {+ self.close_after_device_loss(&ctx);+ return;+ }+ self.ui_setup(&ctx);+ if !self.fonts_ready {+ // A pass that installs fonts draws nothing. No synthetic batch is in flight here (the+ // hook feeds input only to a ready app), and events egui already applied are never+ // fed again: that would double the pointer/key state of one click.+ ctx.request_repaint();+ return;+ }+ self.frame(ui);+ #[cfg(not(target_arch = "wasm32"))]+ pointer_wrap::finish_native(&ctx, frame);+ // wasm32: no frame threads; render queued frames now, between UI frames.+ if cfg!(target_arch = "wasm32") && self.frames.pump(std::time::Duration::from_millis(if self.playback.playing { 24 } else { 40 })) {+ ctx.request_repaint();+ }+ // Input belongs to this known UI phase: record it for the next tick.+ let active = ctx.input(|i| !i.events.is_empty() || i.pointer.any_down() || i.pointer.is_moving());+ self.input_active = active;+ self.last_pointer_down = ctx.input(|i| i.pointer.any_down());+ // Geometry of a completed pass (a discarded pass is laid out again; only the final one+ // describes the surface the next capture will see). Window position is irrelevant.+ if !ctx.will_discard() {+ let rect = ctx.content_rect();+ let ppp = ctx.pixels_per_point();+ let changed = self.draw_geom.is_none_or(|g| g.rect.size() != rect.size() || g.ppp != ppp);+ if changed {+ self.geometry_epoch = self.geometry_epoch.wrapping_add(1);+ }+ self.draw_geom = Some(DrawGeometry { rect, ppp, epoch: self.geometry_epoch });+ self.ui_pass_seq = self.ui_pass_seq.saturating_add(1);+ }+ // A batch is acknowledged once a UI pass applied it, even if layout was later discarded.+ self.mark_synthetic_applied();+ // `AfterInput` replies wait for the final (non-discarded) pass that applied the last+ // synthetic event: a hidden request is answered only after its forced pass, and a pass+ // egui throws away cannot produce an early success reply.+ if !ctx.will_discard() && self.synthetic.is_empty() {+ for w in self.input_waiters.drain(..) {+ let _ = w.send(json!({"ok": true, "result": null}));+ }+ } else if !self.input_waiters.is_empty() {+ self.want_paint = true;+ ctx.request_repaint();+ }+ if self.frames.inflight() > 0 {+ ctx.request_repaint_after(std::time::Duration::from_millis(30));+ }+ }++ /// The panels, menus, dialogs and overlays of one pass.+ fn frame(&mut self, ui: &mut egui::Ui) {+ let ctx = ui.ctx().clone();+ // Only a viewer that draws in *this* pass records a scale: a closed viewer, the Home+ // screen or another comp must stop idle prefetch at a stale scale.+ self.last_viewer_scale = None;+ self.apply_prefs(&ctx);+ // Video Preview is a second viewport: only a real pass can update it.+ prefs_live::frame(self, &ctx);+ self.auto.begin_frame();+ let tab_had_widget_focus = ctx.egui_wants_keyboard_input();+ menus::handle_shortcuts(self, &ctx);+ if !ctx.input(|i| i.pointer.primary_down()) {+ self.ui.viewer.property_interacting = false;+ }+ let t = self.tokens;+ let full = ui.max_rect();+ if self.dialog.is_some() {+ ui.disable();++ // A dialog that edits what is behind it live (Preview) leaves the window at full++ // brightness: clicks still don't reach it, but the canvas is not greyed out.++ if self.dialog == Some(Dialog::GradientEditor) || panels::live_preview::active(self) {++ ui.set_opacity(1.0);++ }+ }+ ui.painter().rect_filled(full, 0.0, t.app_bg);+ let mut top = full.min.y;+ if self.ui.show_menu_bar {+ let mb = egui::Rect::from_min_size(full.min, egui::vec2(full.width(), 24.0));+ let mut child = ui.new_child(egui::UiBuilder::new().max_rect(mb));+ child.painter().rect_filled(mb, 0.0, t.header_bg);+ menus::menu_bar(self, &mut child);+ top = mb.max.y;+ }+ let header_h = 40.0;+ let header = egui::Rect::from_min_size(egui::pos2(full.min.x, top), egui::vec2(full.width(), header_h));+ header::show(self, ui, header);+ let body = egui::Rect::from_min_max(egui::pos2(full.min.x + 4.0, header.max.y + 2.0), egui::pos2(full.max.x - 4.0, full.max.y - 4.0));+ self.dock_area(ui, body);+ #[cfg(not(target_arch = "wasm32"))]+ prefs_live::dropped_files(self, ui, full);+ if !tab_had_widget_focus {+ menus::handle_tab_shortcut(self, &ctx);+ }+ panels::precomp::mini_flowchart(self, &ctx);+ panels::home::capture_thumbnail(self);+ panels::dialogs::show(self, &ctx);+ updates_ui::show(self, &ctx);+ panels::scriptui_view::sync_panels(self);+ panels::scriptui_view::show_windows(self, &ctx);+ panels::learn::coach(self, &ctx);+ let lift = panels::media_panels::import_card(self, ui, full);+ self.draw_toast(ui, full, lift);+ }++ /// Workspace-layout auto-save: a background write that also runs while hidden, once the+ /// pointer has lifted.+ fn tick_workspace_autosave(&mut self, ctx: &egui::Context) {+ if self.session.config.is_none() || !self.workspace_store.has_changes(&self.ui) || self.last_pointer_down {+ return;+ }+ if self.workspace_store.due(self.now) {+ self.save_workspace_state();+ }+ if self.workspace_store.has_changes(&self.ui) {+ ctx.request_repaint_after(std::time::Duration::from_secs(1));+ }+ }++ pub(super) fn save_workspace_state(&mut self) {+ if let Err(error) = self.workspace_store.save(self.session.config.as_deref(), &self.ui) {+ if self.workspace_store.error.as_ref() != Some(&error) {+ log::warn!("{error}");+ self.ui.status = error.clone();+ }+ self.workspace_store.error = Some(error);+ }+ }++ /// The status message or the latest toast, bottom left (`lift` points higher while the+ /// Importing card is there).+ fn draw_toast(&mut self, ui: &mut egui::Ui, full: egui::Rect, lift: f32) {+ let now = self.now;+ let msg = if !self.ui.status.is_empty() {+ Some(self.ui.status.clone())+ } else {+ self.toast.as_ref().filter(|(_, at)| now - at < 4.0).map(|(m, _)| m.clone())+ };+ if let Some(m) = msg {+ let t = &self.tokens;+ let galley = ui.painter().layout_no_wrap(m.clone(), Tokens::ui(12.0), t.text);+ let r = egui::Rect::from_min_size(egui::pos2(full.min.x + 16.0, full.max.y - 44.0 - lift), galley.size() + egui::vec2(24.0, 14.0));+ ui.painter().rect_filled(r, 6.0, t.panel_bg);+ ui.painter().rect_stroke(r, 6.0, egui::Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside);+ ui.painter().galley(r.min + egui::vec2(12.0, 7.0), galley, t.text);+ self.auto.add("toast", r, &m);+ let resp = ui.interact(r, egui::Id::unique("toast"), egui::Sense::click());+ if resp.clicked() {+ self.ui.status.clear();+ self.toast = None;+ }+ ui.ctx().request_repaint_after(std::time::Duration::from_millis(500));+ if !self.ui.status.is_empty() {+ let since: f64 = ui.data(|d| d.get_temp(egui::Id::unique("status-since")).unwrap_or(now));+ ui.data_mut(|d| d.insert_temp(egui::Id::unique("status-since"), since));+ if now - since > 5.0 {+ self.ui.status.clear();+ ui.data_mut(|d| d.remove::<f64>(egui::Id::unique("status-since")));+ }+ }+ }+ }+ }++ impl EffectcraftApp {+ /// Scripts' `app.scheduleTask` tasks that are due (repeating ones keep a ScriptUI panel+ /// fresh): errors as a toast, the last line printed in the status bar, and a repaint when+ /// the next one is due.+ fn run_script_tasks(&mut self, ctx: &egui::Context) {+ if self.session.script_ui.task_hosts.is_empty() {+ return;+ }+ let previous_comp = self.session.active_comp_id();+ let Some(r) = effectcraft_engine::scriptui::ScriptUi::run_tasks(&mut self.session) else { return };+ if self.session.active_comp_id().is_some() && self.session.active_comp_id() != previous_comp {+ self.ui.start_screen = false;+ }+ if let Some(msg) = r["errors"].as_array().and_then(|e| e.first()).and_then(|e| e["message"].as_str()) {+ self.toast = Some((format!("Scheduled script task: {msg}"), self.now));+ } else if let Some(line) = r["output"].as_array().and_then(|o| o.last()).and_then(|l| l.as_str()) {+ self.ui.status = line.to_string();+ }+ if let Some(next) = r["next"].as_u64() {+ ctx.request_repaint_after(std::time::Duration::from_millis(next));+ }+ }++ /// Auto-save a dirty project when the interval has passed (Settings ▸ Project ▸ Auto-Save).+ fn tick_autosave(&mut self, ctx: &egui::Context) {+ // Monotonic app time: a wall-clock jump must not skip or repeat an auto-save.+ let now = self.now;+ if let Some(Err(e)) = self.session.autosave_tick(now) {+ self.ui.status = e.to_string();+ }+ if self.session.prefs.auto_save.enabled {+ ctx.request_repaint_after(std::time::Duration::from_secs(30));+ }+ // File ▸ Watch Folder: look for new projects every 10 seconds.+ if self.session.state.watch_folder.is_some() {+ let key = egui::Id::unique("watchFolder.lastPoll");+ let last: f64 = ctx.data(|d| d.get_temp(key)).unwrap_or(0.0);+ if now - last >= 10.0 {+ ctx.data_mut(|d| d.insert_temp(key, now));+ match self.session.execute("file.watchFolder.poll", serde_json::json!({})) {+ Ok(r) => {+ if let Some(n) = r["rendered"].as_array().map(Vec::len).filter(|n| *n > 0) {+ self.ui.status = format!("Watch Folder: rendered {n} project(s)");+ }+ }+ Err(e) => self.ui.status = e.to_string(),+ }+ }+ ctx.request_repaint_after(std::time::Duration::from_secs(10));+ }+ self.tick_footage_reload(ctx, now);+ }++ /// Settings ▸ Import ▸ Reload Footage Changed on Disk: every two seconds, and as soon as the+ /// window comes back to the front (after saving in another app), stamp the footage files on a+ /// worker thread and reload the ones that changed.+ fn tick_footage_reload(&mut self, ctx: &egui::Context, now: f64) {+ use effectcraft_engine::footage_reload;+ if let Some(Err(e)) = footage_reload::poll_scan(&mut self.session) {+ self.ui.status = e.to_string();+ }+ let (last_key, focus_key) = (egui::Id::unique("footageReload.lastScan"), egui::Id::unique("footageReload.focused"));+ let focused = self.focused;+ let was_focused: bool = ctx.data(|d| d.get_temp(focus_key)).unwrap_or(focused);+ ctx.data_mut(|d| d.insert_temp(focus_key, focused));+ if self.session.prefs.import.auto_reload_footage == "off" || self.session.project.items.is_empty() {+ return;+ }+ let last: f64 = ctx.data(|d| d.get_temp(last_key)).unwrap_or(0.0);+ if now - last >= 2.0 || (focused && !was_focused) {+ ctx.data_mut(|d| d.insert_temp(last_key, now));+ footage_reload::start_scan(&mut self.session);+ }+ if self.session.footage_scan.is_some() {+ ctx.request_repaint_after(std::time::Duration::from_millis(100));+ } else {+ ctx.request_repaint_after(std::time::Duration::from_secs(2));+ }+ }+ }diff --cc crates/ui-egui/src/app/window.rsindex 000000000,10a53f1d2..7326b9f32mode 000000,100644..100644--- a/crates/ui-egui/src/app/window.rs+++ b/crates/ui-egui/src/app/window.rs@@@ -1,0 -1,155 +1,167 @@@+ use super::*;++ impl EffectcraftApp {+ /// Keep the saved workspaces for the next session (see [`EffectcraftApp::new`]): After+ /// Effects' saved workspaces last until they are deleted (#320). `Err` when they weren't+ /// written (#696): the change applies for this session and a later save retries it, but until+ /// then a restart brings back what is on disk.+ pub(crate) fn store_saved_workspaces(&mut self) -> Result<(), String> {+ let Err(error) = self.workspace_store.save_now(self.session.config.as_deref(), &self.ui) else { return Ok(()) };+ let message = format!("Workspace changes couldn't be saved and may be lost after a restart: {error}");+ log::warn!("{message}");+ self.ui.status = message.clone();+ // The raw error, so the background retry doesn't report the same failure again.+ self.workspace_store.error = Some(error);+ Err(message)+ }++ pub fn set_workspace(&mut self, name: &str) {+ // Learn: the Home screen's Learn tab (tutorials) in the Composition panel. Leaving it for+ // another workspace closes the Home screen again: it stayed over every workspace until a+ // project was created (#272).+ if name == "Learn" {+ self.ui.start_screen = true;+ self.ui.home_learn = true;+ self.ui.home_templates = false;+ } else if self.ui.workspace == "Learn" {+ self.ui.start_screen = false;+ self.ui.home_learn = false;+ }+ self.ui.workspace = name.to_string();+ self.ui.dock = self.ui.saved_workspaces.get(name).cloned().unwrap_or_else(|| dock::Workspace::new(dock::workspace(name)));+ self.ui.maximized = None;+ }++ /// Built-in workspaces followed by the saved ones (Window ▸ Workspace ▸ Save as New Workspace).+ pub fn workspace_names(&self) -> Vec<String> {+ let mut v: Vec<String> = dock::WORKSPACES.iter().map(|s| s.to_string()).collect();+ v.extend(self.saved_workspace_names());+ v+ }++ /// The workspaces the user saved under a new name (built-ins whose changes were saved are+ /// not repeated), in name order.+ pub fn saved_workspace_names(&self) -> Vec<String> {+ self.ui.saved_workspaces.keys().filter(|k| !dock::WORKSPACES.contains(&k.as_str())).cloned().collect()+ }++ /// The open Gradient Editor's draft (`panels::gradient_editor`): what OK would set.+ pub fn gradient_draft(&self) -> &panels::gradient_editor::Draft {+ &self.dialog_state.gradient+ }++ /// The open Gradient Editor's draft, to edit (tests and automation; the editor's own fields+ /// do the same).+ pub fn gradient_draft_mut(&mut self) -> &mut panels::gradient_editor::Draft {+ &mut self.dialog_state.gradient+ }+++ /// The open settings dialog's draft and Preview state (`panels::dialogs`): Solid, Camera,++ /// Light and Composition Settings keep what OK would apply here.++ pub fn dialog_state(&self) -> &panels::dialogs::DialogState {++ &self.dialog_state++ }++++ /// The open settings dialog's draft, to edit (tests and automation; the dialog's own fields++ /// do the same).++ pub fn dialog_state_mut(&mut self) -> &mut panels::dialogs::DialogState {++ &mut self.dialog_state++ }+++ /// Show panel `p` (opening it in its usual place if it is closed), bring it to the front and+ /// give it the focus: Window ▸ `<panel>`.+ pub fn show_panel(&mut self, p: PanelKind) {+ if !self.ui.dock.is_floating(p) && self.ui.maximized.is_some_and(|m| m != p) {+ self.ui.maximized = None;+ }+ self.raise_panel(p);+ self.ui.focused = p;+ }++ /// Bring panel `p` to the front of its group, opening it if it is closed, without moving the+ /// focus (a comp opening brings up its viewer, an effect applied brings up Effect Controls).+ /// A closed panel goes back where it was; one never laid out goes to its usual place: the+ /// Composition panel in the centre with the Layer panel and other viewers (with none of+ /// those left, above the Timeline), Layer and the viewers beside the Composition panel, and+ /// so on.+ pub fn raise_panel(&mut self, p: PanelKind) {+ if !self.ui.dock.is_open(p) {+ let docked = |q: &PanelKind| self.ui.dock.is_docked(*q);+ let near = match p {+ PanelKind::Composition => self+ .ui+ .dock+ .panels()+ .into_iter()+ .find(|q| matches!(q, PanelKind::Layer | PanelKind::Viewer(_) | PanelKind::Flowchart | PanelKind::Footage) && docked(q)),+ PanelKind::Layer | PanelKind::Flowchart | PanelKind::Viewer(_) => Some(PanelKind::Composition),+ PanelKind::RenderQueue => Some(PanelKind::Timeline),+ PanelKind::EffectControls | PanelKind::History => Some(PanelKind::Project),+ _ => Some(PanelKind::EffectsPresets),+ }+ .filter(|q| self.ui.dock.is_open(*q));+ let mut workspace = self.ui.dock.clone();+ let known = workspace.hidden.iter().any(|(q, _)| *q == p);+ let opened = if p == PanelKind::Composition && near.is_none() && !known && self.ui.dock.is_docked(PanelKind::Timeline) {+ workspace+ .apply(+ craft_ui::docking::Action::OpenAt {+ panel: p,+ anchor: PanelKind::Timeline,+ placement: craft_ui::docking::Placement::Split(craft_ui::docking::Zone::Top),+ },+ dock::permissions,+ )+ .map(|_| ())+ } else if known {+ workspace.set_visible(p, true, near, dock::permissions)+ } else {+ workspace.apply(craft_ui::docking::Action::Open { panel: p, anchor: near }, dock::permissions).map(|_| ())+ };+ match opened {+ Ok(()) => self.ui.dock = workspace,+ Err(e) => {+ self.ui.status = format!("can't open {}: {e}", p.title());+ return;+ }+ }+ }+ let _ = self.ui.dock.apply(craft_ui::docking::Action::Activate { panel: p }, dock::permissions);+ if self.ui.dock.is_floating(p) {+ self.pending_panel_raise = Some(p);+ }+ }+ }++ /// Maximize a first window that doesn't fit the screen, which fits it to the space beside the+ /// taskbar or dock. The 1680 × 1020 window on a smaller screen is only shrunk to the monitor's+ /// size, so with its title bar it ran under the taskbar and cut menus off at the bottom of the+ /// screen (#269).+ pub(super) fn fit_window(ctx: &egui::Context) {+ let (monitor, window) = ctx.input(|i| (i.viewport().monitor_size, i.viewport().outer_rect.or(i.viewport().inner_rect)));+ if let (Some(monitor), Some(window)) = (monitor, window)+ && overflows_screen(window.size(), monitor)+ {+ ctx.send_viewport_cmd(egui::ViewportCommand::Maximized(true));+ }+ }++ /// Whether a window `size` leaves no room on a `monitor` for a taskbar or dock (points).+ fn overflows_screen(size: egui::Vec2, monitor: egui::Vec2) -> bool {+ const TASKBAR: f32 = 64.0;+ size.x > monitor.x || size.y > monitor.y - TASKBAR+ }++ #[cfg(test)]+ mod fit_window_tests {+ use super::overflows_screen;+ use egui::vec2;++ #[test]+ fn a_window_taller_than_the_screen_beside_its_taskbar_overflows() {+ // The default window on a 1366 × 768 laptop (shrunk to the monitor) and on 1080p.+ assert!(overflows_screen(vec2(1366.0, 799.0), vec2(1366.0, 768.0)));+ assert!(overflows_screen(vec2(1680.0, 1051.0), vec2(1920.0, 1080.0)));+ assert!(!overflows_screen(vec2(1680.0, 1051.0), vec2(2560.0, 1440.0)));+ }+ }diff --cc crates/ui-egui/src/menus/shortcuts.rsindex 000000000,b9990786c..f50fbdb3cmode 000000,100644..100644--- a/crates/ui-egui/src/menus/shortcuts.rs+++ b/crates/ui-egui/src/menus/shortcuts.rs@@@ -1,0 -1,418 +1,432 @@@+ use super::frontend::run_engine;+ use super::invoke::invoke;+ use super::{EffectcraftApp, PanelKind, Value, json};++ /// Shortcut text in this OS's notation (`⇧⌘K` on macOS, `Ctrl+Shift+K` elsewhere).+ pub fn shortcut_text(s: &str) -> String {+ if cfg!(target_os = "macos") {+ let mut out = String::new();+ let parts: Vec<&str> = match s.strip_suffix("++") {+ Some(head) => vec![head, "+"],+ None => s.split('+').collect(),+ };+ let (mods, key) = parts.split_at(parts.len().saturating_sub(1));+ for m in mods {+ out.push_str(match *m {+ "Ctrl" => "⌃",+ "Alt" => "⌥",+ "Shift" => "⇧",+ "Cmd" => "⌘",+ x => x,+ });+ }+ out.push_str(match key.first().copied().unwrap_or("") {+ "Space" => "Space",+ "Escape" => "Esc",+ "Home" => "↖",+ k => k,+ });+ out+ } else {+ s.replace("Cmd", "Ctrl")+ }+ }++ /// Parse "Cmd+Shift+K" into modifiers + key.+ pub fn parse_shortcut(s: &str) -> Option<(egui::Modifiers, egui::Key)> {+ let mut m = egui::Modifiers::NONE;+ let mut key = None;+ // The plus key itself is written `+` or `Cmd++`.+ let (head, plus) = match s.strip_suffix("++") {+ Some(h) => (h, true),+ None if s == "+" => ("", true),+ None => (s, false),+ };+ let mut parts: Vec<&str> = if head.is_empty() { vec![] } else { head.split('+').collect() };+ if plus {+ parts.push("+");+ }+ for p in parts {+ match p {+ "Cmd" => {+ m.command = true;+ m.mac_cmd = cfg!(target_os = "macos");+ if !cfg!(target_os = "macos") {+ m.ctrl = true;+ }+ }+ "Physical" => {}+ "Shift" => m.shift = true,+ "Alt" => m.alt = true,+ "Ctrl" => m.ctrl = true,+ k => {+ key = match k {+ ";" => Some(egui::Key::Semicolon),+ "'" => Some(egui::Key::Quote),+ "," => Some(egui::Key::Comma),+ "." => Some(egui::Key::Period),+ "/" => Some(egui::Key::Slash),+ "\\" => Some(egui::Key::Backslash),+ "=" => Some(egui::Key::Equals),+ "-" => Some(egui::Key::Minus),+ "`" => Some(egui::Key::Backtick),+ "[" => Some(egui::Key::OpenBracket),+ "]" => Some(egui::Key::CloseBracket),+ "Num0" => Some(egui::Key::Num0),+ "Num*" => None,+ _ => egui::Key::from_name(k),+ }+ }+ }+ }+ key.map(|k| (m, k))+ }++ /// The key some keyboards report for a shifted punctuation key (`Shift+=` arrives as `+`).+ fn shifted_alias(k: egui::Key) -> Option<egui::Key> {+ use egui::Key::*;+ Some(match k {+ Equals => Plus,+ Semicolon => Colon,+ OpenBracket => OpenCurlyBracket,+ CloseBracket => CloseCurlyBracket,+ Slash => Questionmark,+ Backslash => Pipe,+ _ => return None,+ })+ }++ /// A key binding: modifiers, key, command id and bound params.+ pub type Binding = (egui::Modifiers, egui::Key, String, Value);++ /// All bindings of the active keyboard shortcut preset, most modifiers first.+ pub fn bindings(session: &effectcraft_engine::Session) -> Vec<Binding> {+ let mut v: Vec<Binding> = Vec::new();+ for (sc, b) in session.shortcuts().bindings() {+ if sc.starts_with("Physical+") {+ continue;+ }+ // Off macOS `Cmd` is Ctrl, so a custom Ctrl+Cmd shortcut would+ // steal the plain Cmd one: such macOS-only shortcuts aren't bound there.+ if !cfg!(target_os = "macos") && sc.split('+').any(|p| p == "Ctrl") && sc.split('+').any(|p| p == "Cmd") {+ continue;+ }+ if let Some((m, k)) = parse_shortcut(sc) {+ if m.shift+ && let Some(alias) = shifted_alias(k)+ {+ v.push((m, alias, b.command.clone(), b.params.clone()));+ }+ v.push((m, k, b.command.clone(), b.params.clone()));+ }+ }+ v.sort_by_key(|(m, ..)| std::cmp::Reverse(m.command as u8 + m.shift as u8 + m.alt as u8 + m.ctrl as u8));+ v+ }++ fn mods_match(want: egui::Modifiers, got: egui::Modifiers) -> bool {+ want.command == got.command && want.shift == got.shift && want.alt == got.alt && (want.ctrl == got.ctrl || got.command && cfg!(not(target_os = "macos")))+ }++ /// Whether the `key`+`mods` chord is the current binding of `command` in the active preset+ /// (so callers that must match a shortcut themselves — like the viewer's text editor, which+ /// holds the keyboard while the shortcut dispatcher is skipped — follow rebinds).+ /// `Physical+`-only bindings never match here, exactly as for the app-wide dispatcher.+ pub fn chord_matches(session: &effectcraft_engine::Session, command: &str, key: egui::Key, mods: egui::Modifiers) -> bool {+ bindings(session).into_iter().any(|(m, k, id, _)| id == command && k == key && mods_match(m, mods))+ }++ /// Whether a Deselect All chord matched by [`chord_matches`] may run while a text editor holds+ /// the keyboard. Chords carrying Cmd/Ctrl/Alt are command chords (the editor treats them as+ /// such for undo and the rest), and function keys never type, so those forward from the editor;+ /// a chord that could instead produce a character — a bare or Shift-only letter, digit or+ /// punctuation key, as from a pathological bare-letter rebinding — stays with the editor so+ /// typing keeps working, the same invariant the app-wide dispatcher honors by skipping+ /// focused text fields.+ pub fn forwardable_during_text_edit(mods: egui::Modifiers, key: egui::Key) -> bool {+ mods.command || mods.ctrl || mods.alt || (egui::Key::F1..=egui::Key::F35).contains(&key)+ }++ /// Set (egui temp data) from a plain Spacebar press until its release while a tap would still+ /// run the Spacebar shortcut.+ /// The system clipboard's text of this frame's paste event, for the Edit ▸ Paste it runs.+ pub(super) fn system_paste_id() -> egui::Id {+ egui::Id::unique("menus-system-paste")+ }++ /// The temp-data id of the flag set by a plain Space press and taken on its release, so a tap+ /// runs the Space shortcut while holding Space stays the Hand tool.+ fn space_tap_id() -> egui::Id {+ egui::Id::unique("spacebar-tap")+ }++ /// The modifiers held when this frame's input began: the state the last pass ended with, if it+ /// ran this (egui keeps only the state after the frame's events). Records this pass's state.+ pub(super) fn modifiers_at_start(ctx: &egui::Context) -> Option<egui::Modifiers> {+ let id = egui::Id::unique("shortcut-modifiers");+ let pass = ctx.cumulative_pass_nr();+ let now = ctx.input(|i| i.modifiers);+ ctx.data_mut(|d| {+ let last = d.get_temp::<(u64, egui::Modifiers, Option<egui::Modifiers>)>(id);+ if let Some((p, _, start)) = last+ && p == pass+ {+ return start;+ }+ let start = last.and_then(|(p, m, _)| (p.checked_add(1) == Some(pass)).then_some(m));+ d.insert_temp(id, (pass, now, start));+ start+ })+ }++ /// Only Shift held (Shift+Delete, not Ctrl/Alt+Shift+Delete).+ fn only_shift(m: egui::Modifiers) -> bool {+ m.shift && !m.alt && !m.ctrl && !m.command && !m.mac_cmd+ }++ /// Dispatch keyboard shortcuts (skipped while typing in a text field).+ pub fn handle_shortcuts(app: &mut EffectcraftApp, ctx: &egui::Context) {+ handle_shortcuts_impl(app, ctx, false);+ }++ /// Tab can acquire widget focus while the current frame is drawn. Dispatch its application+ /// binding only afterward, and only when no widget owned focus before or after layout.+ pub fn handle_tab_shortcut(app: &mut EffectcraftApp, ctx: &egui::Context) {+ if ctx.input(|i| i.key_pressed(egui::Key::Tab)) {+ handle_shortcuts_impl(app, ctx, true);+ }+ }++ /// Escape with a dialog open: close the popup/picker first, else cancel the dialog.+ fn escape_dialog(app: &mut EffectcraftApp, ctx: &egui::Context) {+ // A popup or colour picker takes Escape first (the picker goes back to its original colour).+ if crate::panels::shortcut_editor::recording(app)+ || crate::panels::shortcut_editor::confirming(app)+ || egui::Popup::is_any_open(ctx)+ || crate::color_picker::open_recently(ctx)+ {+ return;+ }+ ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape));+ if app.dialog == Some(crate::Dialog::LayerStyles) {+ crate::panels::layer_styles_dialog::finish(app, false);++ } else if app.dialog == Some(crate::Dialog::GradientEditor) {++ // Escape is Cancel: the preview rolls back.++ crate::panels::gradient_editor::finish(app, false, ctx);+ } else if app.dialog == Some(crate::Dialog::Info) {+ crate::panels::forms::close_info(app);+ } else {+ if app.dialog == Some(crate::Dialog::Settings)+ && let Some(p) = app.dialog_state.prefs_snapshot.take()+ {+ app.session.prefs = p;+ app.session.prefs_changed();+ }+ if app.dialog == Some(crate::Dialog::UnsavedChanges) {+ app.dialog_state.unsaved.command = None;+ }++ // Escape is Cancel: a Preview that edited the project rolls back.++ crate::panels::live_preview::cancel(app);+ app.dialog = None;+ }+ }+++/// Escape with a dialog open: it is Cancel. Escape while recording a shortcut cancels the++/// recording, not the editor; so does Escape in its Delete Preset prompt.++fn cancel_dialog(app: &mut EffectcraftApp, ctx: &egui::Context) {++ if crate::panels::shortcut_editor::recording(app) || crate::panels::shortcut_editor::confirming(app) {++ return;++ }++ if app.dialog == Some(crate::Dialog::Info) {++ crate::panels::forms::close_info(app);++ return;++ }++ if app.dialog == Some(crate::Dialog::GradientEditor) {++ crate::panels::gradient_editor::finish(app, false, ctx);++ return;++ }++ // Escape in Settings is Cancel: restore the settings from when it opened.++ if app.dialog == Some(crate::Dialog::Settings)++ && let Some(p) = app.dialog_state.prefs_snapshot.take()++ {++ app.session.prefs = p;++ app.session.prefs_changed();++ }++ crate::panels::live_preview::cancel(app);++ app.dialog = None;++}+++ type KeyEvent = (egui::Key, egui::Modifiers, bool, Option<egui::Key>);++ /// The frame's key presses, with clipboard events mapped back to Ctrl+C / X / V.+ fn collect_key_events(ctx: &egui::Context, start: Option<egui::Modifiers>, clipboard: bool, project: bool) -> Vec<KeyEvent> {+ ctx.input(|i| {+ // The windowing layer turns Ctrl+C / Ctrl+X / Ctrl+V into clipboard events instead of+ // key presses: map them back to the keys (with the modifiers held) so Edit ▸ Copy, Cut,+ // Paste and their variants (Ctrl+Alt+C…) run. Clipboard events carry no modifiers and+ // `i.modifiers` is the state after all of the frame's events, so each is read with the+ // modifiers where it is in the stream: walk the events from the frame's starting state.+ // `None` when that isn't known.+ let changed = i.events.iter().any(|e| matches!(e, egui::Event::ModifiersChanged(_) | egui::Event::WindowFocused(false)));+ let mut at = if changed { start } else { Some(i.modifiers) };+ let held = |at: Option<egui::Modifiers>| at.filter(|m| m.command).unwrap_or(egui::Modifiers::COMMAND);+ let mut out = Vec::new();+ for e in &i.events {+ match e {+ egui::Event::ModifiersChanged(m) => at = Some(*m),+ // egui forgets the modifiers held when the window loses focus.+ egui::Event::WindowFocused(false) => at = Some(egui::Modifiers::NONE),+ egui::Event::Key { key, physical_key, pressed: true, modifiers, repeat, .. }+ if !*repeat+ || matches!(+ key,+ egui::Key::PageUp | egui::Key::PageDown | egui::Key::ArrowLeft | egui::Key::ArrowRight | egui::Key::ArrowUp | egui::Key::ArrowDown+ ) =>+ {+ out.push((*key, *modifiers, true, *physical_key));+ }+ egui::Event::Key { key: egui::Key::Space, pressed: false, .. } => out.push((egui::Key::Space, egui::Modifiers::NONE, false, None)),+ egui::Event::Copy if clipboard => out.push((egui::Key::C, held(at), true, None)),+ // On Windows, Shift+Delete is the old Cut key and arrives as Cut too. The Project+ // panel has no clipboard: there a Cut with only Shift held is Shift+Delete (Delete+ // Project Items Without Confirmation). Never when the modifiers aren't known.+ egui::Event::Cut if clipboard && project && at.is_some_and(only_shift) => {+ out.push((egui::Key::Delete, egui::Modifiers::SHIFT, true, None));+ }+ egui::Event::Cut if clipboard => out.push((egui::Key::X, held(at), true, None)),+ egui::Event::Paste(_) if clipboard => out.push((egui::Key::V, held(at), true, None)),+ _ => {}+ }+ }+ out+ })+ }++ /// Numpad * (or `*` typed with Shift+8): Add Marker (#275). egui has no key for it, so it+ /// comes as text.+ fn numpad_star_marker(app: &mut EffectcraftApp, ctx: &egui::Context) {+ if !ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Text(t) if t == "*"))) {+ return;+ }+ let bound = app.session.shortcuts().bindings().into_iter().find(|(k, _)| *k == "Num*").map(|(_, b)| (b.command.clone(), b.params.clone()));+ // As in After Effects, it marks the selected layers; only with none selected does it add+ // a composition marker (#976).+ let bound =+ bound.map(+ |(id, params)| {+ if id == "comp.addMarker" && !app.session.state.selected_layers.is_empty() { ("layer.addMarker".to_owned(), params) } else { (id, params) }+ },+ );+ if let Some((id, params)) = bound+ && let Err(e) = invoke(app, ctx, &id, if params.is_null() { json!({}) } else { params })+ {+ app.ui.status = e;+ }+ }++ fn handle_shortcuts_impl(app: &mut EffectcraftApp, ctx: &egui::Context, tab_only: bool) {+ let start = modifiers_at_start(ctx);+ if !tab_only && app.dialog.is_some() && ctx.input(|i| i.key_pressed(egui::Key::Escape)) {+ escape_dialog(app, ctx);+ return;+ }+ // A mouse button down while Spacebar is held belongs to the Hand tool: its release won't+ // preview.+ if ctx.input(|i| i.pointer.any_down()) || ctx.egui_wants_keyboard_input() {+ ctx.data_mut(|d| d.remove::<bool>(space_tap_id()));+ }+ // While a menu or popup list is open, keys go to it, not to the app (Space must not start a+ // preview behind the menu, #279).+ if ctx.egui_wants_keyboard_input() || crate::widgets::any_menu_open(ctx) {+ return;+ }+ // Text editing in the viewer takes the clipboard events itself.+ let clipboard = app.session.state.text_edit.is_none();+ let project = app.ui.focused == PanelKind::Project;+ // The paste event's text: Edit ▸ Paste pastes SVG markup as a shape layer.+ let pasted =+ if clipboard { ctx.input(|i| i.events.iter().rev().find_map(|e| if let egui::Event::Paste(t) = e { Some(t.clone()) } else { None })) } else { None };+ let mut events = collect_key_events(ctx, start, clipboard, project);+ events.retain(|(key, _, _, _)| (*key == egui::Key::Tab) == tab_only);+ if !tab_only && clipboard && app.dialog.is_none() {+ numpad_star_marker(app, ctx);+ }+ if events.is_empty() {+ return;+ }+ let binds = bindings(&app.session);+ for (key, mods, pressed, physical_key) in events {+ // Plain Spacebar runs its shortcut (Play Current Preview) on the release: held, it is+ // the Hand tool (After Effects), and a drag with it must not start or stop playback.+ if key == egui::Key::Space && (!pressed || !mods.any()) {+ if pressed {+ if app.dialog.is_none() {+ ctx.data_mut(|d| d.insert_temp(space_tap_id(), true));+ }+ continue;+ }+ if !ctx.data_mut(|d| d.remove_temp::<bool>(space_tap_id())).unwrap_or(false) {+ continue;+ }+ }+ // Escape closes dialogs.+ if key == egui::Key::Escape && app.dialog.is_some() {- // Escape while recording a shortcut cancels the recording, not the editor; so does- // Escape in its Delete Preset prompt.- if crate::panels::shortcut_editor::recording(app) || crate::panels::shortcut_editor::confirming(app) {- continue;- }- if app.dialog == Some(crate::Dialog::Info) {- crate::panels::forms::close_info(app);- continue;- }- // Escape in Settings is Cancel: restore the settings from when it opened.- if app.dialog == Some(crate::Dialog::Settings)- && let Some(p) = app.dialog_state.prefs_snapshot.take()- {- app.session.prefs = p;- app.session.prefs_changed();- }- app.dialog = None;++ cancel_dialog(app, ctx);+ continue;+ }+ if app.dialog.is_some() {+ continue;+ }+ // Enter in the Project panel renames the selected item (handled by the panel).+ if key == egui::Key::Enter && !mods.any() && app.ui.focused == PanelKind::Project {+ continue;+ }+ // The Project panel has its own selection; a previously selected Timeline layer+ // must not be deleted while the Project panel has focus.+ if matches!(key, egui::Key::Delete | egui::Key::Backspace) && !mods.any() {+ if matches!(app.ui.focused, PanelKind::Composition | PanelKind::Viewer(_)) && !app.session.state.camera_points.is_empty() {+ if let Err(e) = run_engine(app, ctx, "camera.deletePoints", json!({})) {+ app.ui.status = e;+ }+ ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, key));+ continue;+ }+ // The queue panel consumes the event after its selection state is drawn.+ if app.ui.focused == PanelKind::RenderQueue {+ continue;+ }+ let _ = invoke(app, ctx, "edit.clear", json!({}));+ continue;+ }+ // Explicit physical bindings distinguish keys that a layout reports with the same+ // logical name (for example AZERTY's minus and right parenthesis).+ let physical = physical_key.and_then(|key| {+ app.session.shortcuts().bindings().into_iter().find_map(|(sc, b)| {+ let (m, k) = parse_shortcut(sc.strip_prefix("Physical+")?)?;+ (k == key && mods_match(m, mods)).then(|| (b.command.clone(), b.params.clone()))+ })+ });+ if let Some((id, params)) = physical {+ if let Err(e) = invoke(app, ctx, &id, if params.is_null() { json!({}) } else { params }) {+ app.ui.status = e;+ }+ continue;+ }+ if let Some((_, _, id, params)) = binds.iter().filter(|(m, k, ..)| *k == key && mods_match(*m, mods)).min_by_key(|(_, _, id, params)| {+ // The focused panel wins over an application command sharing its chord.+ let key = effectcraft_engine::shortcuts::binding_key(id, params);+ app.session.shortcuts().find(&key).is_none_or(|b| b.scope != app.ui.focused.id())+ }) {+ let (id, params) = (id.clone(), if params.is_null() { json!({}) } else { params.clone() });+ if id == "edit.paste"+ && let Some(t) = &pasted+ {+ ctx.data_mut(|d| d.insert_temp(system_paste_id(), t.clone()));+ }+ if let Err(e) = invoke(app, ctx, &id, params) {+ app.ui.status = e;+ }+ ctx.data_mut(|d| d.remove_temp::<String>(system_paste_id()));+ }+ }+ }diff --cc crates/ui-egui/src/panels/dialogs.rsindex 3e262bd89,7c89ad32d..70363d527--- a/crates/ui-egui/src/panels/dialogs.rs+++ b/crates/ui-egui/src/panels/dialogs.rs@@@ -219,13 -202,10 +233,15 @@@ fn modal_with_scroll(ctx: &egui::Contex/// only its content: `body` gets the height left under the title, with `size` kept within the/// window.pub(crate) fn modal_fit(ctx: &egui::Context, title: &str, size: egui::Vec2, t: &Tokens, body: impl FnOnce(&mut egui::Ui, f32)) {+ modal_fit_placed(ctx, title, size, t, Placement::default(), body);+}++/// [`modal_fit`] at `place`.+pub(crate) fn modal_fit_placed(ctx: &egui::Context, title: &str, size: egui::Vec2, t: &Tokens, place: Placement, body: impl FnOnce(&mut egui::Ui, f32)) {+ let pass = ctx.cumulative_pass_nr_for(egui::ViewportId::ROOT);+ ctx.data_mut(|d| d.insert_temp(modal_pass_id(), pass));let size = size.min(modal_space(ctx));- let id = egui::Id::new(("modal", title));+ let id = egui::Id::unique(("modal", title));// Dragging the title row moves the dialog off what it edits. The offset is kept within the// window, so dragging back never has to undo a part the dialog could not follow.let offset_id = id.with("offset");@@@ -450,12 -428,12 +471,17 @@@ fn comp_settings(app: &mut EffectcraftAif existing && let (Some(cid), Some(m)) = (app.dialog_state.editing_comp, params.as_object_mut()) {m.insert("comp".into(), json!(cid.0));}+ // A preview already made the edit (one undo step): OK keeps it.+ if existing && super::live_preview::keep(app) {+ app.dialog = None;+ return;+ }let r = if existing { app.session.execute("comp.settings", params) } else { app.session.execute("comp.new", params) };+ let cid = if existing { app.dialog_state.editing_comp.map(|c| c.0) } else { r.as_ref().ok().and_then(|v| v["comp"].as_u64()) };+ let r = match cid {+ Some(cid) if r.is_ok() => set_resolution(app, cid, app.dialog_state.comp.resolution).and(r),+ _ => r,+ };if !existing && r.is_ok() {app.dialog_state.last_new_comp = Some(app.dialog_state.comp.clone());}@@@ -518,13 -497,10 +553,13 @@@ fn solid(app: &mut EffectcraftApp, ctx(ds.solid_name.clone(), ds.solid_color, ds.solid_size, ds.solid_pixel_aspect, ds.solid_affect_all);let (editing, shared) = (ds.solid_layer, ds.solid_shared);let comp_size = app.session.active_comp().map(|c| (c.width, c.height)).unwrap_or((1920, 1080));- let lock_id = egui::Id::new("solid-lock-aspect");+ let lock_id = egui::Id::unique("solid-lock-aspect");let mut lock = ctx.data(|m| m.get_temp::<bool>(lock_id)).unwrap_or(true);+ let live = super::live_preview::active(app);+ let place = super::live_preview::place(app);+ let mut preview = app.dialog_state.live.on;let auto = &mut app.auto;- modal(ctx, "Solid Settings", vec2(480.0, if editing.is_some() { 430.0 } else { 390.0 }), t, |ui| {+ modal_placed(ctx, "Solid Settings", vec2(480.0, if editing.is_some() { 430.0 } else { 390.0 }), t, place, |ui| {ui.horizontal(|ui| {ui.label(tr("Name:"));let r = ui.add(egui::TextEdit::singleline(&mut name).desired_width(320.0));diff --cc crates/ui-egui/src/panels/dialogs_3d.rsindex a8d24e9a3,0a4636b87..92b9624f7--- a/crates/ui-egui/src/panels/dialogs_3d.rs+++ b/crates/ui-egui/src/panels/dialogs_3d.rs@@@ -178,14 -168,11 +183,14 @@@ pub fn camera(app: &mut EffectcraftApplet w = comp_w(app);let mut d = app.dialog_state.camera.clone();let (mut ok, mut close) = (false, false);- let mut rects = (egui::Rect::NOTHING, egui::Rect::NOTHING);- super::dialogs::modal(ctx, "Camera Settings", vec2(520.0, 420.0), t, |ui| {+ let mut rects = (egui::Rect::NOTHING, egui::Rect::NOTHING, egui::Rect::NOTHING);+ let live = super::live_preview::active(app);+ let place = super::live_preview::place(app);+ let mut preview = app.dialog_state.live.on;+ super::dialogs::modal_placed(ctx, "Camera Settings", vec2(520.0, 420.0), t, place, |ui| {egui::Grid::new("cam-grid").num_columns(2).spacing([14.0, 9.0]).show(ui, |ui| {ui.label(tr("Type"));- egui::ComboBox::from_id_salt("cam-type").selected_text(if d.two_node { "Two-Node Camera" } else { "One-Node Camera" }).show_ui(ui, |ui| {+ craft_ui::ComboBox::from_id_salt("cam-type").selected_text(if d.two_node { "Two-Node Camera" } else { "One-Node Camera" }).show_ui(ui, |ui| {ui.selectable_value(&mut d.two_node, true, tr("Two-Node Camera"));ui.selectable_value(&mut d.two_node, false, tr("One-Node Camera"));});@@@ -350,23 -318,43 +356,25 @@@ pub fn light(app: &mut EffectcraftApp,}});ui.add_space(14.0);- ui.label(egui::RichText::new(tr("Note: Shadows are only cast from layers with Cast Shadows enabled.")).font(Tokens::ui(11.0)).color(t.text_dim));- ui.add_space(8.0);+ if falls_off(d.kind) {+ ui.label(egui::RichText::new(tr("Note: Shadows are only cast from layers with Cast Shadows enabled.")).font(Tokens::ui(11.0)).color(t.text_dim));+ ui.add_space(8.0);+ }- rects = buttons(ui, t, &mut ok, &mut close);+ rects = buttons(ui, t, &mut ok, &mut close, live.then_some(&mut preview));});+ app.dialog_state.live.on = preview;app.auto.add("dialog.light.ok", rects.0, "OK");app.auto.add("dialog.light.cancel", rects.1, "Cancel");+ if live {+ app.auto.add("dialog.light.preview", rects.2, "Preview");+ }app.dialog_state.light = d.clone();+ let (id, p) = light_command(&d);if ok || super::dialogs::ui_enter(ctx) {- let kind = d.kind;- let mut p = json!({- "name": d.name,- "kind": kind.label(),- "color": [d.color[0], d.color[1], d.color[2]],- "intensity": d.intensity,- });- if kind == LightKind::Spot {- p["coneAngle"] = json!(d.cone_angle);- p["coneFeather"] = json!(d.cone_feather);- }- if falls_off(kind) {- p["falloff"] = json!(d.falloff);- p["radius"] = json!(d.radius);- p["falloffDistance"] = json!(d.falloff_distance);- p["castsShadows"] = json!(d.casts_shadows);- p["shadowDarkness"] = json!(d.shadow_darkness);- p["shadowDiffusion"] = json!(d.shadow_diffusion);- }- let id = match d.layer {- Some(l) => {- p["layer"] = json!(l);- "layer.lightSettings"- }- None => "layer.newLight",- };- if let Err(e) = app.session.execute(id, p) {+ // A preview already made the edit (one undo step): OK keeps it.+ if !super::live_preview::keep(app)+ && let Err(e) = app.session.execute(id, p)+ {app.ui.status = e.to_string();}close = true;@@@ -380,37 -364,6 +388,37 @@@}}+/// The command Light Settings' OK runs, and its parameters.+fn light_command(d: &LightDraft) -> (&'static str, Value) {- let kind = KINDS[d.kind.min(3)];++ let kind = d.kind;+ let mut p = json!({+ "name": d.name,+ "kind": kind.label(),+ "color": [d.color[0], d.color[1], d.color[2]],+ "intensity": d.intensity,+ });+ if kind == LightKind::Spot {+ p["coneAngle"] = json!(d.cone_angle);+ p["coneFeather"] = json!(d.cone_feather);+ }- if kind != LightKind::Ambient {++ if falls_off(kind) {+ p["falloff"] = json!(d.falloff);+ p["radius"] = json!(d.radius);+ p["falloffDistance"] = json!(d.falloff_distance);+ p["castsShadows"] = json!(d.casts_shadows);+ p["shadowDarkness"] = json!(d.shadow_darkness);+ p["shadowDiffusion"] = json!(d.shadow_diffusion);+ }+ let id = match d.layer {+ Some(l) => {+ p["layer"] = json!(l);+ "layer.lightSettings"+ }+ None => "layer.newLight",+ };+ (id, p)+}+/// Menu/shortcut routing: commands that open a 3D settings dialog when invoked without params./// Returns true when a dialog was opened.pub fn route(app: &mut EffectcraftApp, id: &str, params: &Value) -> Result<bool, String> {diff --cc crates/ui-egui/src/panels/layer_styles_dialog.rsindex 440784b7e,14507b868..70ba5b5b0--- a/crates/ui-egui/src/panels/layer_styles_dialog.rs+++ b/crates/ui-egui/src/panels/layer_styles_dialog.rs@@@ -264,15 -277,67 +265,87 @@@ pub fn finish(app: &mut EffectcraftAppapp.dialog = None;}+/// Put the project and undo history back as `checkpoint` has them (nothing happens when nothing+/// changed since).+pub(crate) fn restore(app: &mut EffectcraftApp, checkpoint: Checkpoint) {+ let changed = !std::sync::Arc::ptr_eq(&app.session.project, &checkpoint.project);- app.session.project = checkpoint.project;- app.session.history = checkpoint.history;- app.session.sanitize_state();+ if changed {++ // Snapshot only when Cancel has something to restore: opening and cancelling without++ // edits must not copy the whole TextDoc.++ let edited = active_editor_snapshot(&app.session);++ app.session.project = checkpoint.project;++ app.session.history = checkpoint.history;++ app.session.sanitize_after_replacement(edited.as_ref());+ app.session.bump();++ } else {++ // No edit was committed, so nothing can have become invalid. In particular, do not++ // call sanitize_state here: its text-edit cleanup clones the whole TextDoc.++ app.session.history = checkpoint.history;+ }+ app.session.history.merge_key = None;+}+++ #[cfg(test)]+ mod tests {+ use super::*;+ use effectcraft_engine::Session;+ use effectcraft_engine::commands::text_edit::layer_doc;+ use effectcraft_engine::project::LayerId;+ use effectcraft_engine::project::styles::BLENDING;+ use serde_json::json;++ fn editing_app() -> (EffectcraftApp, u64) {+ let mut s = Session::default();+ s.execute("comp.new", json!({"name": "Styles", "width": 320, "height": 180, "duration": 1})).unwrap();+ let lid = s.execute("layer.newText", json!({"text": "abcdef"})).unwrap()["layer"].as_u64().unwrap();+ s.execute("text.edit", json!({"layer": lid, "caret": 3})).unwrap();+ (EffectcraftApp::new(s), lid)+ }++ fn editor_state(app: &EffectcraftApp) -> Option<(LayerId, u64, usize, usize)> {+ app.session.state.text_edit.as_ref().map(|e| (e.layer, e.session, e.anchor, e.caret))+ }++ #[test]+ fn cancel_keeps_an_open_text_editor_when_the_dialog_did_not_change_its_text() {+ let (mut app, lid) = editing_app();+ open(&mut app, &json!({"layer": lid, "style": BLENDING})).unwrap();+ // A live preview edit changes the project but not the edited Source Text.+ app.session.execute("prop.set", json!({"layer": lid, "path": "transform/opacity", "value": 40})).unwrap();+ let before = editor_state(&app);+ assert!(before.is_some());++ finish(&mut app, false);+ assert_eq!(editor_state(&app), before, "Cancel keeps an editor whose document it did not replace");+ }++ #[test]+ fn cancel_without_a_dialog_edit_keeps_the_open_editor_and_its_document_untouched() {+ let (mut app, lid) = editing_app();+ open(&mut app, &json!({"layer": lid, "style": BLENDING})).unwrap();+ let before = editor_state(&app);+ let project = app.session.project.clone();+ let undo = app.session.history.undo.len();+ assert!(before.is_some());++ finish(&mut app, false);+ assert!(std::sync::Arc::ptr_eq(&app.session.project, &project), "a no-op Cancel restores the same project");+ assert_eq!(app.session.history.undo.len(), undo, "and the same undo history");+ assert_eq!(editor_state(&app), before, "and leaves the open editor untouched");+ }++ #[test]+ fn cancel_replaces_an_open_text_editor_when_the_preview_changed_its_text() {+ let (mut app, lid) = editing_app();+ open(&mut app, &json!({"layer": lid, "style": BLENDING})).unwrap();+ app.session.execute("layer.setText", json!({"layer": lid, "text": "ab"})).unwrap();+ let preview = editor_state(&app).expect("still editing");+ assert_eq!(layer_doc(&app.session, LayerId(lid)).unwrap().text, "ab");++ finish(&mut app, false);+ let restored = editor_state(&app).expect("the editor survives the rollback");+ assert_eq!(layer_doc(&app.session, LayerId(lid)).unwrap().text, "abcdef", "Cancel restores the pre-dialog text");+ assert_ne!(restored.1, preview.1, "the restored editor starts a new epoch");+ assert_eq!((restored.2, restored.3), (2, 2), "the caret stays in the restored document");+ }+ }diff --cc crates/ui-egui/tests/it/main.rsindex 000000000,6b4c08912..44f09b4d6mode 000000,100644..100644--- a/crates/ui-egui/tests/it/main.rs+++ b/crates/ui-egui/tests/it/main.rs@@@ -1,0 -1,105 +1,106 @@@+ //! The crate's integration tests, one binary (each module is a former `tests/<name>.rs`).++ mod native_menu_text_keys;+ mod render_queue_snapshot;+ mod shared_docking_ui;+ mod ui_3d;+ mod ui_agent_audit;+ mod ui_angles;+ mod ui_audio_scrub;+ mod ui_azerty_shortcuts;+ mod ui_batch_switches;+ mod ui_blank_context_menus;+ mod ui_camera_tracker;+ mod ui_character_eyedropper;+ mod ui_color_hex;+ mod ui_comp_presets;+ mod ui_control_modifiers;++mod ui_dialog_preview;+ mod ui_dock_resize;+ mod ui_drag_drop;+ mod ui_effect_controls;+ mod ui_effect_drop_highlight;+ mod ui_effect_names;+ mod ui_font_search;+ mod ui_form_fit;+ mod ui_frame_step;+ mod ui_fx_editors;+ mod ui_gpu;+ mod ui_gradient_editor;+ mod ui_gradient_handles;+ mod ui_gradient_value;+ mod ui_graph_fit;+ mod ui_group_rename;+ mod ui_guide_layers;+ mod ui_inline_edit;+ mod ui_keyframes;+ mod ui_large_project;+ mod ui_layer_panel_zoom;+ mod ui_layer_source_picker;+ mod ui_light_settings;+ mod ui_live_preview;+ mod ui_locked_color;+ mod ui_media_browser_cache;+ mod ui_media_browser_copy_path;+ mod ui_menus;+ mod ui_new_primitive;+ mod ui_object_matte;+ mod ui_panel_focus;+ mod ui_panel_windows;+ mod ui_panels;+ mod ui_parameter_spacing;+ mod ui_presets_folder;+ mod ui_preview_align;+ mod ui_project_delete;+ mod ui_project_duplicate;+ mod ui_project_keyboard;+ mod ui_project_new_folder;+ mod ui_project_rows;+ mod ui_quick_offset;+ mod ui_ram_preview;+ mod ui_render_queue;+ mod ui_script_console;+ mod ui_scriptui;+ mod ui_scrolling;+ mod ui_settings_info;+ mod ui_tabs;+ mod ui_tail;+ mod ui_text_edit;+ mod ui_text_range_handles;+ mod ui_theme_favorites;+ mod ui_time_zoom_controls;+ mod ui_timeline_effect_label;+ mod ui_timeline_pan;+ mod ui_timeline_shapes;+ mod ui_timeline_switches;+ mod ui_timeline_trim;+ mod ui_timeline_zoom;+ mod ui_toolbar_gradient;+ mod ui_tracker;+ mod ui_unreadable_footage;+ mod ui_video_preview_off;+ mod ui_viewer;+ mod ui_viewers;+ mod ui_visual_review;+ mod ui_web_gpu_storage;+ mod ui_web_job_gpu;+ mod ui_web_offload;+ mod ui_workflow_selection;+ mod ui_workspace_focus;+ mod viewer_geometry;+ mod viewer_passive_display;++ /// Register the managed build's canonical craft-fonts checkout (`CRAFT_FONTS_DIR/fonts`) through+ /// the same directory source production scans for `EFFECTCRAFT_FONT_DIRS`. The UI tests then render+ /// real Japanese glyphs from the canonical external input instead of relying on host fonts.+ pub(crate) fn add_canonical_test_fonts() {+ use effectcraft_text::fonts::{self, DirectorySource};+ static REGISTER: std::sync::Once = std::sync::Once::new();+ REGISTER.call_once(|| {+ let Some(root) = std::env::var_os("CRAFT_FONTS_DIR") else { return };+ let dir = std::path::PathBuf::from(root).join("fonts");+ if dir.is_dir() {+ fonts::add_source(&DirectorySource { dirs: vec![dir] });+ }+ });+ }diff --cc crates/ui-egui/tests/it/ui_dialog_preview.rsindex 861548012,000000000..861548012mode 100644,000000..100644--- a/crates/ui-egui/tests/it/ui_dialog_preview.rs+++ b/crates/ui-egui/tests/it/ui_dialog_preview.rs