665bfac0b339
prefs_live.rs
//! Settings the desktop frontend applies every frame: dropped files (Import ▸ Default Drag
//! Import As), the memory watch (Memory & CPU ▸ RAM Reserved / Reduce Cache Size When System Is
//! Low on Memory), Startup ▸ Show Home Screen When Opening a Project, and Video ▸ Video Preview
//! output (a second window showing the composition frame, Mercury Transmit-style).
use egui::{Color32, Rect};
use serde_json::Value;
#[cfg(not(target_arch = "wasm32"))]
use serde_json::json;
use crate::EffectcraftApp;
use crate::frames::FrameKey;
/// Settings read once per tick, before any paint (they must keep working while hidden).
pub fn tick(app: &mut EffectcraftApp, ctx: &egui::Context, now: f64) {
memory_watch(app, ctx, now);
home_on_open(app, ctx);
}
/// Settings that show or draw something: run in the UI pass, before the panels draw.
pub fn frame(app: &mut EffectcraftApp, ctx: &egui::Context) {
video_preview(app, ctx);
}
/// Import native file drops through the same command as the file picker. Run after the dock
/// layout to use the current viewer rectangle for drops that also add layers.
#[cfg(not(target_arch = "wasm32"))]
pub fn dropped_files(app: &mut EffectcraftApp, ui: &egui::Ui, bounds: Rect) {
use egui::{Align2, Stroke, StrokeKind, vec2};
let ctx = ui.ctx().clone();
let hovered = ctx.input(|i| i.raw.hovered_files.len());
if hovered != 0 {
let label =
if hovered == 1 { crate::i18n::tr("Drop file to import").to_string() } else { crate::i18n::tr_args("Drop {} files to import", &[&hovered]) };
let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("native-file-drop")));
painter.rect_stroke(bounds.shrink(8.0), 6.0, Stroke::new(2.0, app.tokens.accent), StrokeKind::Inside);
let hint = Rect::from_center_size(bounds.center(), vec2(300.0, 46.0));
painter.rect_filled(hint, 6.0, app.tokens.panel_bg);
painter.text(hint.center(), Align2::CENTER_CENTER, &label, crate::theme::Tokens::medium(14.0), app.tokens.text);
app.auto.add("file.dropTarget", hint, &label);
}
let (paths, skipped) = ctx.input(|i| {
let mut paths = Vec::new();
let mut skipped = 0;
for file in &i.raw.dropped_files {
if file.path().is_absolute() {
paths.push(file.path().to_string_lossy().into_owned());
} else {
skipped += 1;
}
}
(paths, skipped)
});
if paths.is_empty() && skipped == 0 {
return;
}
let mut errors = Vec::new();
let mut import_reported_errors = false;
if skipped != 0 {
errors.push(crate::i18n::tr_args("Skipped {} dropped file(s) without a local path. Use File ▸ Import ▸ File…", &[&skipped]));
}
// Taken once per drop frame, so a handed-over flag cannot survive into a later, unrelated
// drop (#2661).
let handed_by_a_floating_window = std::mem::take(&mut app.forwarded.dropped_on_timeline);
let (proj, rest): (Vec<String>, Vec<String>) = paths.into_iter().partition(|p| {
let l = p.to_ascii_lowercase();
l.ends_with(".ecproj") || l.ends_with(".ecprojx")
});
if proj.len() > 1 {
errors.push(crate::i18n::tr_args("Only one project can be opened per drop; skipped {} more", &[&proj.len().saturating_sub(1)]));
}
// While the After Effects losses prompt waits, opening a project would replace it (and the
// project the answer imports into): the project waits for the answer, dropped again after it.
let proj = if crate::panels::aep_losses::asking(app) && !proj.is_empty() {
errors.push(crate::i18n::tr_args("Skipped {} more file(s) while a dialog is open; import them again after it", &[&1]));
Vec::new()
} else {
proj
};
// After Effects projects import as projects (File ▸ Import ▸ Adobe After Effects Project…),
// each into a folder named after its file, opening its first composition.
let (aep, mut rest): (Vec<String>, Vec<String>) = rest.into_iter().partition(|p| effectcraft_engine::commands::is_aep_path(p));
// A project in the drop changes the active composition: the other files go to the Project
// panel only, not into a composition.
let has_project = !proj.is_empty() || !aep.is_empty();
// Opened first, so the other files land in the project it opens. While it waits on Save
// changes? the rest of the drop is skipped with a note: it would land in the project about
// to be replaced.
let mut waiting = false;
if let Some(p) = proj.first() {
match crate::menus::invoke(app, &ctx, "file.open", json!({"path": p})) {
Ok(r) => waiting = crate::menus::waits_on_dialog(&r),
Err(e) => errors.push(crate::i18n::tr_args("Cannot open dropped project {}: {}", &[&p, &e])),
}
}
let mut aep = aep;
if waiting {
let skipped = rest.len() + aep.len();
if skipped > 0 {
errors.push(crate::i18n::tr_args("Skipped {} more file(s) while a dialog is open; import them again after it", &[&skipped]));
}
rest.clear();
aep.clear();
}
// One with losses asks first; the projects after it wait for the answer, the other files
// import meanwhile. The errors name their files.
errors.extend(crate::menus::import_aep_projects(app, aep));
if !rest.is_empty() {
let viewer = app
.auto
.elements
.iter()
.find(|e| e.id == "viewer.area")
.map(|e| Rect::from_min_size(egui::pos2(e.rect[0], e.rect[1]), egui::vec2(e.rect[2], e.rect[3])));
// Dropping a file on the Timeline adds it to the composition the panel shows, as it does
// on the viewer (#2588); the import decides the layer's position.
let over_timeline = handed_by_a_floating_window
|| ctx.input(|i| i.pointer.hover_pos()).is_some_and(|p| {
app.auto
.elements
.iter()
.find(|e| e.id == "panel.Timeline")
.is_some_and(|e| Rect::from_min_size(egui::pos2(e.rect[0], e.rect[1]), egui::vec2(e.rect[2], e.rect[3])).contains(p))
});
let at = if !has_project && !over_timeline {
ctx.input(|i| i.pointer.hover_pos()).filter(|p| viewer.is_some_and(|v| v.contains(*p))).and_then(|p| crate::panels::viewer::screen_to_comp(&ctx, p))
} else {
None
};
// Dropped files import as stills and folders' numbered stills as sequences; Alt-drag
// imports a folder's files one by one (After Effects).
let alt = ctx.input(|i| i.modifiers.alt);
// A dropped Photoshop file asks how to import it (the Import Photoshop File dialog, its
// Import Kind starting at Default Drag Import As), as File ▸ Import ▸ File… does (#678).
let layered = rest.iter().any(|p| p.rsplit('.').next().is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "psd" | "psb")));
let mut params = json!({
"paths": rest,
"drag": true,
"addToComp": !has_project && (at.is_some() || over_timeline),
"position": at,
"background": true
});
// While the losses prompt of a project dropped with it shows, a Photoshop file imports
// with Default Drag Import As: one dialog at a time.
if !layered || crate::panels::aep_losses::asking(app) {
params["importAs"] = json!(app.session.prefs.drag_import_as());
}
if alt {
params["sequence"] = json!(false);
}
match crate::menus::invoke(app, &ctx, "file.import", params) {
Ok(result) => {
import_reported_errors = result["errors"].as_array().is_some_and(|errors| errors.iter().any(Value::is_string));
}
Err(e) => errors.push(crate::i18n::tr_args("Cannot import dropped files: {}", &[&e])),
}
}
if !errors.is_empty() {
let local = errors.join("; ");
app.ui.status = if import_reported_errors { format!("{}; {local}", app.ui.status) } else { local };
}
}
/// Re-read the system's free memory every 30 s (cache budgets follow it; on Windows each
/// reading starts PowerShell in the background, so it isn't done more often).
pub(crate) fn memory_watch(app: &mut EffectcraftApp, ctx: &egui::Context, now: f64) {
let id = egui::Id::unique("prefs-memory-watch");
// While free disk space keeps frames and layers out of the disk cache, the idle passes ask
// for no repaint (nothing to write): keep a frame coming so its free space is read again and
// the RAM frames are written once there is room (the reading lands between frames).
if app.session.disk_cache.as_ref().is_some_and(|dc| !dc.accepts_writes()) {
ctx.request_repaint_after(std::time::Duration::from_secs(5));
}
let last = ctx.data(|d| d.get_temp::<f64>(id));
if last.is_some_and(|t| now - t < 30.0) {
return;
}
ctx.data_mut(|d| d.insert_temp(id, now));
// The first frame only records the time: tests and short runs don't query the system.
if last.is_some() {
app.session.memory_tick();
}
}
/// Startup ▸ Show Home Screen When Opening a Project.
pub(crate) fn home_on_open(app: &mut EffectcraftApp, ctx: &egui::Context) {
let id = egui::Id::unique("prefs-last-project");
let path = app.session.path.clone();
let last = ctx.data(|d| d.get_temp::<Option<String>>(id));
ctx.data_mut(|d| d.insert_temp(id, path.clone()));
let Some(last) = last else { return };
let opened = app.session.journal.last().is_some_and(|(c, _)| matches!(c.as_str(), "file.open" | "file.openRecent" | "file.revert"));
if path.is_some() && path != last && opened && app.session.prefs.startup.show_home_on_open_project {
app.ui.start_screen = true;
}
}
/// Video ▸ Mirror on Computer Monitor off: during playback the Composition panel leaves the
/// frame to the Video Preview window.
pub fn main_viewer_hidden(app: &EffectcraftApp) -> bool {
let v = &app.session.prefs.video;
v.enable_output && !v.mirror_on_monitor && app.playback.playing
}
/// Whether the Video Preview window shows now (Disable Video Output When in Background).
pub fn video_preview_active(app: &EffectcraftApp, focused: bool) -> bool {
let v = &app.session.prefs.video;
v.enable_output && (focused || !v.disable_when_background)
}
/// Video ▸ Enable Video Preview Output: a second native window with the current composition
/// frame, letterboxed on black. Video Device "Full Screen" opens it full screen (move it to the
/// external display first); Video Output During Playback off holds the last frame while playing.
fn video_preview(app: &mut EffectcraftApp, ctx: &egui::Context) {
let focused = ctx.input(|i| i.focused);
if !video_preview_active(app, focused) {
return;
}
let v = app.session.prefs.video.clone();
let tex_id = egui::Id::unique("video-preview-tex");
let update = !app.playback.playing || v.output_during_playback;
let key = app.viewer_shown.as_ref().map(|(_, k)| *k);
let cur: Option<(FrameKey, egui::TextureHandle)> = ctx.data(|d| d.get_temp(tex_id));
let tex = match (update, key, cur) {
(true, Some(k), Some((ck, t))) if ck == k => Some(t),
(true, Some(k), prev) => match app.viewer_pixels() {
Some(img) => {
let opts = crate::panels::viewer::zoom_texture_options(app.session.prefs.viewer_zoom_smooth());
let t = match prev {
Some((_, mut t)) => {
t.set(crate::frames::fit_texture((*img).clone(), crate::frames::max_texture_side(ctx)), opts);
t
}
None => crate::frames::load_fitted(ctx, "video-preview", (*img).clone(), opts),
};
ctx.data_mut(|d| d.insert_temp(tex_id, (k, t.clone())));
Some(t)
}
None => prev.map(|p| p.1),
},
(_, _, prev) => prev.map(|p| p.1),
};
let title =
format!("Video Preview — {}", app.session.active_comp_id().and_then(|c| app.session.project.item(c)).map(|i| i.name.clone()).unwrap_or_default());
let mut builder = egui::ViewportBuilder::default().with_title(title).with_inner_size([960.0, 540.0]);
if v.device == "fullscreen" {
builder = builder.with_fullscreen(true);
}
let mut closed = false;
ctx.show_viewport_immediate(egui::ViewportId::from_hash_of("effectcraft-video-preview"), builder, |vctx, _| {
egui::CentralPanel::default().frame(egui::Frame::NONE.fill(Color32::BLACK)).show(vctx, |ui| {
let area = ui.max_rect();
if let Some(t) = &tex {
let [w, h] = t.size().map(|x| x.max(1) as f32);
let s = (area.width() / w).min(area.height() / h);
let r = Rect::from_center_size(area.center(), egui::vec2(w * s, h * s));
ui.painter().image(t.id(), r, Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE);
}
});
if vctx.input(|i| i.viewport().close_requested()) {
closed = true;
}
});
if closed && let Err(e) = app.set_pref("video.enableOutput", Value::Bool(false)) {
app.ui.status = e;
}
}
No file is open. Choose one in the tree, or press Ctrl+O (⌘O on a Mac) to find one by name.
Syntax highlighting could not load. The unmodified read-only text remains available above.