GitCorner

Code

ossartcrafteffectcraft🌐
665bfac0b339
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::AwaitScript(host) => {
                    self.script_waiters.push((host, 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;
        }
        let script_busy = self.session.script_ui.render_host.is_some();
        if !script_busy {
            self.session.poll_render();
            self.session.poll_offload();
        }
        let waiters = std::mem::take(&mut self.job_waiters);
        for (w, reply) in waiters {
            // Completed native snapshots are immutable, so even a later suspended script
            // cannot delay their replies. Other completions can edit its open undo group.
            if (script_busy && w.render.is_none()) || 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));
        }
    }

    /// A suspended script still owns its undo groups. Only its render, inspection and Stop
    /// run until the continuation reaches its next real script boundary; no scheduled callback
    /// or background analysis may edit the document in the middle of the group.
    fn tick_script_render(&mut self, ctx: &egui::Context) {
        let Some(host) = self.session.script_ui.render_host else { return };
        let result = match self.session.script_ui.poll_render {
            Some(poll) => poll(&mut self.session),
            None => {
                self.session.script_ui.render_host = None;
                Some(json!({"ok": false, "error": {"message": "The script render waiter is unavailable."}}))
            }
        };
        if let Some(result) = result {
            if let Some(message) = result["error"]["message"].as_str() {
                self.ui.status = message.to_string();
            } else if let Some(output) = result["output"].as_str().filter(|s| !s.is_empty()) {
                self.ui.status = output.lines().last().unwrap_or(output).to_string();
            }
            self.script_waiters.retain(|(id, reply)| {
                if *id == host {
                    let _ = reply.send(json!({"ok": true, "result": result}));
                    false
                } else {
                    true
                }
            });
        }
        // Do not interpret a close as permission to abandon the still-running script. Once
        // Stop finishes it, the normal unsaved-changes prompt can handle a new close request.
        if ctx.input(|i| i.viewport().close_requested()) {
            ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
        }
        self.drain_control(ctx, self.now);
        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(crate) 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, error } => {
                    if error {
                        self.push_error_toast(crate::ErrorToast::new([message.as_str()], None));
                    } else {
                        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();
                    crate::panels::project::forget_thumbnails(ctx);
                    // (frames made after it get keys of their own: see `Self::purge_stamp`)
                    self.purges = self.purges.wrapping_add(1);
                }
                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(ctx, frame);
        self.apply_gpu_failure(ctx);
        if self.gpu_failure_applied == Some(true) {
            self.close_after_device_loss(ctx);
            // On macOS the app quits through `-[NSApplication terminate:]` instead of closing the
            // window while AppKit's run loop is running (#341).
            craft_quit::on_close_request(ctx);
            return;
        }
        if self.session.script_ui.render_host.is_some() {
            self.tick_script_render(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);
        // #1089: a font-menu rescan runs off the UI thread. Poll it on the logic tick so the
        // status and the menu update even when the window is not painting.
        crate::panels::text_panels::poll_font_rescan(self, ctx);
        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));
        }
        // Plug-in Library: a finished job's toast (also polled with Roto, for other frontends).
        self.session.poll_library();
        // 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);
        if self.session.script_ui.render_host.is_some() {
            self.tick_script_render(ctx);
            return;
        }
        self.run_dialog_answers();
        if self.session.script_ui.render_host.is_some() {
            self.tick_script_render(ctx);
            return;
        }
        self.handle_events(ctx);
        if self.session.script_ui.render_host.is_some() {
            self.tick_script_render(ctx);
            return;
        }
        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);
        }
        if self.session.script_ui.render_host.is_some() {
            self.tick_script_render(ctx);
            return;
        }
        // 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);
        // A clean project may have passed the close guard before a control script created
        // unsaved edits and suspended. Cancel that same tick's close before the host handles it.
        if self.session.script_ui.render_host.is_some() {
            self.tick_script_render(ctx);
            return;
        }
        // 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;
        }
        panels::crypto_pick::pass_start(self, &ctx);
        self.frame(ui);
        panels::crypto_pick::upkeep(self, &ctx);
        #[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();
        if self.session.script_ui.render_host.is_some() {
            self.auto.begin_frame();
            ui.vertical_centered(|ui| {
                ui.add_space(32.0);
                ui.heading("Rendering script");
                ui.label("The script will continue when rendering finishes. Editing is paused to preserve its undo group.");
                if let Some(progress) = self.session.render_progress() {
                    ui.label(format!("{} / {} frames", progress.done, progress.total));
                }
                let stop = ui.button("Stop Render");
                self.auto.add("scriptRender.stop", stop.rect, "Stop Render");
                if stop.clicked() {
                    self.session.stop_render();
                }
            });
            return;
        }
        // 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();
        panels::viewer_tools::clear_sample_source(&ctx);
        if let Some(rect) = crate::color_picker::take_automation(&ctx) {
            self.auto.add("colorPicker.eyedropper", rect, "Eyedropper");
        }
        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));
        crate::color_picker::note_dialog(&ctx, self.dialog);
        // After the shortcuts, menus and header, which can replace the project (New, Open).
        self.ui.timeline.scope_links(self.session.script_ui.project_epoch);
        panels::effect_controls::scope_lock(self);
        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);
        }
    }

    /// Sets the status line and restarts its 5 s, also when the same text is still showing (a
    /// message set again would otherwise keep the time it was first shown).
    pub(crate) fn say(&mut self, ctx: &egui::Context, msg: String) {
        ctx.data_mut(|d| d.remove::<(f64, String)>(egui::Id::unique("status-since")));
        self.ui.status = msg;
    }

    /// 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;
        // A message cleared before its time (a click on it, Esc, another pick) forgets its time, so
        // the same message shown again later gets its own 5 s.
        if self.ui.status.is_empty() {
            ui.data_mut(|d| d.remove::<(f64, String)>(egui::Id::unique("status-since")));
        }
        while self.error_toasts.front().is_some_and(|toast| toast.shown_at.is_some_and(|at| now - at >= 4.0)) {
            self.error_toasts.pop_front();
        }
        let error = self.error_toasts.front_mut().and_then(|toast| toast.message_at(!self.ui.status.is_empty(), now)).map(str::to_owned);
        let notice = self.toast.as_ref().filter(|(_, at)| now - at < 4.0).map(|(message, _)| crate::ErrorToast::bounded_text([message.as_str()]));
        let mut msg = if !self.ui.status.is_empty() {
            // A background result must get its display time after the foreground status.
            // Keep its details available on hover while the status takes precedence.
            let status = crate::ErrorToast::bounded_text([self.ui.status.as_str()]);
            if let Some(details) = error { Some(format!("{status}\n{details}")) } else { Some(status) }
        } else {
            error.or_else(|| notice.clone())
        };
        if let Some(m) = &mut msg
            && let Some(notice) = &notice
            && m != notice
        {
            m.push('\n');
            m.push_str(notice);
        }
        if let Some(m) = msg {
            let t = &self.tokens;
            let summary = m.lines().next().unwrap_or_default().to_owned();
            let galley = ui.painter().layout_no_wrap(summary, 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()).on_hover_text(&m);
            if resp.clicked() {
                if self.ui.status.is_empty() {
                    self.error_toasts.pop_front();
                } else if let Some(index) = self.error_toasts.iter().rposition(|toast| toast.reported_by(&self.ui.status)) {
                    // The current status belongs to the latest matching import. Earlier
                    // imports can share its summary while carrying different details.
                    self.error_toasts.remove(index);
                }
                self.ui.status.clear();
                self.toast = None;
            }
            // "Preparing the GPU compositor…" stays until the compositor is attached (tens of
            // seconds on a cold shader cache), not 5 s: `finish_gpu_build` clears it, and the
            // worker's repaint brings that frame, so nothing needs to tick meanwhile. A click
            // still dismisses it.
            if self.ui.status == crate::GPU_PREPARING && self.gpu_initializing() {
                return;
            }
            ui.ctx().request_repaint_after(std::time::Duration::from_millis(500));
            if !self.ui.status.is_empty() {
                // Each message gets its own 5 s (a new one doesn't inherit the old one's time).
                let key = egui::Id::unique("status-since");
                let shown = ui.data(|d| d.get_temp::<(f64, String)>(key)).filter(|(_, m)| *m == self.ui.status);
                let since = shown.map_or(now, |(t, _)| t);
                ui.data_mut(|d| d.insert_temp(key, (since, self.ui.status.clone())));
                if now - since > 5.0 {
                    self.ui.status.clear();
                    ui.data_mut(|d| d.remove::<(f64, String)>(key));
                }
            }
        }
    }
}

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);
        self.tick_lut_files(ctx);
    }

    /// A LUT file in use changed on disk (#3493): the frames kept were rendered with the old one.
    /// Renders read it again by themselves; the watcher wakes the interface when no render did.
    /// The frame keys carry the generation ([`Self::frame_series`]), so the viewers show the
    /// frames rendered again, and a frame still rendering with the old LUT is never asked for.
    fn tick_lut_files(&mut self, ctx: &egui::Context) {
        if self.lut_watcher.is_none() {
            let wake = ctx.clone();
            self.lut_watcher = effectcraft_engine::lut_reload::Watcher::start(move || wake.request_repaint());
        }
        let generation = effectcraft_engine::lut_reload::generation();
        if generation != self.lut_generation {
            self.lut_generation = generation;
            self.frames.clear();
        }
    }

    /// One background worker tracks source availability and optional content reloads. It wakes
    /// the UI only for changes; availability remains enabled when automatic reload is off.
    fn tick_footage_reload(&mut self, ctx: &egui::Context) {
        use effectcraft_engine::footage_reload;
        if self.session.project.items.is_empty() && self.footage_watcher.is_none() {
            return;
        }
        if self.footage_watcher.is_none() {
            let wake = ctx.clone();
            self.footage_watcher = footage_reload::Watcher::start(self.session.services.clone(), move || wake.request_repaint());
        }
        let Some(watcher) = &mut self.footage_watcher else { return };
        watcher.set_focused(self.focused);
        // Which files are watched follows the project and the preference, not the frame.
        let key = (self.session.revision, self.session.prefs.import.auto_reload_footage.clone(), self.session.disk_cache.is_some());
        if self.footage_watch_key.as_ref() != Some(&key) {
            self.footage_watch_key = Some(key);
            watcher.update(&self.session);
        }
        let before = self.session.revision;
        if let Some(scan) = watcher.take() {
            match scan.apply(&mut self.session) {
                Ok(result) if result.get("stale").and_then(serde_json::Value::as_bool) == Some(true) => watcher.recheck(),
                Err(e) => self.ui.status = e.to_string(),
                _ => {}
            }
        }
        if self.session.revision != before {
            self.footage_watch_key = Some((self.session.revision, self.session.prefs.import.auto_reload_footage.clone(), self.session.disk_cache.is_some()));
            watcher.update(&self.session);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn dismissing_a_status_acknowledges_its_queued_error_behind_another() {
        let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
        app.session.events.push(effectcraft_engine::Event::Toast { message: "Earlier background error".into(), error: true });
        let ctx = egui::Context::default();
        app.handle_events(&ctx);
        app.report_import_errors("file.import", &json!({"errors":["Later import error"]}));
        ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
        let r = app.auto.elements.iter().find(|e| e.id == "toast").unwrap().rect;
        let pos = egui::pos2(r[0] + r[2] / 2.0, r[1] + r[3] / 2.0);
        for pressed in [true, false] {
            app.auto.elements.clear();
            let events = vec![
                egui::Event::PointerMoved(pos),
                egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() },
            ];
            ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
        }
        assert!(app.ui.status.is_empty());
        app.auto.elements.clear();
        ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
        assert!(app.auto.elements.iter().any(|e| e.label.contains("Earlier background error")));
        app.now = 4.1;
        app.auto.elements.clear();
        ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
        assert!(!app.auto.elements.iter().any(|e| e.id == "toast"), "the acknowledged later error must not reappear");
    }

    #[test]
    fn matching_import_summaries_only_acknowledge_the_latest_details() {
        for first in ["Shared error".to_owned(), "💥".repeat(20_000)] {
            let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
            app.report_import_errors("file.import", &json!({"errors":[first, "Earlier details"]}));
            app.report_import_errors("file.import", &json!({"errors":[first, "Later details"]}));
            let ctx = egui::Context::default();
            ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
            let r = app.auto.elements.iter().find(|e| e.id == "toast").unwrap().rect;
            let pos = egui::pos2(r[0] + 4.0, r[1] + 4.0);
            for pressed in [true, false] {
                let events = vec![
                    egui::Event::PointerMoved(pos),
                    egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() },
                ];
                ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
            }
            assert!(app.ui.status.is_empty());
            assert_eq!(app.error_toasts.len(), 1, "only the latest matching import is acknowledged, including long statuses");
            if first.len() < 100 {
                assert!(app.error_toasts.front().unwrap().message.contains("Earlier details"));
            }
        }
    }

    #[test]
    fn pending_error_notifications_are_bounded_and_report_omissions() {
        let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
        app.session.events.extend((0..40).map(|i| effectcraft_engine::Event::Toast { message: format!("Error {i}"), error: true }));
        let ctx = egui::Context::default();
        app.handle_events(&ctx);
        assert!(app.error_toasts.len() <= 32);
        assert_eq!(app.error_toasts.front().unwrap().message, "Error 0");
        assert_eq!(app.error_toasts.back().unwrap().message, "Error 39");
        ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
        app.now += 4.1;
        app.auto.elements.clear();
        ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
        assert!(app.auto.elements.iter().any(|e| e.label.contains("notifications omitted")));
        let long = format!("a{}", "💥".repeat(20_000));
        let toast = crate::ErrorToast::new([long.as_str()], None);
        assert!(toast.message.starts_with("a💥"));
        assert!(toast.message.len() < 20 << 10);
        assert!(toast.message.capacity() < 64 << 10, "the large input allocation must not remain retained");
        assert!(toast.message.contains("truncated"));
    }

    #[test]
    fn consecutive_background_errors_are_each_shown_before_expiring_or_dismissal() {
        for dismiss in [false, true] {
            let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
            app.session.events.extend([
                effectcraft_engine::Event::Toast { message: "First.vectorcraft failed".into(), error: true },
                effectcraft_engine::Event::Toast { message: "A routine notice".into(), error: false },
                effectcraft_engine::Event::Toast { message: "Second.vectorcraft failed".into(), error: true },
            ]);
            let ctx = egui::Context::default();
            app.handle_events(&ctx);
            ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
            assert!(app.auto.elements.iter().any(|e| e.id == "toast" && e.label.contains("First.vectorcraft")));
            if dismiss {
                let r = app.auto.elements.iter().find(|e| e.id == "toast").unwrap().rect;
                let pos = egui::pos2(r[0] + r[2] / 2.0, r[1] + r[3] / 2.0);
                for pressed in [true, false] {
                    app.auto.elements.clear();
                    let events = vec![
                        egui::Event::PointerMoved(pos),
                        egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() },
                    ];
                    ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
                }
                app.now = 0.1;
            } else {
                app.now = 4.1;
            }
            app.auto.elements.clear();
            ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
            assert!(app.auto.elements.iter().any(|e| e.id == "toast" && e.label.contains("Second.vectorcraft")));
            assert!(!app.auto.elements.iter().any(|e| e.label.contains("First.vectorcraft")));
            app.now += 4.1;
            app.auto.elements.clear();
            ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
            assert!(!app.auto.elements.iter().any(|e| e.id == "toast"));
        }
    }

    #[test]
    fn an_unshown_error_survives_a_replacement_foreground_status() {
        let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
        app.ui.status = "First foreground status".into();
        app.session.events.push(effectcraft_engine::Event::Toast { message: "An unseen import error".into(), error: true });
        let ctx = egui::Context::default();
        app.handle_events(&ctx);
        ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
        app.ui.status = "Another foreground status".into();
        for now in [1.0, 3.0, 6.0, 6.1] {
            app.now = now;
            app.auto.elements.clear();
            ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
        }
        assert!(app.auto.elements.iter().any(|e| e.id == "toast" && e.label.contains("unseen import error")));
    }

    #[test]
    fn dismissing_a_status_keeps_an_unshown_background_error() {
        let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
        app.ui.status = "A local drop failed".into();
        app.session.events.push(effectcraft_engine::Event::Toast { message: "A later background import failed".into(), error: true });
        let ctx = egui::Context::default();
        app.handle_events(&ctx);
        ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
        let click = |app: &mut EffectcraftApp| {
            let r = app.auto.elements.iter().find(|e| e.id == "toast").unwrap().rect;
            let pos = egui::pos2(r[0] + r[2] / 2.0, r[1] + r[3] / 2.0);
            for pressed in [true, false] {
                app.auto.elements.clear();
                let events = vec![
                    egui::Event::PointerMoved(pos),
                    egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() },
                ];
                ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
            }
        };
        click(&mut app);
        assert!(app.ui.status.is_empty());
        app.auto.elements.clear();
        ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
        assert!(app.auto.elements.iter().any(|e| e.id == "toast" && e.label.contains("later background import failed")));
        click(&mut app);
        assert!(app.error_toasts.is_empty(), "the displayed error can be dismissed too");
        app.report_import_errors("file.import", &json!({"errors": ["An immediate import error", "Another import error"]}));
        app.auto.elements.clear();
        ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
        click(&mut app);
        assert!(app.ui.status.is_empty());
        assert!(app.error_toasts.is_empty(), "dismissing an error status acknowledges its own details");
    }

    #[test]
    fn a_later_status_does_not_extend_an_error_already_shown() {
        let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
        app.session.events.push(effectcraft_engine::Event::Toast { message: "An earlier error".into(), error: true });
        let ctx = egui::Context::default();
        app.handle_events(&ctx);
        ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
        app.ui.status = "An unrelated later status".into();
        for now in [1.0, 4.0, 7.0, 7.1] {
            app.now = now;
            app.auto.elements.clear();
            ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
        }
        assert!(!app.auto.elements.iter().any(|e| e.id == "toast"));
    }

    #[test]
    fn import_error_details_survive_a_warning_event() {
        let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
        app.report_import_errors("file.import", &json!({"errors": ["first failed file", "second failed file"]}));
        app.session.events.push(effectcraft_engine::Event::Toast { message: "Sequence has missing frames".into(), error: false });
        let ctx = egui::Context::default();
        app.handle_events(&ctx);
        ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
        assert!(app.auto.elements.iter().any(|e| e.id == "toast" && e.label.contains("second failed file")));
        assert!(app.auto.elements.iter().any(|e| e.id == "toast" && e.label.contains("missing frames")));
    }

    #[test]
    fn a_foreground_status_does_not_extend_a_confirmation_toast() {
        let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
        app.ui.status = "A foreground status".into();
        app.toast = Some(("Saved".into(), 0.0));
        let ctx = egui::Context::default();
        for now in [0.0, 3.0, 6.0, 6.1] {
            app.now = now;
            app.auto.elements.clear();
            ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
        }
        assert!(!app.auto.elements.iter().any(|e| e.id == "toast"));
    }

    #[test]
    fn a_new_status_does_not_revive_an_expired_toast() {
        let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
        app.ui.status = "A new status".into();
        app.toast = Some(("An old toast".into(), 0.0));
        app.now = 8.0;
        let ctx = egui::Context::default();
        ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
        assert!(app.auto.elements.iter().all(|e| !e.label.contains("old toast")));
        app.ui.status.clear();
        app.auto.elements.clear();
        app.now = 8.1;
        ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
        assert!(!app.auto.elements.iter().any(|e| e.id == "toast"));
    }

    #[test]
    fn a_status_message_does_not_expire_a_background_import_error() {
        let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
        app.ui.status = "A local drop failed".into();
        app.session.events.push(effectcraft_engine::Event::Toast { message: "Imported 1 item. Failed first file\nFailed second file".into(), error: true });
        let ctx = egui::Context::default();
        app.handle_events(&ctx);
        for now in [0.0, 3.0, 6.0] {
            app.now = now;
            ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
        }
        assert!(app.ui.status.is_empty());
        app.auto.elements.clear();
        app.now = 6.1;
        ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
        assert!(app.auto.elements.iter().any(|e| e.id == "toast" && e.label.contains("Failed second file")), "{:?}", app.auto.elements);
    }
}