EffectCraft: An open-source motion graphics and compositing tool written by scratch in pure Rust
Preserve bug fixes after main module moves and bound workspace migration
dotCooCoo97ef73d59210
diff --cc crates/render/src/disk_cache.rsindex 4fa2e1cb3,4fa2e1cb3..26e684732--- a/crates/render/src/disk_cache.rs+++ b/crates/render/src/disk_cache.rs@@@ -772,7 -772,7 +772,7 @@@ fn decode_layer(p: &[u8]) -> Option<Buf// ---------------------------------------------------------------- content keys/// Bump when rendering changes in a way that makes old disk entries wrong.--const RENDER_VERSION: &str = "effectcraft-render-2";++const RENDER_VERSION: &str = "effectcraft-render-3";fn hash_debug(h: &mut Hash128, v: &impl std::fmt::Debug) {h.write(format!("{v:?}").as_bytes());@@@ -1001,6 -1001,6 +1001,28 @@@ mod testsassert!(dc.get_frame(42).is_none());}++ #[test]++ fn previous_renderer_frames_are_not_reused() {++ use effectcraft_project::{Comp, ItemKind, Project};++ use effectcraft_time::{FrameRate, Tick};++++ let mut project = Project::default();++ let comp = Comp::new(2, 2, FrameRate::FPS_30, Tick::from_seconds_f64(1.0));++ let id = project.add_item("Cached composition", effectcraft_color::Label::None, None, ItemKind::Comp(comp.into()));++ let key = frame_key(comp_content_key(&project, id), 0, 1000, 0);++ let previous_key = 188276472871424236106264377269312920732;++ let dir = tmpdir("previous-renderer");++ {++ let cache = DiskCache::open(&dir, 1 << 30).unwrap();++ cache.put_frame_now(previous_key, 2, 2, &[9; 16]);++ }++ let cache = DiskCache::open(&dir, 1 << 30).unwrap();++ assert_eq!(cache.get_frame(previous_key).unwrap().rgba, vec![9; 16]);++ assert!(cache.get_frame(key).is_none());++ cache.put_frame_now(key, 2, 2, &[17; 16]);++ assert_eq!(cache.get_frame(key).unwrap().rgba, vec![17; 16]);++ }++#[test]fn persists_across_restarts_and_clears() {let dir = tmpdir("persist");diff --cc crates/render/src/pipeline.rsindex 000000000,92b5b7f5c..faa21294emode 000000,100644..100644--- a/crates/render/src/pipeline.rs+++ b/crates/render/src/pipeline.rs@@@ -1,0 -1,886 +1,888 @@@+ use super::accel::{Accelerator, Backend, CpuFx, FxStep, FxTarget};+ use super::footage::{FootageSource, is_vector_footage};+ use super::frames::{blend_frames, content_bounds, field_frame, frame_blend_mode, frame_position, frame_size, interpret_pixels, roi_inside};+ use super::fx_host::{FxHost, essential_overrides};+ use super::opts::{Collapse3d, LayerTiming, MAX_THROUGH, RenderOpts, Through};+ use super::*;++ impl<'a> Renderer<'a> {+ pub fn new(project: &'a Project, footage: &'a dyn FootageSource, opts: RenderOpts) -> Renderer<'a> {+ Renderer {+ project,+ footage,+ expr: None,+ opts,+ cache: None,+ profile: None,+ accel: None,+ depth: 0,+ pipe: color::Pipe::of(&project.settings),+ outer: None,+ opacity_mul: 1.0,+ collapse3d: None,+ inherited: None,+ defer_dof: false,+ top: true,+ through: [None; MAX_THROUGH],+ through_lost: false,+ }+ }++ /// The layer cache to keep this render's buffers in: none once its footage reads were+ /// called off, as they may have come back empty ([`FootageSource::called_off`], #329).+ pub(crate) fn cache_to_keep(&self) -> Option<&'a LayerCache> {+ self.cache.filter(|_| !self.footage.called_off())+ }++ /// A layer's Quality switch, limited by the precomp layers above it when+ /// [`RenderOpts::nested_switches`] is on.+ pub fn quality(&self, layer: &Layer) -> Quality {+ let rank = |q: Quality| match q {+ Quality::Best => 0,+ Quality::Draft => 1,+ Quality::Wireframe => 2,+ };+ match self.inherited {+ Some((q, _)) if rank(q) > rank(layer.switches.quality) => q,+ _ => layer.switches.quality,+ }+ }++ /// A layer's Motion Blur switch, limited by the precomp layers above it.+ pub(crate) fn layer_motion_blur(&self, layer: &Layer) -> bool {+ layer.switches.motion_blur && self.inherited.is_none_or(|(_, mb)| mb)+ }++ /// The renderer for the nested comp of precomp layer `layer`: its switches pass down when+ /// [`RenderOpts::nested_switches`] is on.+ fn nested_through(&self, layer: &Layer) -> Renderer<'a> {+ let mut sub = self.nested();+ if self.opts.nested_switches {+ sub.inherited = Some((self.quality(layer), self.layer_motion_blur(layer)));+ }+ sub+ }++ /// The render options one level down (precomps, collapsed precomps, comps read by effects):+ /// guide layers render only in their own comp, never when it is nested.+ fn nested_opts(&self) -> RenderOpts {+ RenderOpts { guides: false, ..self.opts }+ }++ /// A renderer for nested work (precomps, layers read by effects): one level deeper.+ pub(crate) fn nested(&self) -> Renderer<'a> {+ Renderer {+ opts: self.nested_opts(),+ depth: self.depth + 1,+ outer: None,+ opacity_mul: 1.0,+ collapse3d: None,+ defer_dof: false,+ top: false,+ through: [None; MAX_THROUGH],+ through_lost: false,+ ..*self+ }+ }++ /// A precomp layer's nested comp for an accelerator to render resident (no CPU render and+ /// upload of the nested frame): the renderer one level down, the comp, its time and the+ /// buffer scale, exactly as [`Self::layer_source`]'s comp branch would render it. `None`+ /// when that branch does more (composition proxy, Essential Properties overrides, frame+ /// blending, recursion) or draws nothing (outside the nested comp's span): use the CPU path.+ pub fn precomp_source(&self, ctx: &EvalCtx, layer: &Layer) -> Option<(Renderer<'a>, ItemId, Tick, f64)> {+ let LayerSource::Comp { item } = layer.source else { return None };+ if layer.switches.adjustment || self.project.comp_contains(item, ctx.comp_id) {+ return None;+ }+ let nc = self.project.comp(item)?;+ let lt = ctx.nested_time(layer);+ if self.content_times(ctx, layer).is_some() {+ return None;+ }+ if !nc.covers(lt) || self.proxy_for(item).is_some() || !essential_overrides(ctx, layer).is_empty() || frame_blend_mode(ctx, layer) != FrameBlend::Off {+ return None;+ }+ let s = self.opts.scale;+ let bs = if s < 1.0 && nc.preserve_resolution { 1.0 } else { s };+ let base = self.nested_through(layer);+ Some((Renderer { opts: RenderOpts { scale: bs, ..base.opts }, ..base }, item, lt, bs))+ }++ /// The nested comp of a precomp layer whose transformations collapse into this comp: the+ /// Collapse Transformations switch is on and the layer has no masks, effects or layer+ /// styles (those force a flattened render of the precomp, as in After Effects).+ pub fn collapsed(&self, ctx: &EvalCtx, layer: &Layer) -> Option<ItemId> {+ if !layer.switches.collapse || layer.switches.adjustment || self.depth > 12 {+ return None;+ }+ let LayerSource::Comp { item } = &layer.source else { return None };+ if self.project.comp_contains(*item, ctx.comp_id) || self.project.comp(*item).is_none() {+ return None;+ }+ if layer.masks().is_some_and(|m| !m.children.is_empty()) {+ return None;+ }+ if layer.switches.effects && layer.effects().is_some_and(|fx| fx.groups().any(|g| g.enabled)) {+ return None;+ }+ if styles::active(ctx, layer) {+ return None;+ }+ // Instance overrides (Essential Properties) need the nested comp rendered on its own.+ if !effectcraft_project::essential::overridden(layer).is_empty() {+ return None;+ }+ Some(*item)+ }++ /// A renderer and context that draw a collapsed precomp's layers straight into this comp:+ /// their transforms are concatenated with the precomp layer's (one resample, no+ /// rasterisation at the precomp's bounds), their opacity multiplied by `opacity`, and their+ /// 3D layers use this comp's camera and lights.+ pub fn collapse_into(&self, ctx: &EvalCtx<'a>, layer: &'a Layer, item: ItemId, opacity: f32) -> Option<(Renderer<'a>, EvalCtx<'a>)> {+ let nc = self.project.comp(item)?;+ let t = ctx.nested_time(layer);+ if !nc.covers(t) {+ return None;+ }+ let nctx = EvalCtx { comp_id: item, comp: nc, time: t, ..*ctx };+ let (l2c, _) = ctx.layer_to_comp(layer);+ let outer = Some(self.outer.map_or(l2c, |o| o * l2c));+ let world = ctx.world_matrix(layer);+ let c3 = Collapse3d {+ world: self.collapse3d.map_or(world, |c| c.world * world),+ cam: three_d::compose::camera_for(self, ctx),+ parent: self.collapse3d.map_or(*ctx, |c| c.parent),+ };+ // Motion blur follows the precomp layer's own motion too.+ let link = Through { comp_id: ctx.comp_id, comp: ctx.comp, time: ctx.time, layer, blur: self.mb_on(ctx, layer) };+ let mut through = self.through;+ let slot = through.iter_mut().find(|t| t.is_none());+ let through_lost = self.through_lost || slot.is_none();+ if let Some(slot) = slot {+ *slot = Some(link);+ }+ Some((+ Renderer { opts: self.nested_opts(), depth: self.depth + 1, outer, opacity_mul: opacity, collapse3d: Some(c3), through, through_lost, ..*self },+ nctx,+ ))+ }++ pub(crate) fn opacity_mul(&self) -> f32 {+ self.opacity_mul+ }++ /// Draw a collapsed 2D precomp layer: nested layers blend straight into `canvas` with their+ /// own modes (Normal precomp, no matte); otherwise they are drawn into an isolated buffer+ /// that then takes the precomp layer's track matte, Preserve Transparency and blend mode.+ /// Returns the region left to re-quantise (nested layers drawn straight into `canvas`+ /// quantise their own footprints).+ pub(crate) fn draw_collapsed(&self, ctx: &EvalCtx<'a>, layer: &Layer, item: ItemId, canvas: &mut Image, blank: bool) -> Region {+ let opacity = ctx.opacity(layer) as f32 * self.opacity_mul;+ if opacity <= 0.0 {+ return Region::Empty;+ }+ let matte = layer.track_matte.is_some_and(|tm| tm.layer != layer.id && ctx.comp.layer(tm.layer).is_some());+ if layer.blend_mode == BlendMode::Normal && !matte && !layer.preserve_transparency {+ if let Some((sub, nctx)) = self.collapse_into(ctx, layer, item, opacity) {+ sub.draw_comp(&nctx, canvas, blank);+ }+ return Region::Empty;+ }+ let Some((sub, nctx)) = self.collapse_into(ctx, layer, item, 1.0) else { return Region::Empty };+ let mut iso = Image::new(canvas.width, canvas.height);+ sub.draw_comp(&nctx, &mut iso, true);+ self.composite_iso(ctx, layer, iso, canvas, opacity);+ Region::Full+ }++ /// Whether `layer`'s processed buffer (source → masks → effects) is cached and the same as+ /// one frame earlier: drawing it from the layer cache (an accelerator uploads it once) beats+ /// re-running its effects every frame.+ pub fn layer_is_static(&self, ctx: &EvalCtx, layer: &Layer) -> bool {+ if self.cache.is_none() {+ return false;+ }+ let (scale, draft, blur) = (self.raster_scale(ctx, layer), self.opts.draft, self.mb_on(ctx, layer));+ let prev = ctx.time - ctx.comp.frame_rate.frame_duration();+ let now = cache::layer_key(ctx, layer, scale, draft, blur);+ now.is_some() && now == cache::layer_key(&ctx.at(prev), layer, scale, draft, blur)+ }++ /// Rasterisation scale of a layer's source: the output scale, or — for text and shape layers,+ /// which are always continuously rasterised (#390, #751), and Continuously Rasterize vector+ /// footage — the output scale times the layer's on-screen scale (quarter-octave steps, rounded+ /// up, so vector content is drawn at its final size and stays sharp when scaled up).+ pub fn raster_scale(&self, ctx: &EvalCtx, layer: &Layer) -> f64 {+ let s = self.opts.scale;+ let continuous = match layer.source {+ LayerSource::Text | LayerSource::Shape => true,+ LayerSource::Footage { item } => {+ layer.switches.collapse && matches!(self.project.item(item).map(|i| &i.kind), Some(ItemKind::Footage(f)) if is_vector_footage(f))+ }+ _ => false,+ };+ if !continuous {+ return s;+ }+ let (l2c, _) = ctx.layer_to_comp(layer);+ let m = self.outer.map_or(l2c, |o| o * l2c);+ let a = layer.transform().map(|tr| ctx.v3(layer, tr, "anchor", [0.0; 3])).unwrap_or([0.0; 3]);+ let p0 = m.apply(vec2(a[0], a[1]));+ let px = m.apply(vec2(a[0] + 1.0, a[1]));+ let py = m.apply(vec2(a[0], a[1] + 1.0));+ let k = ((px.x - p0.x).hypot(px.y - p0.y)).max((py.x - p0.x).hypot(py.y - p0.y));+ if !k.is_finite() || k <= 1e-6 {+ return s;+ }+ // The step is rounded up past rounding noise only: an unscaled layer whose position isn't+ // a whole number maps the unit vectors to lengths a hair over 1, which must stay 1 (#390:+ // rounded up to 2^¼, unscaled text was drawn larger and resampled, softer).+ let mut k = 2f64.powf((k.log2() * 4.0 - 1e-6).ceil() / 4.0).clamp(1.0 / 16.0, 64.0);+ // Keep the buffer within about 16 million pixels.+ if let Some(b) = content_bounds(ctx, layer) {+ let area = ((b[2] - b[0]) * (b[3] - b[1])).max(1.0) * s * s;+ k = k.min((16.0e6 / area).sqrt().max(1.0));+ }+ s * k+ }++ /// Draw a Wireframe-quality layer: its bounds as a one-pixel outline.+ pub(crate) fn draw_wireframe(&self, ctx: &EvalCtx, layer: &Layer, canvas: &mut Image) {+ for (x, y) in self.wireframe_pixels(ctx, layer, (canvas.width, canvas.height)) {+ canvas.set(x, y, [1.0, 1.0, 1.0, 1.0]);+ }+ }++ pub(crate) fn ctx(&self, comp_id: ItemId, comp: &'a Comp, t: Tick) -> EvalCtx<'a> {+ EvalCtx { project: self.project, comp_id, comp, time: t, expr: self.expr, footage: Some(self.footage) }+ }++ /// This renderer with another accelerator (or none): the passes of+ /// [`passes::in_passes`] render with the accelerator, its CPU fallback without.+ pub fn with_accel(&self, accel: Option<&'a dyn Accelerator>) -> Renderer<'a> {+ Renderer { accel, ..*self }+ }++ /// The accelerator to use for this render, if any (see [`Backend`]).+ pub fn active_accel(&self) -> Option<&'a dyn Accelerator> {+ let a = self.accel?;+ match self.opts.backend {+ Backend::Cpu => None,+ Backend::Gpu => Some(a),+ Backend::Auto => self.project.settings.gpu_acceleration.then_some(a),+ }+ }++ /// Render a composition at comp time `t` (transparent background, comp size × scale).+ /// Top-level frames go to the GPU when [`Self::active_accel`] is set and handles them.+ pub fn comp_frame(&self, comp_id: ItemId, t: Tick) -> Image {+ // Classic 3D runs composite on the GPU too (M12.7), so Auto sends 3D comps there as well;+ // Auto renders each comp on whichever compositor measured faster ([`AutoPick`]).+ if self.depth == 0+ && let Some(a) = self.active_accel()+ {+ let auto = self.frame_auto(a, comp_id, false);+ if auto.is_none_or(|(p, key)| p.choose(key)) {+ let t0 = web_time::Instant::now();+ if let Some(img) = a.comp_frame(self, comp_id, t) {+ if let Some((p, key)) = auto {+ p.record(key, true, t0.elapsed().as_secs_f64() * 1e3);+ }+ return img;+ }+ if let Some((p, key)) = auto {+ p.declined(key);+ }+ }+ let t0 = web_time::Instant::now();+ let img = self.comp_frame_cpu(comp_id, t);+ if let Some((p, key)) = auto {+ p.record(key, false, t0.elapsed().as_secs_f64() * 1e3);+ }+ return img;+ }+ self.comp_frame_cpu(comp_id, t)+ }++ /// The Auto timing history and key for a top-level frame of `comp` (`None` unless the+ /// backend is [`Backend::Auto`] and the accelerator keeps history).+ pub fn frame_auto(&self, a: &'a dyn Accelerator, comp: ItemId, display: bool) -> Option<(&'a AutoPick, AutoKey)> {+ if self.opts.backend != Backend::Auto || self.opts.roi.is_some() {+ return None;+ }+ Some((a.auto_pick()?, AutoKey::new(comp, self.opts.scale, display)))+ }++ /// [`Self::comp_frame`] on the CPU compositor only.+ pub fn comp_frame_cpu(&self, comp_id: ItemId, t: Tick) -> Image {+ let Some(comp) = self.project.comp(comp_id) else { return Image::new(1, 1) };+ let s = self.opts.scale;+ let (w, h) = frame_size(comp.width, comp.height, s);+ // Region of interest on a comp with 3D layers: render the frame and crop it. A region+ // reaching past the comp frame (the Extended Viewer) renders Classic 3D natively — the+ // planes project through the offset camera — and Advanced 3D as the frame, padded.+ if self.depth == 0+ && let Some(r) = self.opts.roi+ && comp.has_3d()+ && (roi_inside(r, comp.width, comp.height) || comp.renderer == effectcraft_project::Renderer::Advanced3D)+ {+ let full = Renderer { opts: RenderOpts { roi: None, ..self.opts }, ..*self }.comp_frame(comp_id, t);+ let (x0, y0) = ((r[0] * s).round() as i64, (r[1] * s).round() as i64);+ let (rw, rh) = (((r[2] * s).round() as u32).max(1), ((r[3] * s).round() as u32).max(1));+ let mut out = Image::new(rw, rh);+ for y in 0..rh as i64 {+ let sy = y + y0;+ if sy < 0 || sy >= full.height as i64 {+ continue;+ }+ for x in 0..rw as i64 {+ let sx = x + x0;+ if sx >= 0 && sx < full.width as i64 {+ out.data[(y * rw as i64 + x) as usize] = full.data[(sy * full.width as i64 + sx) as usize];+ }+ }+ }+ return out;+ }+ let (w, h) = match self.roi_offset() {+ Some((_, _, rw, rh)) => (rw, rh),+ None => (w, h),+ };+ let mut canvas = Image::new(w, h);+ if self.depth > 16 {+ return canvas;+ }+ let ctx = self.ctx(comp_id, comp, t);+ self.draw_comp(&ctx, &mut canvas, true);+ // The canvas is already quantised after every layer; only re-encoding changes it.+ if let Some(c) = self.pipe.from_blend() {+ color::convert(&mut canvas, &c);+ self.pipe.quantize(&mut canvas);+ }+ // The top-level comp leaves the working space for the (sRGB) display / output.+ if self.depth == 0+ && let Some(c) = self.pipe.output()+ {+ color::convert(&mut canvas, &c);+ self.pipe.quantize(&mut canvas);+ }+ if self.depth == 0+ && let Some((lin, mode, enc)) = self.pipe.output_hdr()+ {+ color::output_hdr(&mut canvas, lin, mode, enc);+ self.pipe.quantize(&mut canvas);+ }+ canvas+ }++ /// Draw a comp's layers (bottom to top) into `canvas` (blending space).+ /// `blank`: the canvas is fully transparent (lets the first layer skip re-quantising).+ fn draw_comp(&self, ctx: &EvalCtx<'a>, canvas: &mut Image, mut blank: bool) {+ // Bottom-to-top, with runs of consecutive 3D layers depth-sorted (farthest first).+ let visible = self.visible_layers(ctx);+ let mut i = 0;+ while i < visible.len() {+ if visible[i].is_3d() {+ let mut j = i;+ while j < visible.len() && visible[j].is_3d() {+ j += 1;+ }+ three_d::compose::draw_run(self, ctx, &visible[i..j], canvas);+ i = j;+ self.pipe.quantize(canvas);+ blank = false;+ } else {+ let changed = match self.collapsed(ctx, visible[i]) {+ Some(item) => self.draw_collapsed(ctx, visible[i], item, canvas, blank),+ None => self.draw_layer(ctx, visible[i], canvas, blank),+ };+ i += 1;+ // 8/16 bpc: the comp is an integer buffer after every layer (only the pixels the+ // layer touched need re-quantising).+ self.pipe.quantize_region(canvas, changed);+ blank = false;+ }+ }+ }++ /// Evaluate an effect instance's parameters.+ fn effect_params(&self, ctx: &EvalCtx, layer: &Layer, g: &effectcraft_project::PropGroup) -> Params {+ // Nested groups (Paint strokes, Puppet meshes and pins) are flattened too.+ effectcraft_effects::flatten_params(g, &mut |pr| ctx.value(layer, pr))+ }++ pub(crate) fn apply_effects(&self, ctx: &EvalCtx, layer: &Layer, buf: Buf, adjustment: bool) -> Buf {+ self.apply_effects_timed(ctx, layer, buf, adjustment, usize::MAX, None)+ }++ /// Run the first `limit` effects of the layer's stack (by position; disabled ones count) on+ /// `buf` (layer space, or the comp below for an adjustment layer).+ fn apply_effects_timed(&self, ctx: &EvalCtx, layer: &Layer, mut buf: Buf, adjustment: bool, limit: usize, timing: Option<&mut Vec<(String, f64)>>) -> Buf {+ // The comp below an adjustment layer is not in its layer space: it stays as it is.+ let origin = if adjustment { [0.0; 2] } else { ctx.effect_bounds(layer).1 };+ buf.rebase(origin);+ let mut out = self.effect_space_stack(ctx, layer, buf, adjustment, limit, timing, origin);+ out.rebase([-origin[0], -origin[1]]);+ out+ }++ /// [`Renderer::apply_effects_timed`] on a buffer already in effect space (measured from+ /// `origin`, in layer coordinates); the result stays in effect space.+ #[allow(clippy::too_many_arguments)]+ fn effect_space_stack(+ &self,+ ctx: &EvalCtx,+ layer: &Layer,+ buf: Buf,+ adjustment: bool,+ limit: usize,+ timing: Option<&mut Vec<(String, f64)>>,+ origin: [f64; 2],+ ) -> Buf {+ let mut t = CpuFx { accel: self.active_accel(), levels: self.pipe.levels, buf: Some(buf) };+ self.run_effect_stack(ctx, layer, adjustment, limit, timing, origin, &mut t);+ t.buf.unwrap_or_else(|| Buf { img: Image::new(1, 1), offset: [0.0; 2], scale: self.opts.scale })+ }++ /// Run the layer's video effect stack on `target` (in effect space, measured from `origin`+ /// in layer coordinates): runs of GPU-capable effects go to [`FxTarget::gpu`] (when an+ /// accelerator is active and supports them), the rest to [`FxTarget::cpu`] one by one+ /// (quantised to the bit depth after each).+ #[allow(clippy::too_many_arguments)]+ pub(crate) fn run_effect_stack(+ &self,+ ctx: &EvalCtx,+ layer: &Layer,+ adjustment: bool,+ limit: usize,+ mut timing: Option<&mut Vec<(String, f64)>>,+ origin: [f64; 2],+ target: &mut dyn FxTarget,+ ) {+ if !layer.switches.effects {+ return;+ }+ let Some(fx) = layer.effects() else { return };+ let lt = layer.layer_time(ctx.time);+ let layer_size = ctx.effect_bounds(layer).0;+ // #659: an authored layer's buffer spans only its painted content while the stack works+ // on the layer's whole region (`layer_size`): give the buffer the room a sized source+ // already has, so tiling or displacement can place pixels outside the content instead+ // of losing them at its edge. Only when something will actually run, and not for an+ // adjustment layer, whose buffer is the comp below and already spans it.+ if !adjustment+ && fx.groups().any(|g| g.enabled && matches!(&g.kind, GroupKind::Effect { effect } if effectcraft_effects::find(effect).is_some_and(|s| !effectcraft_effects::audio_fx::is_audio_effect(s.id)))) {+ target.cover(layer_size);+ }+ let mut mask_shapes = masks::shapes(ctx, layer);+ if origin != [0.0; 2] {+ for q in mask_shapes.iter_mut().flat_map(|m| m.points.iter_mut()) {+ *q = [q[0] - origin[0], q[1] - origin[1]];+ }+ }+ // Capture once, before preceding effects can expand or replace the input. An+ // adjustment stack's original is the comp below, not its solid source.+ let needs_original =+ fx.groups().take(limit).any(|g| g.enabled && matches!(&g.kind, GroupKind::Effect { effect } if effect == "ec.channel.cccomposite"));+ let mut original = None;+ if needs_original {+ target.cpu(&mut |buf| {+ original = Some(buf.clone());+ buf+ });+ }+ let host = FxHost { r: self, ctx, layer, origin, index: 0, original: original.as_ref() };+ let env = EffectEnv {+ masks: &mask_shapes,+ host: Some(&host),+ comp_time: ctx.time.seconds(),+ frame_rate: ctx.comp.frame_rate.as_f64(),+ effect_index: 0,+ working_space: self.pipe.space,+ working_linear: self.pipe.linear,+ float_depth: self.pipe.levels.is_none(),+ shutter: self.mb_on(ctx, layer).then_some((ctx.comp.shutter_angle, ctx.comp.shutter_phase, ctx.comp.motion_blur_samples)),+ };+ // Video effects in stack order (index, group, spec); disabled and audio effects skipped.+ let stack: Vec<(usize, &effectcraft_project::PropGroup, &'static effectcraft_effects::EffectSpec)> = fx+ .groups()+ .enumerate()+ .take_while(|(i, _)| *i < limit)+ .filter(|(_, g)| g.enabled)+ .filter_map(|(i, g)| match &g.kind {+ GroupKind::Effect { effect } => effectcraft_effects::find(effect).map(|s| (i, g, s)),+ _ => None,+ })+ .filter(|(_, _, s)| !effectcraft_effects::audio_fx::is_audio_effect(s.id))+ .collect();+ let accel = self.active_accel();+ let mut k = 0;+ while k < stack.len() {+ let (i, g, spec) = stack[k];+ // A run of GPU effects goes to the accelerator in one go.+ if let Some(a) = accel+ && spec.gpu+ && a.supports_effect(spec.id)+ {+ let run: Vec<_> = stack[k..].iter().take_while(|(_, _, s)| s.gpu && a.supports_effect(s.id)).collect();+ let params: Vec<Params> = run.iter().map(|(_, g, _)| self.effect_params(ctx, layer, g)).collect();+ let hosts: Vec<_> = run.iter().map(|(i, _, _)| FxHost { index: *i, ..host }).collect();+ let steps: Vec<FxStep> = run+ .iter()+ .zip(¶ms)+ .zip(&hosts)+ .map(|(((i, g, s), params), host)| FxStep {+ spec: s,+ ctx: EffectCtx {+ params,+ time: lt.seconds(),+ layer_size,+ seed: g.uid as u32,+ adjustment,+ env: EffectEnv { host: Some(host), effect_index: *i, ..env },+ },+ })+ .collect();+ let t0 = web_time::Instant::now();+ if target.gpu(&steps) {+ if let Some(v) = timing.as_deref_mut() {+ let ms = t0.elapsed().as_secs_f64() * 1e3 / run.len() as f64;+ v.extend(run.iter().map(|(_, _, s)| (format!("{} (gpu)", s.id), ms)));+ }+ k += run.len();+ continue;+ }+ }+ k += 1;+ let params = self.effect_params(ctx, layer, g);+ let host = FxHost { index: i, ..host };+ let env = EffectEnv { host: Some(&host), effect_index: i, ..env };+ let ectx = EffectCtx { params: ¶ms, time: lt.seconds(), layer_size, seed: g.uid as u32, adjustment, env };+ let t0 = web_time::Instant::now();+ target.cpu(&mut |buf| {+ let mut buf = effectcraft_effects::apply(spec, &ectx, buf);+ // 8/16 bpc effects write integer pixels.+ self.pipe.quantize(&mut buf.img);+ buf+ });+ if let Some(v) = timing.as_deref_mut() {+ v.push((spec.id.to_string(), t0.elapsed().as_secs_f64() * 1e3));+ }+ }+ }++ /// Source pixels of a layer in layer space (before masks/effects).+ pub(crate) fn source(&self, ctx: &EvalCtx, layer: &Layer) -> Option<Buf> {+ let s = self.opts.scale;+ match &layer.source {+ LayerSource::Solid { item } => {+ let ItemKind::Solid(sol) = &self.project.item(*item)?.kind else { return None };+ let w = ((sol.width as f64 * s).ceil() as u32).max(1);+ let h = ((sol.height as f64 * s).ceil() as u32).max(1);+ if layer.switches.adjustment {+ return Some(Buf { img: Image::filled(w, h, [1.0; 4]), offset: [0.0; 2], scale: s });+ }+ let mut c = sol.color;+ if let Some(conv) = self.pipe.authored_in() {+ c = conv.apply(c);+ }+ let px = self.pipe.quantize_px([c[0], c[1], c[2], 1.0]);+ Some(Buf { img: Image::filled(w, h, px), offset: [0.0; 2], scale: s })+ }+ LayerSource::Comp { item } => {+ if self.project.comp_contains(*item, ctx.comp_id) {+ return None;+ }- // A composition proxy (a rendered still or movie) stands in for the comp.- // Nothing before the nested comp starts or after it ends.++ // A composition proxy (a rendered still or movie) stands in for the comp. It is++ // decoded like footage: its Separate Fields, Invert Alpha and Interpret As Linear++ // Light settings and the layer's Frame Blending apply. Nothing before the nested++ // comp starts or after it ends.+ let lt = ctx.nested_time(layer);+ if !self.project.comp(*item).is_some_and(|nc| nc.covers(lt)) {+ return None;+ }+ if let Some(pf) = self.proxy_for(*item)+ && let Some(nc) = self.project.comp(*item)+ {- let img = self.footage.frame_with(*item, pf, lt, None, self.pipe.float_encoding())?;++ let img = self.footage_frame(ctx, layer, *item, pf, lt, None)?;+ return Some(self.footage_buf(&img, pf, nc.width, nc.height));+ }+ // Essential Properties overrides render the nested comp with this instance's+ // values.+ let ov = essential_overrides(ctx, layer);+ let tmp = if ov.is_empty() { None } else { effectcraft_project::essential::with_overrides(self.project, *item, &ov) };+ // Preserve resolution when nested: drawn at full size even when this comp renders+ // smaller (the buffer's scale places it).+ let full = s < 1.0 && self.project.comp(*item).is_some_and(|nc| nc.preserve_resolution);+ let bs = if full { 1.0 } else { s };+ let base = self.nested_through(layer);+ let base = Renderer { opts: RenderOpts { scale: bs, ..base.opts }, ..base };+ let sub = match &tmp {+ Some(p) => Renderer { project: p, ..base },+ None => base,+ };+ // Frame blending between the nested comp's frames (time-stretched/remapped).+ let mode = frame_blend_mode(ctx, layer);+ if mode != FrameBlend::Off+ && let Some(nc) = self.project.comp(*item)+ {+ let (i, w) = frame_position(lt, nc.frame_rate);+ if w > 1e-6 {+ let a = sub.comp_frame(*item, nc.frame_rate.tick_of(i));+ let b = sub.comp_frame(*item, nc.frame_rate.tick_of(i + 1));+ return Some(Buf { img: blend_frames(mode, &a, &b, w as f32), offset: [0.0; 2], scale: bs });+ }+ }+ Some(Buf { img: sub.comp_frame(*item, lt), offset: [0.0; 2], scale: bs })+ }+ LayerSource::Footage { item } => {+ let it = self.project.item(*item)?;+ let ItemKind::Footage(f) = &it.kind else { return None };+ if !f.has_video {+ return None;+ }+ // Continuously rasterised vector footage: drawn at the on-screen scale.+ if layer.switches.collapse && is_vector_footage(f) {+ let k = self.raster_scale(ctx, layer);+ if let Some(img) = self.footage.vector_frame(*item, f, k) {+ let mut buf = Buf { img: (*img).clone(), offset: [0.0; 2], scale: k };+ if let Some(c) = self.pipe.media_in(f) {+ color::convert(&mut buf.img, &c);+ }+ return Some(buf);+ }+ }+ let lt = ctx.source_time(layer);+ // The proxy is decoded instead, at its own size, and fills the footage's frame.+ let proxy = self.proxy_for(*item);+ let pf = proxy.unwrap_or(f);+ let size = self.reduced_size(f.width, f.height).filter(|_| proxy.is_none());+ let img = self.footage_frame(ctx, layer, *item, pf, lt, size)?;+ Some(self.footage_buf(&img, pf, f.width, f.height))+ }+ LayerSource::Text => Some(self.authored(text::render(ctx, layer, self.raster_scale(ctx, layer)))),+ LayerSource::Shape => layer.props.sub("contents").map(|c| self.authored(shapes::render(ctx, layer, c, self.raster_scale(ctx, layer)))),+ _ => None,+ }+ }++ /// The proxy footage used for `item` under this render's Proxy Use, if any.+ pub fn proxy_for(&self, item: ItemId) -> Option<&'a Footage> {+ let it = self.project.item(item)?;+ let px = it.proxy.as_deref()?;+ (self.opts.proxy.uses(matches!(it.kind, ItemKind::Comp(_)), px.enabled) && px.footage.has_video).then_some(&px.footage)+ }++ /// A decoded frame of `f` as a layer buffer covering `w`×`h` layer pixels (the footage's+ /// nominal size; proxies are scaled up to it), converted from its colour profile.+ fn footage_buf(&self, img: &Image, f: &Footage, w: u32, h: u32) -> Buf {+ let s = self.opts.scale;+ let k = if img.width > 0 { w.max(1) as f64 / img.width as f64 } else { 1.0 };+ // Keep native pixels when downsampling is small; resample otherwise.+ let mut buf = match self.reduced_size(w, h) {+ // The source resampled it already (`FootageSource::frame_at_size`).+ Some(size) if (img.width, img.height) == size => Buf { img: img.clone(), offset: [0.0; 2], scale: s },+ Some((rw, rh)) if k <= 1.0 + 1e-9 => Buf { img: effectcraft_raster::resample(img, rw, rh), offset: [0.0; 2], scale: s },+ _ => Buf { img: img.clone(), offset: [0.0; 2], scale: 1.0 / k },+ };+ if let Some(c) = self.pipe.media_in(f) {+ color::convert(&mut buf.img, &c);+ }+ buf+ }++ /// The size of `w` × `h` layer pixels in this render when it is reduced enough that footage+ /// is resampled to it (below 3/4 scale).+ fn reduced_size(&self, w: u32, h: u32) -> Option<(u32, u32)> {+ let s = self.opts.scale;+ (s < 0.75).then(|| (((w as f64 * s).round() as u32).max(1), ((h as f64 * s).round() as u32).max(1)))+ }++ /// Authored colours into the working space (linear working spaces).+ fn authored(&self, mut buf: Buf) -> Buf {+ if let Some(c) = self.pipe.authored_in() {+ color::convert(&mut buf.img, &c);+ }+ buf+ }++ /// A footage frame at source time `t`, frame-blended between the two nearest source frames+ /// when the layer's Frame Blending switch (and the comp's Enable Frame Blending) is on and+ /// `t` falls between frames (footage rate ≠ comp rate, time stretch, time remapping).+ /// `size`: a plain frame may come resampled to it ([`FootageSource::frame_at_size`]).+ fn footage_frame(&self, ctx: &EvalCtx, layer: &Layer, item: ItemId, f: &Footage, t: Tick, size: Option<(u32, u32)>) -> Option<Arc<Image>> {+ // Interpret Footage ▸ Separate Fields: each field is a frame at twice the rate.+ if f.fields != effectcraft_project::FieldOrder::Off && matches!(f.kind, FootageKind::Video | FootageKind::Sequence) {+ let field_rate = FrameRate::new(f.frame_rate.num * 2, f.frame_rate.den);+ let i = field_rate.frame_at(t).max(0);+ let img = self.footage.frame_with(item, f, f.frame_rate.tick_of(i / 2), None, self.pipe.float_curve(f))?;+ let dominant_upper = f.fields == effectcraft_project::FieldOrder::UpperFirst;+ // Upper field = even lines (0, 2, …).+ let parity = if (i % 2 == 0) == dominant_upper { 0 } else { 1 };+ return Some(Arc::new(interpret_pixels(&field_frame(&img, parity), f, self.pipe.linear_footage_space(f))));+ }+ // Interpretation is per pixel but not linear: it runs on the frame before resampling.+ let size = size.filter(|_| !(f.invert_alpha || f.linear_light_applies()));+ let img = self.footage_frame_raw(ctx, layer, item, f, t, size)?;+ if f.invert_alpha || f.linear_light_applies() { Some(Arc::new(interpret_pixels(&img, f, self.pipe.linear_footage_space(f)))) } else { Some(img) }+ }++ fn footage_frame_raw(&self, ctx: &EvalCtx, layer: &Layer, item: ItemId, f: &Footage, t: Tick, size: Option<(u32, u32)>) -> Option<Arc<Image>> {+ let mode = frame_blend_mode(ctx, layer);+ let float = self.pipe.float_curve(f);+ if mode != FrameBlend::Off && matches!(f.kind, FootageKind::Video | FootageKind::Sequence) {+ let (i, w) = frame_position(t, f.frame_rate);+ if w > 1e-6 {+ // Blended frames are cached (Pixel Motion is expensive).+ let key = self.cache.map(|_| {+ use std::hash::{Hash, Hasher};+ let mut h = std::collections::hash_map::DefaultHasher::new();+ (0x00f8_a3e5_u64, item, i, (w as f32).to_bits(), mode as u8, f.frame_rate.num, f.frame_rate.den, &f.path, float).hash(&mut h);+ h.finish()+ });+ if let (Some(c), Some(k)) = (self.cache, key)+ && let Some(b) = c.get(k)+ {+ return Some(Arc::new(b.img.clone()));+ }+ let a = self.footage.frame_with(item, f, f.frame_rate.tick_of(i), None, float);+ let b = self.footage.frame_with(item, f, f.frame_rate.tick_of(i + 1), None, float);+ if let (Some(a), Some(b)) = (a, b) {+ let img = blend_frames(mode, &a, &b, w as f32);+ if let (Some(c), Some(k)) = (self.cache_to_keep(), key) {+ c.insert(k, Arc::new(Buf { img: img.clone(), offset: [0.0; 2], scale: 1.0 }));+ }+ return Some(Arc::new(img));+ }+ }+ }+ self.footage.frame_with(item, f, t, size, float)+ }++ /// Source → masks, clamped/quantised to the project depth.+ fn masked_source(&self, ctx: &EvalCtx, layer: &Layer) -> Option<Buf> {+ let mut buf = match self.content_times(ctx, layer) {+ Some(times) => self.blurred_source(ctx, layer, ×)?,+ None => self.source(ctx, layer)?,+ };+ // A solid is filled with a quantised colour: only masks can take it off the grid.+ let solid = matches!(layer.source, LayerSource::Solid { .. });+ if masks::apply(ctx, layer, &mut buf, self.mask_blur(ctx, layer)) || !solid {+ self.pipe.quantize(&mut buf.img);+ }+ Some(buf)+ }++ /// Fully processed layer buffer (source → masks → effects → layer styles, flattened).+ /// Served from the layer cache when the layer's content key matches.+ pub fn layer_buf(&self, ctx: &EvalCtx, layer: &Layer) -> Option<Arc<Buf>> {+ self.layer_buf_keyed(ctx, layer).map(|(b, _)| b)+ }++ /// [`Self::layer_buf`] in the blending space (linear with Blend Colors Using 1.0 Gamma).+ pub fn blend_layer_buf(&self, ctx: &EvalCtx, layer: &Layer) -> Option<Arc<Buf>> {+ let (b, k) = self.layer_buf_keyed(ctx, layer)?;+ Some(self.to_blend(b, k))+ }++ /// A buffer converted to the blending space (cached under a key derived from `key`).+ pub(crate) fn to_blend(&self, b: Arc<Buf>, key: Option<u64>) -> Arc<Buf> {+ let Some(c) = self.pipe.to_blend() else { return b };+ let key = key.map(|k| cache::derive(k, 0x1ea7));+ if let (Some(cache), Some(k)) = (self.cache, key)+ && let Some(x) = cache.get(k)+ {+ return x;+ }+ let mut nb = (*b).clone();+ color::convert(&mut nb.img, &c);+ let nb = Arc::new(nb);+ // The buffer the cache keeps (another worker's, if it kept one first).+ match (self.cache_to_keep(), key) {+ (Some(cache), Some(k)) => cache.insert(k, nb),+ _ => nb,+ }+ }++ fn layer_buf_keyed(&self, ctx: &EvalCtx, layer: &Layer) -> Option<(Arc<Buf>, Option<u64>)> {+ let st = self.styled(ctx, layer, None)?;+ if st.passes.is_empty() {+ return Some((st.body, st.key));+ }+ let key = st.key.map(|k| cache::derive(k, 0xf1a7));+ if let (Some(c), Some(k)) = (self.cache, key)+ && let Some(b) = c.get(k)+ {+ return Some((b, key));+ }+ let flat = Arc::new(styles::Styled { passes: st.passes.iter().map(|(b, m)| ((**b).clone(), *m)).collect(), body: (*st.body).clone() }.flatten());+ // The buffer the cache keeps (another worker's, if it kept one first).+ let flat = match (self.cache_to_keep(), key) {+ (Some(c), Some(k)) => c.insert(k, flat),+ _ => flat,+ };+ Some((flat, key))+ }++ /// A layer's source pixels at the context time, before masks, effects and the transform+ /// (what the motion tracker analyses, like After Effects' Layer panel). `None` for layers+ /// without pixels.+ pub fn layer_source(&self, ctx: &EvalCtx, layer: &Layer) -> Option<Buf> {+ self.source(ctx, layer)+ }++ /// Layer pixels after source → masks → effects (no layer styles).+ pub fn content_buf(&self, ctx: &EvalCtx, layer: &Layer) -> Option<Arc<Buf>> {+ self.content_buf_timed(ctx, layer, None).map(|(b, _)| b)+ }++ pub(crate) fn content_buf_timed(&self, ctx: &EvalCtx, layer: &Layer, mut timing: Option<&mut LayerTiming>) -> Option<(Arc<Buf>, Option<u64>)> {+ let key = self.cache.and_then(|_| cache::layer_key(ctx, layer, self.raster_scale(ctx, layer), self.opts.draft, self.mb_on(ctx, layer)));+ let key = self.content_key(ctx, layer, key);+ if let (Some(c), Some(k)) = (self.cache, key)+ && let Some(b) = c.get(k)+ {+ if let Some(t) = timing.as_deref_mut() {+ t.cached = true;+ }+ return Some((b, key));+ }+ let buf = self.masked_source(ctx, layer)?;+ let buf = Arc::new(self.apply_effects_timed(ctx, layer, buf, false, usize::MAX, timing.map(|t| &mut t.effects)));+ // The buffer the cache keeps (another worker's, if it kept one first).+ let buf = match (self.cache_to_keep(), key) {+ (Some(c), Some(k)) => c.insert(k, buf),+ _ => buf,+ };+ Some((buf, key))+ }++ /// A layer's input at the context time: source → masks → its first `effects` effects+ /// (what Time effects read at neighbouring times), in effect space (see [`effect_bounds`]):+ /// what effect `effects` sees. Served from / stored in the layer cache under its own key,+ /// so scrubbing reuses frames rendered for earlier output frames.+ pub fn layer_input(&self, ctx: &EvalCtx, layer: &Layer, effects: usize) -> Option<Arc<Buf>> {+ let key = self.cache.and_then(|_| cache::input_key(ctx, layer, self.raster_scale(ctx, layer), self.opts.draft, self.mb_on(ctx, layer), effects));+ let key = self.content_key(ctx, layer, key);+ if let (Some(c), Some(k)) = (self.cache, key)+ && let Some(b) = c.get(k)+ {+ return Some(b);+ }+ let mut buf = self.masked_source(ctx, layer)?;+ let origin = ctx.effect_bounds(layer).1;+ buf.rebase(origin);+ if effects > 0 {+ buf = self.effect_space_stack(ctx, layer, buf, false, effects, None, origin);+ }+ let buf = Arc::new(buf);+ // The buffer the cache keeps (another worker's, if it kept one first).+ let buf = match (self.cache_to_keep(), key) {+ (Some(c), Some(k)) => c.insert(k, buf),+ _ => buf,+ };+ Some(buf)+ }+ }diff --cc crates/render/src/three_d/adv/shade.rsindex 0168a769e,9acc852fe..ddf752e7f--- a/crates/render/src/three_d/adv/shade.rs+++ b/crates/render/src/three_d/adv/shade.rs@@@ -249,11 -230,10 +249,11 @@@ const PLANE_SLOPE_MAX: f32 = 64.0/// Fraction of light reaching `p` through shadow map `m` (1 = lit). `ng` is the/// receiver's geometric (not normal-mapped) normal facing the viewer.///- /// PCF over an N×N tap grid (5 ≤ N ≤ [`PCF_MAX_TAPS`]) spread over a reach derived+ /// PCF over an N×N tap grid (5 ≤ N ≤ `PCF_MAX_TAPS`) spread over a reach derived/// from `radius` (the wanted penumbra in output pixels) divided by the receiver's-/// texel footprint, each tap jittered by an integer hash of the receiver's-/// sub-texel cell and the tap index, and each tap comparing against the four+/// texel footprint, each tap jittered by [`tap_jitter`] (an integer hash of the+/// receiver's sub-texel lattice and the tap index, blended across the receiver's+/// lattice cell), and each tap comparing against the four/// nearest texel centres with bilinear weights. The jitter detaches the tap grid/// from the texel axes (axis-aligned binary taps are what stair-step a straight/// shadow edge), and keying it below texel size keeps the dither finer than andiff --cc crates/ui-egui/src/app/frame.rsindex 000000000,c0f9c7bd1..3d9ed8d20mode 000000,100644..100644--- a/crates/ui-egui/src/app/frame.rs+++ b/crates/ui-egui/src/app/frame.rs@@@ -1,0 -1,551 +1,556 @@@+ 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);++ // 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;+ }+ // 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.- panels::unsaved::on_close_requested(self, ctx);++ // On macOS a close that nothing held open quits through `-[NSApplication terminate:]`++ // (#341).++ panels::unsaved::close_or_quit(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();+ }+ 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/workspace_state/legacy.rsindex 93d71fd75,93d71fd75..bcb5a9691--- a/crates/ui-egui/src/workspace_state/legacy.rs+++ b/crates/ui-egui/src/workspace_state/legacy.rs@@@ -25,6 -25,6 +25,9 @@@ use super::{Snapshot, VERSION}use crate::dock::{Layout, PanelKind, Workspace};use crate::state::UiState;++#[cfg(test)]++mod tests;++#[derive(Deserialize)]enum OldSplitSize {Ratio(f32),@@@ -166,7 -166,7 +169,7 @@@ fn node(old: OldNode, depth: usize) ->first: Box::new(node(*a, depth.saturating_add(1))?),second: Box::new(node(*b, depth.saturating_add(1))?),},-- OldNode::Stack { entries } => column(entries)?,++ OldNode::Stack { entries } => column(entries, depth)?,})}@@@ -183,7 -183,7 +186,7 @@@ struct Frame}/// A column of stacked frames as tab groups split top to bottom (see the module docs).--fn column(entries: Vec<OldStackEntry>) -> Result<Node<PanelKind>, String> {++fn column(entries: Vec<OldStackEntry>, depth: usize) -> Result<Node<PanelKind>, String> {let mut frames: Vec<Frame> = Vec::new();// Tabs of closed frames above the first open one.let mut waiting: Vec<PanelKind> = Vec::new();@@@ -199,6 -199,6 +202,9 @@@}let active = entry.active.min(panels.len().saturating_sub(1));if entry.open {++ if depth.saturating_add(frames.len()) > craft_ui::docking::MAX_DEPTH {++ return Err("workspace dock tree exceeds supported limits".into());++ }let height = entry.height.filter(|h| h.is_finite() && *h > 0.0).map(|h| h.min(MAX_FRAME));frames.push(Frame { panels, active, height });} else if let Some(above) = frames.last_mut() {diff --cc crates/ui-egui/src/workspace_state/legacy/tests.rsindex 000000000,000000000..a3d182f4fnew file mode 100644--- /dev/null+++ b/crates/ui-egui/src/workspace_state/legacy/tests.rs@@@ -1,0 -1,0 +1,35 @@@++use super::*;++++fn stack(count: usize) -> OldNode {++ OldNode::Stack {++ entries: (0..count).map(|_| OldStackEntry { panel: Some(PanelKind::Info), panels: Vec::new(), active: 0, open: true, height: None }).collect(),++ }++}++++#[test]++fn stacked_frames_respect_the_remaining_tree_depth() {++ let limit = craft_ui::docking::MAX_DEPTH;++ assert!(node(stack(limit + 1), 0).is_ok());++ assert!(node(stack(limit + 2), 0).is_err());++ assert!(node(stack(1), limit).is_ok());++ assert!(node(stack(2), limit).is_err());++ assert!(node(stack(limit), 2).is_err());++}++++#[test]++fn oversized_legacy_stack_load_does_not_abort() {++ const CHILD: &str = "EFFECTCRAFT_TEST_LEGACY_STACK_CHILD";++ if std::env::var_os(CHILD).is_some() {++ let entry = serde_json::json!({"panel": "Info", "open": true});++ let value = serde_json::json!({"workspaces": {"Oversized": {"Stack": {"entries": vec![entry; 20_000]}}}});++ assert!(serde_json::to_vec(&value).unwrap().len() < super::super::MAX_BYTES);++ assert!(migrate(value, &UiState::default()).is_err());++ return;++ }++ let output = std::process::Command::new(std::env::current_exe().unwrap())++ .args(["--exact", "workspace_state::legacy::tests::oversized_legacy_stack_load_does_not_abort", "--nocapture"])++ .env(CHILD, "1")++ .output()++ .unwrap();++ assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr));++}