Merge main into M13.2

This commit is contained in:
Brandon Thomas
2026-10-03 04:19:01 -04:00
86 changed files with 10306 additions and 325 deletions
+44 -9
View File
@@ -51,11 +51,13 @@ pub struct AudioOutput {
pub device: String,
pub left: u32,
pub right: u32,
/// Preview Sample Rate: devices that support it are opened at this rate.
pub rate: u32,
}
impl AudioOutput {
pub fn from_prefs(p: &effectcraft_engine::prefs::Prefs) -> AudioOutput {
AudioOutput { device: p.audio.output_device.clone(), left: p.audio.output_left, right: p.audio.output_right }
AudioOutput { device: p.audio.output_device.clone(), left: p.audio.output_left, right: p.audio.output_right, rate: p.audio.preview_sample_rate }
}
}
@@ -165,7 +167,7 @@ pub struct AudioPlayback {
stop: Arc<AtomicBool>,
thread: Option<JoinHandle<()>>,
/// wasm32 (no threads): what the feeder thread would own, run by [`AudioPlayback::pump`].
feeder: Option<(RenderSource, ItemId, i64)>,
feeder: Option<(RenderSource, ItemId, i64, u32)>,
pub rate: u32,
pub span: PlaySpan,
}
@@ -178,6 +180,9 @@ fn queue_target(rate: u32) -> usize {
impl AudioPlayback {
/// Start mixing `comp` over `span` into `device`.
/// `mix_rate`: Settings ▸ Audio ▸ Preview Sample Rate, the rate the comp's audio is mixed
/// at (resampled to the device's rate when they differ; 0 = the device's rate).
#[allow(clippy::too_many_arguments)]
pub fn start(
mut device: Box<dyn AudioDevice>,
src: RenderSource,
@@ -186,8 +191,10 @@ impl AudioPlayback {
wa: Tick,
wb: Tick,
looping: bool,
mix_rate: u32,
) -> Result<AudioPlayback, String> {
let rate = device.sample_rate().max(8000);
let mix = if mix_rate == 0 { rate } else { mix_rate.clamp(8000, 192_000) };
let span = PlaySpan::new(start, wa, wb, looping, rate);
let feed = Arc::new(AudioFeed::default());
let stop = Arc::new(AtomicBool::new(false));
@@ -195,10 +202,10 @@ impl AudioPlayback {
let mut cursor = span.start;
let prime = (rate as usize / 20).div_ceil(BLOCK);
for _ in 0..prime {
cursor = feed_block(&src, comp, &feed, &span, cursor, rate);
cursor = feed_block(&src, comp, &feed, &span, cursor, rate, mix);
}
if cfg!(target_arch = "wasm32") {
let mut p = AudioPlayback { feed: feed.clone(), device, stop, thread: None, feeder: Some((src, comp, cursor)), rate, span };
let mut p = AudioPlayback { feed: feed.clone(), device, stop, thread: None, feeder: Some((src, comp, cursor, mix)), rate, span };
p.device.start(feed)?;
p.pump();
return Ok(p);
@@ -211,7 +218,7 @@ impl AudioPlayback {
let target = queue_target(rate);
while !stop.load(Ordering::Relaxed) {
if feed.queued_frames() < target && !feed.finished.load(Ordering::Relaxed) {
cursor = feed_block(&src, comp, &feed, &span, cursor, rate);
cursor = feed_block(&src, comp, &feed, &span, cursor, rate, mix);
} else {
std::thread::sleep(std::time::Duration::from_millis(4));
}
@@ -226,10 +233,10 @@ impl AudioPlayback {
/// Every UI frame while playing: on wasm32 mix ahead into the feed (what the feeder thread
/// does elsewhere), then let the device take what it needs.
pub fn pump(&mut self) {
if let Some((src, comp, cursor)) = &mut self.feeder {
if let Some((src, comp, cursor, mix)) = &mut self.feeder {
let target = queue_target(self.rate);
while self.feed.queued_frames() < target && !self.feed.finished.load(Ordering::Relaxed) {
*cursor = feed_block(src, *comp, &self.feed, &self.span, *cursor, self.rate);
*cursor = feed_block(src, *comp, &self.feed, &self.span, *cursor, self.rate, *mix);
}
}
self.device.pump();
@@ -261,7 +268,7 @@ impl Drop for AudioPlayback {
/// Mix one block at `cursor` into the feed; returns the next cursor (wrapping or finishing at
/// the work-area end).
fn feed_block(src: &RenderSource, comp: ItemId, feed: &AudioFeed, span: &PlaySpan, cursor: i64, rate: u32) -> i64 {
fn feed_block(src: &RenderSource, comp: ItemId, feed: &AudioFeed, span: &PlaySpan, cursor: i64, rate: u32, mix: u32) -> i64 {
let mut cursor = cursor;
if cursor >= span.wb {
if !span.looping {
@@ -271,11 +278,39 @@ fn feed_block(src: &RenderSource, comp: ItemId, feed: &AudioFeed, span: &PlaySpa
cursor = span.wa;
}
let n = ((span.wb - cursor) as usize).min(BLOCK);
let buf = effectcraft_engine::render::audio::mix_comp(&src.project, src.footage.as_ref(), src.expr.as_deref(), comp, sample_time(cursor, rate), n, rate);
let t = sample_time(cursor, rate);
let buf = if mix == rate {
effectcraft_engine::render::audio::mix_comp(&src.project, src.footage.as_ref(), src.expr.as_deref(), comp, t, n, rate)
} else {
let m = (n as u64 * mix as u64).div_ceil(rate as u64) as usize + 1;
let b = effectcraft_engine::render::audio::mix_comp(&src.project, src.footage.as_ref(), src.expr.as_deref(), comp, t, m, mix);
resample_stereo(&b, mix, rate, n)
};
feed.push(&buf);
cursor + n as i64
}
/// Linear resampling of interleaved stereo from `from` Hz to `n` frames at `to` Hz.
pub fn resample_stereo(src: &[f32], from: u32, to: u32, n: usize) -> Vec<f32> {
let frames = src.len() / 2;
let mut out = Vec::with_capacity(n * 2);
if frames == 0 {
out.resize(n * 2, 0.0);
return out;
}
let step = from as f64 / to as f64;
for i in 0..n {
let x = i as f64 * step;
let a = (x.floor() as usize).min(frames - 1);
let b = (a + 1).min(frames - 1);
let f = (x - a as f64) as f32;
for c in 0..2 {
out.push(src[a * 2 + c] * (1.0 - f) + src[b * 2 + c] * f);
}
}
out
}
/// VU meter state for the Audio panel: smoothed level with a falling decay and peak hold, in
/// dBFS per channel.
#[derive(Clone, Copy, Debug)]
+30 -8
View File
@@ -36,10 +36,16 @@ pub enum PanelKind {
MaskInterpolation,
ScriptConsole,
EssentialGraphics,
LumetriScopes,
Footage,
MediaBrowser,
Metadata,
Progress,
ContentAwareFill,
}
impl PanelKind {
pub const ALL: [PanelKind; 26] = [
pub const ALL: [PanelKind; 32] = [
PanelKind::Project,
PanelKind::EffectControls,
PanelKind::Composition,
@@ -66,6 +72,12 @@ impl PanelKind {
PanelKind::MaskInterpolation,
PanelKind::ScriptConsole,
PanelKind::EssentialGraphics,
PanelKind::LumetriScopes,
PanelKind::Footage,
PanelKind::MediaBrowser,
PanelKind::Metadata,
PanelKind::Progress,
PanelKind::ContentAwareFill,
];
pub fn title(self) -> &'static str {
match self {
@@ -95,6 +107,12 @@ impl PanelKind {
PanelKind::MaskInterpolation => "Mask Interpolation",
PanelKind::ScriptConsole => "Script Console",
PanelKind::EssentialGraphics => "Essential Graphics",
PanelKind::LumetriScopes => "Lumetri Scopes",
PanelKind::Footage => "Footage",
PanelKind::MediaBrowser => "Media Browser",
PanelKind::Metadata => "Metadata",
PanelKind::Progress => "Progress",
PanelKind::ContentAwareFill => "Content-Aware Fill",
}
}
pub fn id(self) -> String {
@@ -102,7 +120,7 @@ impl PanelKind {
}
pub fn from_name(s: &str) -> Option<PanelKind> {
let n = s.to_ascii_lowercase().replace([' ', '_', '-', '&'], "");
Self::ALL.iter().copied().find(|p| format!("{p:?}").to_ascii_lowercase() == n || p.title().to_ascii_lowercase().replace([' ', '&'], "") == n)
Self::ALL.iter().copied().find(|p| format!("{p:?}").to_ascii_lowercase() == n || p.title().to_ascii_lowercase().replace([' ', '&', '-'], "") == n)
}
/// Window-menu shortcut.
pub fn window_shortcut(self) -> Option<&'static str> {
@@ -295,7 +313,7 @@ pub fn workspace(name: &str) -> DockNode {
hsplit(
FixedA(360.0),
tabs(&[EffectControls, Project], 0),
hsplit(FixedB(300.0), tabs(&[Composition, Layer], 0), right(&[Info, Preview], &[EffectsPresets])),
hsplit(FixedB(340.0), tabs(&[Composition, Layer], 0), right(&[LumetriScopes, Info, Preview], &[EffectsPresets])),
),
tabs(&[Timeline], 0),
),
@@ -315,17 +333,17 @@ pub fn workspace(name: &str) -> DockNode {
Ratio(0.55),
hsplit(
FixedA(300.0),
tabs(&[Project, EffectControls, Flowchart, History], 0),
tabs(&[Project, EffectControls, Flowchart, History, MediaBrowser, Metadata], 0),
hsplit(
FixedB(300.0),
tabs(&[Composition, Layer], 0),
tabs(&[Composition, Layer, Footage], 0),
right(
&[Info, Preview, Audio, Align, Character, Paragraph],
&[EffectsPresets, Properties, Tracker, Wiggler, Smoother, MotionSketch, Paint, Brushes, Markers],
&[Info, Preview, Audio, Align, Character, Paragraph, LumetriScopes],
&[EffectsPresets, Properties, Tracker, Wiggler, Smoother, MotionSketch, Paint, Brushes, Markers, ContentAwareFill],
),
),
),
tabs(&[Timeline, RenderQueue], 0),
tabs(&[Timeline, RenderQueue, Progress], 0),
),
"Standard" => vsplit(
Ratio(0.56),
@@ -779,6 +797,10 @@ pub fn draw_group_chrome(
}
} else {
let strip = Rect::from_min_size(g.rect.min, vec2(g.rect.width(), t.tab_h));
if t.gradients {
// Settings ▸ Appearance ▸ Use Gradients.
crate::theme::gradient_rect(&painter, strip.shrink2(vec2(t.radius, 0.0)), t.grad_top(t.panel_bg), t.panel_bg);
}
let mut x = strip.min.x + 12.0;
let text_y = strip.min.y + 16.0;
for (i, p) in g.panels.iter().enumerate() {
+25
View File
@@ -29,6 +29,30 @@ impl EffectcraftApp {
out
}
/// Settings ▸ Appearance ▸ Use Label Color for Related Tabs: the Composition and Timeline
/// tabs carry their comp's label colour, Effect Controls and Properties the layer's.
fn label_tab_marks(&self, ui: &egui::Ui) {
if !self.session.prefs.appearance.use_label_color_for_tabs {
return;
}
let Some(cid) = self.session.active_comp_id() else { return };
let comp_label = self.session.project.item(cid).map(|i| i.label);
let layer_label = self.session.active_comp().and_then(|c| self.session.state.selected_layers.first().and_then(|l| c.layer(*l))).map(|l| l.label);
for (p, label) in [
(PanelKind::Composition, comp_label),
(PanelKind::Timeline, comp_label),
(PanelKind::EffectControls, layer_label),
(PanelKind::Properties, layer_label),
] {
let (Some(label), Some(e)) = (label, self.auto.find(&format!("panel.tab.{}", p.id()))) else { continue };
if label == effectcraft_engine::color::Label::None {
continue;
}
let r = Rect::from_min_size(pos2(e.rect[0] + 2.0, e.rect[1] + 9.0), vec2(4.0, (e.rect[3] - 16.0).max(6.0)));
ui.painter().rect_filled(r, 1.0, self.tokens.label(label));
}
}
/// Edit the full layout (docked tree + floating groups) with a [`Layout`] operation.
pub fn edit_layout(&mut self, f: impl FnOnce(&mut Layout) -> bool) -> bool {
let mut l = Layout { root: self.ui.dock.clone(), floating: self.ui.floating.clone() };
@@ -98,6 +122,7 @@ impl EffectcraftApp {
for g in &groups {
actions.extend(dock::draw_group_chrome(ui, g, self.ui.focused, &t, &mut self.auto, &title));
}
self.label_tab_marks(ui);
if maximized.is_none() {
self.ui.dock = dock;
}
+12 -2
View File
@@ -16,6 +16,7 @@ pub mod icons;
pub mod menus;
pub mod native_menu;
pub mod panels;
pub mod prefs_live;
pub mod state;
pub mod theme;
pub mod widgets;
@@ -255,7 +256,7 @@ impl EffectcraftApp {
ctx.all_styles_mut(|s| s.interaction.tooltip_delay = if tips { 0.5 } else { f32::INFINITY });
self.ui.cache_when_idle = p.previews.cache_frames_when_idle;
self.ui.viewer.fast_preview = p.previews.fast_previews;
self.frames.set_budget(p.preview_cache_bytes());
self.frames.set_budget(p.cache_budgets(self.session.sys_memory).preview);
}
/// Change settings from the UI (applied next frame and saved).
@@ -475,6 +476,8 @@ impl EffectcraftApp {
view: self.session.view_camera(comp),
roi,
backend: effectcraft_engine::render::Backend::Auto,
nested_switches: self.session.prefs.general.switches_affect_nested_comps,
draft_shadows: self.session.prefs.three_d.realtime_shadows,
proxy: Default::default(),
}
}
@@ -528,7 +531,8 @@ impl EffectcraftApp {
}
let out = audio::AudioOutput::from_prefs(&self.session.prefs);
let Some(dev) = self.hooks.audio_device.as_ref().and_then(|f| f(&out)) else { return };
match audio::AudioPlayback::start(dev, self.render_source(), cid, t, c.work_area.0, c.work_area.1, self.ui.preview_loop) {
let mix = self.session.prefs.audio.preview_sample_rate;
match audio::AudioPlayback::start(dev, self.render_source(), cid, t, c.work_area.0, c.work_area.1, self.ui.preview_loop, mix) {
Ok(a) => self.audio = Some(a),
Err(e) => log::warn!("audio preview: {e}"),
}
@@ -787,6 +791,11 @@ impl EffectcraftApp {
self.session.poll_mask_track();
ctx.request_repaint_after(std::time::Duration::from_millis(50));
}
// Background tasks (Content-Aware Fill, Scene Edit Detection).
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();
@@ -806,6 +815,7 @@ impl EffectcraftApp {
self.apply_prefs(&ctx);
self.handle_events(&ctx);
self.tick_autosave(&ctx);
prefs_live::frame(self, &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!({})) {
+76 -20
View File
@@ -754,6 +754,37 @@ pub fn frontend(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, p: Valu
app.show_panel(PanelKind::Layer);
Value::Null
}
"app.confirmExecute" => {
// Settings ▸ Scripting ▸ Warn User When Executing Files.
let path = p.get("path").and_then(Value::as_str).unwrap_or_default().to_string();
crate::panels::forms::form(
app,
"A script wants to open a file",
"file.executeFile",
json!({"path": path, "confirmed": true}),
vec![crate::panels::forms::Field::text("path", "Open", &path)],
);
Value::Null
}
"app.showReport" => {
let title = p.get("title").and_then(Value::as_str).unwrap_or("Report").to_string();
let text = p.get("text").and_then(Value::as_str).unwrap_or_default().to_string();
crate::panels::dialogs::info(app, &title, &text);
Value::Null
}
"window.assignWorkspaceShortcut" => {
let mut q = p.clone();
q["workspace"] = json!(app.ui.workspace);
return run_engine(app, ctx, "window.assignWorkspaceShortcut", q);
}
"file.interpretFootage" => {
// Import ▸ Interpret Unlabeled Alpha As: Ask User.
if let Some(i) = p.get("item").and_then(Value::as_u64) {
app.session.state.project_selection = vec![effectcraft_engine::project::ItemId(i)];
}
crate::panels::dialogs::open_form(app, "file.interpretFootage", &json!({}));
Value::Null
}
"effect.manage" | "anim.browsePresets" => {
app.show_panel(PanelKind::EffectsPresets);
Value::Null
@@ -794,6 +825,8 @@ fn file_dialog(app: &mut EffectcraftApp, id: &str, params: &Value) -> Option<Res
"file.runScript" => ("path", Ask::Open(&["jsx", "js", "jsonl", "json", "txt"])),
"file.replaceFootage" => ("path", Ask::Import),
"file.collectFiles" => ("folder", Ask::Save("Collected Files")),
"file.saveCopyAsXml" => ("path", Ask::Save("Untitled Project.ecprojx")),
"keys.rpfCameraImport" => ("path", Ask::Open(&["json", "csv", "txt"])),
"essential.exportTemplate" => ("path", Ask::Save("Template.ectemplate")),
"essential.importTemplate" => ("path", Ask::Open(&["ectemplate"])),
"file.setProxy" => ("path", Ask::Open(&["mp4", "mov", "m4v", "mkv", "webm", "png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr"])),
@@ -873,6 +906,15 @@ pub(crate) fn entry_label(app: &EffectcraftApp, e: &MenuEntry) -> String {
match e.command.as_str() {
"edit.undo" => app.session.history.undo.last().map(|u| format!("Undo {}", u.0)).unwrap_or_else(|| "Can't Undo".into()),
"edit.redo" => app.session.history.redo.last().map(|u| format!("Redo {}", u.0)).unwrap_or_else(|| "Can't Redo".into()),
// Window ▸ Layer: the layer open in the Layer panel.
"window.panel" if e.params.get("panel").and_then(Value::as_str) == Some("layer") => {
let name = app
.ui
.layer_panel
.and_then(|id| app.session.active_comp().and_then(|c| c.layer(effectcraft_engine::project::LayerId(id))))
.map(|l| l.name.clone());
format!("Layer: {}", name.unwrap_or_else(|| "(none)".into()))
}
_ => effectcraft_engine::menus::entry_label(&app.session, e),
}
}
@@ -1137,29 +1179,38 @@ fn menu_nodes(app: &mut EffectcraftApp, ui: &mut egui::Ui, nodes: &[MenuNode], c
MenuNode::Separator => {
ui.separator();
}
MenuNode::Submenu { label, children } if label == "Open Recent" => {
// File ▸ Open Recent: the recent projects (Settings), then the static entries.
ui.menu_button((gutter(false), label.as_str()), |ui| {
ui.set_min_width(320.0);
let recent = app.session.prefs.recent_projects.clone();
if recent.is_empty() {
ui.add_enabled(false, egui::Button::new((gutter(false), "No Recent Projects")));
MenuNode::Dynamic { name } => {
// Recent projects / footage / presets, undo history, shortcut slots, viewers.
let ws = app.ui.workspace.clone();
let (entries, empty) = effectcraft_engine::menus::dynamic(&app.session, name, &dyn_ctx(&ws));
if entries.is_empty()
&& let Some(e) = empty
{
ui.add_enabled(false, egui::Button::new((gutter(false), e)));
}
for (i, e) in entries.iter().enumerate() {
let tip = match name.as_str() {
"recentProjects" => app.session.prefs.recent_projects.get(i).cloned(),
"recentFootage" => app.session.prefs.recent_footage.get(i).cloned(),
"recentPresets" => app.session.prefs.recent_presets.get(i).cloned(),
_ => None,
};
let r = ui.add_enabled(entry_enabled(app, e), egui::Button::new((gutter(false), e.label.as_str())));
let r = match &tip {
Some(t) => r.on_hover_text(t),
None => r,
};
app.auto.add(&format!("menu.{name}.{i}"), r.rect, &e.label);
if r.clicked() {
*clicked = Some((e.command.clone(), e.params.clone()));
ui.close();
}
for (i, path) in recent.iter().enumerate() {
let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or(path.clone());
let r = ui.add(egui::Button::new((gutter(false), name))).on_hover_text(path);
app.auto.add(&format!("menu.openRecent.{i}"), r.rect, path);
if r.clicked() {
*clicked = Some(("file.openRecent".into(), json!({"index": i})));
ui.close();
}
}
ui.separator();
menu_nodes(app, ui, children, clicked);
});
}
}
MenuNode::Submenu { label, children } => {
ui.menu_button((gutter(false), label.as_str()), |ui| {
let ws = app.ui.workspace.clone();
let shown = effectcraft_engine::menus::submenu_label(&app.session, label, &dyn_ctx(&ws));
ui.menu_button((gutter(false), shown.as_str()), |ui| {
ui.set_min_width(if children.len() > 30 { 200.0 } else { 240.0 });
// Long submenus (Blending Mode, effect categories) scroll instead of running
// off the screen.
@@ -1177,6 +1228,11 @@ fn menu_nodes(app: &mut EffectcraftApp, ui: &mut egui::Ui, nodes: &[MenuNode], c
}
}
/// Frontend state for dynamic menus (the current workspace).
pub(crate) fn dyn_ctx(workspace: &str) -> effectcraft_engine::menus::DynCtx<'_> {
effectcraft_engine::menus::DynCtx { workspace: Some(workspace) }
}
/// The check-mark column every menu row reserves (like macOS / After Effects menus).
fn gutter(checked: bool) -> egui::Atom<'static> {
use egui::AtomExt;
+44 -21
View File
@@ -134,28 +134,41 @@ pub fn build(app: &EffectcraftApp) -> NativeMenu {
let id = format!("{path}.{i}");
match n {
MenuNode::Separator => out.push(NativeNode::Separator),
MenuNode::Dynamic { name } => {
// Recent projects / footage / presets, undo history, shortcut slots, viewers.
let (entries, empty) = effectcraft_engine::menus::dynamic(&app.session, name, &crate::menus::dyn_ctx(&app.ui.workspace));
if entries.is_empty()
&& let Some(e) = empty
{
out.push(NativeNode::Item(NativeItem {
id: format!("{id}.none"),
label: e.to_string(),
command: String::new(),
params: Value::Null,
shortcut: None,
accelerator: None,
enabled: false,
checked: None,
}));
}
for (k, e) in entries.iter().enumerate() {
out.push(NativeNode::Item(NativeItem {
id: format!("{id}.d{k}"),
label: e.label.clone(),
command: e.command.clone(),
params: e.params.clone(),
shortcut: None,
accelerator: None,
enabled: crate::menus::entry_enabled(app, e),
checked: None,
}));
}
}
MenuNode::Submenu { label, children } => {
let mut kids = vec![];
if label == "Open Recent" {
for (k, p) in app.session.prefs.recent_projects.iter().enumerate() {
let name = std::path::Path::new(p).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or(p.clone());
kids.push(NativeNode::Item(NativeItem {
id: format!("{id}.r{k}"),
label: name,
command: "file.openRecent".into(),
params: json!({"index": k}),
shortcut: None,
accelerator: None,
enabled: true,
checked: None,
}));
}
if !kids.is_empty() {
kids.push(NativeNode::Separator);
}
}
rec(app, children, &id, &mut kids);
out.push(NativeNode::Submenu { label: label.clone(), children: kids });
let shown = effectcraft_engine::menus::submenu_label(&app.session, label, &crate::menus::dyn_ctx(&app.ui.workspace));
out.push(NativeNode::Submenu { label: shown, children: kids });
}
MenuNode::Item(e) => {
let role = match e.command.as_str() {
@@ -272,6 +285,11 @@ pub fn state_key(app: &EffectcraftApp) -> u64 {
s.journal.len().hash(&mut h);
s.journal.last().map(|j| &j.0).hash(&mut h);
s.prefs.recent_projects.hash(&mut h);
(&s.prefs.recent_footage, &s.prefs.recent_presets).hash(&mut h);
s.history.undo.iter().for_each(|(l, _)| l.hash(&mut h));
s.state.open_comps.hash(&mut h);
s.active_comp_id().and_then(|c| s.state.views3d.get(&c)).map(|v| format!("{:?}", v.current)).hash(&mut h);
s.shortcuts().keys.len().hash(&mut h);
s.keymaps.active.hash(&mut h);
let v = &app.ui.viewer;
(v.rulers, v.guides, v.snap_guides, v.lock_guides, v.grid, v.snap_grid, v.show_layer_controls, v.pasteboard).hash(&mut h);
@@ -340,7 +358,10 @@ mod tests {
fn commands(n: &[NativeNode], out: &mut Vec<(String, String)>) {
for x in n {
match x {
NativeNode::Item(i) if i.command != "file.openRecent" => out.push((i.command.clone(), i.params.to_string())),
// Dynamic entries (recent files, History, viewers…) are not tree entries.
NativeNode::Item(i) if !i.id.rsplit('.').next().is_some_and(|l| l.starts_with('d') || l == "none") => {
out.push((i.command.clone(), i.params.to_string()))
}
NativeNode::Predefined { command, .. } if !command.is_empty() => out.push((command.clone(), "null".into())),
NativeNode::Submenu { children, .. } => commands(children, out),
_ => {}
@@ -431,7 +452,9 @@ mod tests {
app.session.execute("layer.setSwitch", json!({"switch": "lock"})).unwrap();
assert_ne!(state_key(&app), k0);
let spec1 = build(&app);
assert_eq!(spec0.structure(), spec1.structure(), "state changes don't rebuild the menu");
// The new undo step joins Edit ▸ History (a dynamic submenu); nothing else is rebuilt.
let history = |s: &NativeMenu| s.items().into_iter().filter(|i| i.command == "edit.history").count();
assert_eq!(history(&spec1), history(&spec0) + 1);
let lock = spec1.items().into_iter().find(|i| i.command == "layer.setSwitch" && i.params["switch"] == "lock").unwrap().checked;
assert_eq!(lock, Some(true));
assert_ne!(undo(&spec0), undo(&spec1));
@@ -0,0 +1,138 @@
//! Content-Aware Fill panel (Window ▸ Content-Aware Fill): Fill Target, Alpha Expansion, Fill
//! Method (Object / Surface / Edge Blend), Lighting Correction, Range (Work Area / Entire
//! Duration), a reference frame from a layer of the comp, and Generate Fill Layer. The settings
//! live in `EditorState::content_fill` (`contentFill.set`); the button runs
//! `contentFill.generate` as a background job (Window ▸ Progress).
use egui::{Align2, Rect, pos2, vec2};
use serde_json::json;
use super::panel_kit as kit;
use crate::EffectcraftApp;
use crate::theme::Tokens;
const ROW: f32 = 28.0;
pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let t = app.tokens;
let p = ui.painter().with_clip_rect(rect);
p.rect_filled(rect, 0.0, t.panel_bg);
let x0 = rect.min.x + 12.0;
let xv = x0 + 130.0;
let w = (rect.max.x - xv - 12.0).clamp(90.0, 220.0);
let mut y = rect.min.y + 10.0;
let st = app.session.state.content_fill.clone();
let comp = app.session.active_comp().cloned();
let layer = comp.as_ref().and_then(|c| app.session.state.selected_layers.first().and_then(|l| c.layer(*l)).cloned());
// Fill Target.
p.text(pos2(x0, y + 9.0), Align2::LEFT_CENTER, "Fill Target", Tokens::semibold(12.0), t.text);
y += ROW - 6.0;
let target = match &layer {
Some(l) => {
let masks = l
.masks()
.map(|m| {
m.groups()
.filter(|g| {
matches!(
g.kind,
effectcraft_engine::project::GroupKind::Mask { mode: effectcraft_engine::project::MaskMode::Subtract, .. }
| effectcraft_engine::project::GroupKind::Mask { inverted: true, .. }
)
})
.count()
})
.unwrap_or(0);
format!("{} — {masks} subtracting mask(s)", l.name)
}
None => "Select a layer with a Subtract mask".into(),
};
p.text(pos2(x0, y + 9.0), Align2::LEFT_CENTER, &target, Tokens::ui(11.5), if layer.is_some() { t.text_dim } else { t.text_faint });
app.auto.add("contentFill.target", Rect::from_min_size(pos2(x0, y), vec2(rect.width() - 24.0, 18.0)), &target);
y += ROW;
let mut set = serde_json::Map::new();
// Alpha Expansion.
kit::label(ui, pos2(x0, y), "Alpha Expansion:", &t);
let a = kit::number(app, ui, pos2(xv, y), "contentFill.alphaExpansion", st.alpha_expansion, 0.2, (0.0, 100.0), 0, " px");
if (a - st.alpha_expansion).abs() > 1e-9 {
set.insert("alphaExpansion".into(), json!(a.round()));
}
y += ROW;
// Fill Method.
kit::label(ui, pos2(x0, y), "Fill Method:", &t);
let methods = ["object", "surface", "edgeBlend"];
let cur = methods.iter().position(|m| *m == st.method).unwrap_or(0);
if let Some(i) = kit::dropdown(app, ui, Rect::from_min_size(pos2(xv, y), vec2(w, 20.0)), "contentFill.method", &["Object", "Surface", "Edge Blend"], cur) {
set.insert("method".into(), json!(methods[i]));
}
y += ROW;
// Lighting Correction (Object / Surface).
kit::label(ui, pos2(x0, y), "Lighting Correction:", &t);
let lights = ["none", "subtle", "moderate", "strong"];
let cur = lights.iter().position(|m| *m == st.lighting_correction).unwrap_or(0);
if st.method != "edgeBlend"
&& let Some(i) =
kit::dropdown(app, ui, Rect::from_min_size(pos2(xv, y), vec2(w, 20.0)), "contentFill.lighting", &["None", "Subtle", "Moderate", "Strong"], cur)
{
set.insert("lightingCorrection".into(), json!(lights[i]));
}
y += ROW;
// Range.
kit::label(ui, pos2(x0, y), "Range:", &t);
let cur = usize::from(st.range == "entire");
if let Some(i) = kit::dropdown(app, ui, Rect::from_min_size(pos2(xv, y), vec2(w, 20.0)), "contentFill.range", &["Work Area", "Entire Duration"], cur) {
set.insert("range".into(), json!(if i == 1 { "entire" } else { "workArea" }));
}
y += ROW;
// Reference frame: a layer of the comp at a time.
kit::label(ui, pos2(x0, y), "Reference Frame:", &t);
if let Some(c) = &comp {
let mut names = vec!["None".to_string()];
names.extend(c.layers.iter().map(|l| l.name.clone()));
let cur = st.reference_layer.and_then(|r| c.layers.iter().position(|l| l.id == r)).map(|i| i + 1).unwrap_or(0);
let opts: Vec<&str> = names.iter().map(String::as_str).collect();
if let Some(i) = kit::dropdown(app, ui, Rect::from_min_size(pos2(xv, y), vec2(w, 20.0)), "contentFill.referenceLayer", &opts, cur) {
set.insert("referenceLayer".into(), if i == 0 { json!(null) } else { json!(c.layers[i - 1].id.0) });
}
y += ROW;
if st.reference_layer.is_some() {
let at = st.reference_time.unwrap_or(0.0);
p.text(pos2(xv, y + 9.0), Align2::LEFT_CENTER, format!("at {}", kit::seconds(at)), Tokens::ui(11.5), t.text_dim);
if kit::button(app, ui, Rect::from_min_size(pos2(xv + 80.0, y), vec2(120.0, 20.0)), "contentFill.referenceHere", "Use Current Time", false) {
set.insert("referenceTime".into(), json!(app.session.time().seconds()));
}
y += ROW;
}
} else {
y += ROW;
}
if !set.is_empty() {
kit::exec(app, "contentFill.set", serde_json::Value::Object(set));
}
// Generate, or the running job.
y += 6.0;
let running = app.session.jobs().into_iter().find(|j| j.kind == "contentFill");
match running {
Some(j) => {
let frac = j.fraction.unwrap_or(0.0) as f32;
let bar = Rect::from_min_size(pos2(x0, y + 7.0), vec2((rect.width() - 110.0).max(60.0), 6.0));
p.rect_filled(bar, 3.0, t.field_bg);
p.rect_filled(Rect::from_min_size(bar.min, vec2(bar.width() * frac, 6.0)), 3.0, t.accent);
p.text(pos2(x0, y + 24.0), Align2::LEFT_CENTER, format!("{} {:.0} %", j.message, frac * 100.0), Tokens::ui(11.0), t.text_dim);
if kit::button(app, ui, Rect::from_min_size(pos2(bar.max.x + 10.0, y), vec2(70.0, 20.0)), "contentFill.cancel", "Cancel", false) {
kit::exec(app, "jobs.cancel", json!({"job": j.id}));
}
ui.ctx().request_repaint_after(std::time::Duration::from_millis(150));
}
None => {
if kit::button(app, ui, Rect::from_min_size(pos2(x0, y), vec2(160.0, 24.0)), "contentFill.generate", "Generate Fill Layer", true) {
match &layer {
Some(l) => {
kit::exec(app, "contentFill.generate", json!({"layer": l.id.0}));
}
None => app.ui.status = "Select the layer to fill first".into(),
}
}
}
}
}
+394
View File
@@ -0,0 +1,394 @@
//! The expression editor of the Timeline, following Settings ▸ Scripting & Expressions:
//! Font Size, Syntax Highlighting, Line Numbers, Auto-complete (Tab accepts), Bracket Matching
//! and Word Wrap; and the Composition panel's expression error banner (Show Expression Error
//! Banner).
use effectcraft_engine::prefs::Scripting;
use egui::text::{LayoutJob, TextFormat};
use egui::{Color32, FontId, Rect, Stroke, pos2, vec2};
use crate::theme::Tokens;
/// Syntax colours.
const KEYWORD: Color32 = Color32::from_rgb(0xc6, 0x8a, 0xe6);
const NUMBER: Color32 = Color32::from_rgb(0xe0, 0xb4, 0x6c);
const STRING: Color32 = Color32::from_rgb(0x9c, 0xd0, 0x7a);
const COMMENT: Color32 = Color32::from_rgb(0x80, 0x88, 0x90);
const API: Color32 = Color32::from_rgb(0x6c, 0xb8, 0xf0);
const BRACKET_BG: Color32 = Color32::from_rgb(0x4a, 0x55, 0x6a);
const KEYWORDS: &[&str] = &[
"var",
"let",
"const",
"function",
"return",
"if",
"else",
"for",
"while",
"do",
"break",
"continue",
"new",
"true",
"false",
"null",
"undefined",
"this",
"typeof",
"in",
"of",
"switch",
"case",
"default",
"try",
"catch",
"throw",
];
/// Expression language names offered by auto-complete (public Expression Language Reference
/// vocabulary).
pub const COMPLETIONS: &[&str] = &[
"thisComp",
"thisLayer",
"thisProperty",
"time",
"value",
"index",
"layer",
"effect",
"mask",
"content",
"transform",
"position",
"anchorPoint",
"scale",
"rotation",
"opacity",
"orientation",
"xRotation",
"yRotation",
"zRotation",
"wiggle",
"loopOut",
"loopIn",
"loopOutDuration",
"loopInDuration",
"valueAtTime",
"velocityAtTime",
"speedAtTime",
"linear",
"ease",
"easeIn",
"easeOut",
"clamp",
"random",
"gaussRandom",
"seedRandom",
"noise",
"degreesToRadians",
"radiansToDegrees",
"timeToFrames",
"framesToTime",
"timeToTimecode",
"length",
"lookAt",
"toComp",
"fromComp",
"toWorld",
"fromWorld",
"sourceRectAtTime",
"sourceText",
"numKeys",
"key",
"nearestKey",
"inPoint",
"outPoint",
"startTime",
"width",
"height",
"frameDuration",
"marker",
"Math",
"comp",
"footage",
"posterizeTime",
"add",
"sub",
"mul",
"div",
"normalize",
"cross",
"dot",
"hslToRgb",
"rgbToHsl",
"createPath",
"points",
"inTangents",
"outTangents",
"isClosed",
];
/// The bracket matching the one at or just before char index `cursor`: (open, close) char
/// indices.
pub fn matching_bracket(text: &str, cursor: usize) -> Option<(usize, usize)> {
let chars: Vec<char> = text.chars().collect();
let pairs = [('(', ')'), ('[', ']'), ('{', '}')];
for at in [cursor, cursor.wrapping_sub(1)] {
let Some(&c) = chars.get(at) else { continue };
if let Some(&(o, cl)) = pairs.iter().find(|(o, _)| *o == c) {
let mut depth = 0;
for (i, &x) in chars.iter().enumerate().skip(at) {
if x == o {
depth += 1;
} else if x == cl {
depth -= 1;
if depth == 0 {
return Some((at, i));
}
}
}
}
if let Some(&(o, cl)) = pairs.iter().find(|(_, cl)| *cl == c) {
let mut depth = 0;
for i in (0..=at).rev() {
if chars[i] == cl {
depth += 1;
} else if chars[i] == o {
depth -= 1;
if depth == 0 {
return Some((i, at));
}
}
}
}
}
None
}
/// The identifier being typed before char index `cursor`, and auto-complete candidates for it.
pub fn completions(text: &str, cursor: usize) -> (String, Vec<&'static str>) {
let chars: Vec<char> = text.chars().collect();
let end = cursor.min(chars.len());
let mut start = end;
while start > 0 && (chars[start - 1].is_alphanumeric() || chars[start - 1] == '_') {
start -= 1;
}
let word: String = chars[start..end].iter().collect();
if word.chars().count() < 2 || word.chars().next().is_some_and(|c| c.is_ascii_digit()) {
return (word, vec![]);
}
let c: Vec<&str> = COMPLETIONS.iter().copied().filter(|w| w.starts_with(word.as_str()) && *w != word).take(6).collect();
(word, c)
}
/// Colour runs for JavaScript: (byte start, byte end, colour).
pub fn highlight(text: &str, base: Color32) -> Vec<(usize, usize, Color32)> {
let b = text.as_bytes();
let mut out = vec![];
let mut i = 0;
while i < b.len() {
let c = b[i];
let start = i;
let col = if c == b'/' && b.get(i + 1) == Some(&b'/') {
while i < b.len() && b[i] != b'\n' {
i += 1;
}
COMMENT
} else if c == b'/' && b.get(i + 1) == Some(&b'*') {
i += 2;
while i < b.len() && !(b[i] == b'*' && b.get(i + 1) == Some(&b'/')) {
i += 1;
}
i = (i + 2).min(b.len());
COMMENT
} else if c == b'"' || c == b'\'' || c == b'`' {
i += 1;
while i < b.len() && b[i] != c {
i += if b[i] == b'\\' { 2 } else { 1 };
}
i = (i + 1).min(b.len());
STRING
} else if c.is_ascii_digit() {
while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'.') {
i += 1;
}
NUMBER
} else if c.is_ascii_alphabetic() || c == b'_' || c == b'$' {
while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_' || b[i] == b'$') {
i += 1;
}
let w = &text[start..i];
if KEYWORDS.contains(&w) {
KEYWORD
} else if COMPLETIONS.contains(&w) {
API
} else {
base
}
} else {
// Advance one whole character.
i += text[i..].chars().next().map_or(1, char::len_utf8);
base
};
match out.last_mut() {
Some((_, e, c)) if *c == col && *e == start => *e = i,
_ => out.push((start, i, col)),
}
}
out
}
/// Byte index of char index `ci`.
fn byte_of(text: &str, ci: usize) -> usize {
text.char_indices().nth(ci).map(|(b, _)| b).unwrap_or(text.len())
}
/// The layout job of the editor text: syntax colours, the matched brackets' background, wrap.
fn layout(text: &str, font: FontId, base: Color32, p: &Scripting, brackets: Option<(usize, usize)>, wrap: f32) -> LayoutJob {
let mut job = LayoutJob::default();
let runs = if p.syntax_highlighting { highlight(text, base) } else { vec![(0, text.len(), base)] };
let marks: Vec<usize> = brackets.filter(|_| p.bracket_matching).map(|(a, b)| vec![byte_of(text, a), byte_of(text, b)]).unwrap_or_default();
for (s, e, col) in runs {
// Split runs at the marked brackets.
let mut cuts = vec![s];
for m in &marks {
if *m >= s && *m < e {
cuts.push(*m);
cuts.push((*m + 1).min(e));
}
}
cuts.push(e);
cuts.sort_unstable();
cuts.dedup();
for w in cuts.windows(2) {
let bg = if marks.contains(&w[0]) { BRACKET_BG } else { Color32::TRANSPARENT };
job.append(&text[w[0]..w[1]], 0.0, TextFormat { font_id: font.clone(), color: col, background: bg, ..Default::default() });
}
}
job.wrap.max_width = if p.word_wrap { wrap } else { f32::INFINITY };
job
}
/// The editor: returns the response; `buf` is edited in place.
pub fn editor(ui: &mut egui::Ui, id: egui::Id, buf: &mut String, rect: Rect, p: &Scripting, color: Color32, rows: usize, t: &Tokens) -> egui::Response {
let size = (p.editor_font_size.clamp(8, 40) as f32) * 0.9;
let font = Tokens::mono(size);
// Line numbers in a gutter on the left.
let gutter = if p.line_numbers { (size * 0.62) * (buf.lines().count().max(1).to_string().len() as f32 + 1.0) + 6.0 } else { 0.0 };
let er = Rect::from_min_max(pos2(rect.min.x + gutter, rect.min.y), rect.max);
let cursor = egui::TextEdit::load_state(ui.ctx(), id).and_then(|s| s.cursor.char_range()).map(|r| r.primary.index.0);
let brackets = cursor.and_then(|c| matching_bracket(buf, c));
let pc = p.clone();
let mut layouter = move |ui: &egui::Ui, text: &dyn egui::TextBuffer, wrap: f32| {
let job = layout(text.as_str(), font.clone(), color, &pc, brackets, wrap);
ui.fonts_mut(|f| f.layout_job(job))
};
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(er));
// Auto-complete: Tab accepts the first candidate (consumed before the editor sees it).
let mut accepted = None;
if p.auto_complete
&& child.memory(|m| m.has_focus(id))
&& let Some(c) = cursor
{
let (word, cands) = completions(buf, c);
if let Some(first) = cands.first()
&& child.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Tab))
{
let at = byte_of(buf, c);
buf.insert_str(at, &first[word.len()..]);
accepted = Some(c + first.chars().count() - word.chars().count());
}
}
let out = egui::TextEdit::multiline(buf)
.id(id)
.font(Tokens::mono(size))
.desired_width(er.width())
.desired_rows(rows)
.frame(egui::Frame::NONE)
.lock_focus(true)
.layouter(&mut layouter)
.show(&mut child);
if let Some(c) = accepted {
let mut st = out.state.clone();
st.cursor.set_char_range(Some(egui::text::CCursorRange::one(egui::text::CCursor::new(c))));
st.store(ui.ctx(), id);
}
let painter = ui.painter();
if p.line_numbers {
let g = out.galley.clone();
let mut line = 1;
let mut new_line = true;
for row in &g.rows {
if new_line {
let y = out.galley_pos.y + row.rect().center().y;
painter.text(pos2(rect.min.x + gutter - 6.0, y), egui::Align2::RIGHT_CENTER, line.to_string(), Tokens::mono(size * 0.85), t.text_faint);
line += 1;
}
new_line = row.ends_with_newline;
}
painter.line_segment([pos2(rect.min.x + gutter - 3.0, rect.min.y), pos2(rect.min.x + gutter - 3.0, rect.max.y)], Stroke::new(1.0, t.separator));
}
// Candidate list under the editor.
if p.auto_complete
&& out.response.has_focus()
&& let Some(c) = out.cursor_range.map(|r| r.primary.index.0)
{
let (_, cands) = completions(buf, c);
if !cands.is_empty() {
let pos = out.galley_pos + out.galley.pos_from_cursor(egui::text::CCursor::new(c)).left_bottom().to_vec2() + vec2(0.0, 2.0);
egui::Area::new(id.with("complete")).order(egui::Order::Tooltip).fixed_pos(pos).show(ui.ctx(), |ui| {
egui::Frame::popup(ui.style()).show(ui, |ui| {
for (i, w) in cands.iter().enumerate() {
let txt = if i == 0 { format!("{w} Tab") } else { w.to_string() };
ui.label(egui::RichText::new(txt).font(Tokens::mono(size * 0.9)).color(if i == 0 { t.text } else { t.text_dim }));
}
});
});
}
}
out.response.response
}
/// Settings ▸ Scripting & Expressions ▸ Show Expression Error Banner: the first failing
/// expression of the comp at the current time, in a banner along the bottom of the viewer
/// (click it to reveal the property).
pub fn error_banner(app: &mut crate::EffectcraftApp, ui: &egui::Ui, area: Rect) {
if !app.session.prefs.scripting.error_banner {
return;
}
let Some(cid) = app.session.active_comp_id() else { return };
let key = (app.session.revision, cid.0, app.session.time().0);
let id = egui::Id::new("expr-error-banner");
let cached: Option<((u64, u64, i64), Vec<serde_json::Value>)> = ui.ctx().data(|d| d.get_temp(id));
let errors = match cached {
Some((k, e)) if k == key => e,
_ => {
let e = app.session.expression_errors(cid);
ui.ctx().data_mut(|d| d.insert_temp(id, (key, e.clone())));
e
}
};
let Some(first) = errors.first() else { return };
let layer = first["layer"].as_u64().unwrap_or(0);
let lname = app.session.active_comp().and_then(|c| c.layer(effectcraft_engine::project::LayerId(layer))).map(|l| l.name.clone()).unwrap_or_default();
let msg = format!(
"⚠ Expression error{}: {} ▸ {}: {}",
if errors.len() > 1 { format!(" (1 of {})", errors.len()) } else { String::new() },
lname,
first["name"].as_str().unwrap_or(""),
first["error"].as_str().unwrap_or("").lines().next().unwrap_or("")
);
let r = Rect::from_min_max(pos2(area.min.x, area.max.y - 22.0), area.max);
let p = ui.painter();
p.rect_filled(r, 0.0, Color32::from_rgb(0xf0, 0xc0, 0x30));
p.text(pos2(r.min.x + 8.0, r.center().y), egui::Align2::LEFT_CENTER, msg, Tokens::ui(11.5), Color32::BLACK);
app.auto.add("viewer.expressionErrorBanner", r, "Expression error banner");
if ui.interact(r, id.with("click"), egui::Sense::click()).clicked() {
let p = serde_json::json!({"props": [{"layer": layer, "prop": first["prop"]}]});
if let Err(e) = crate::menus::invoke(app, ui.ctx(), "timeline.revealProps", p) {
app.ui.status = e;
}
}
}
+150
View File
@@ -0,0 +1,150 @@
//! The Footage panel (double-click footage in the Project panel): the source on its own time
//! ruler, play / pause, In and Out marks, and the Edit Target buttons — Overlay Edit and Ripple
//! Insert Edit — that cut the marked range into the active composition at its current time.
//! Everything runs `footage.*` commands (state in `EditorState::footage_panel`).
use effectcraft_engine::project::{FootageKind, ItemKind};
use effectcraft_engine::time::Tick;
use egui::{Align2, Color32, Rect, Sense, Stroke, pos2, vec2};
use serde_json::json;
use super::panel_kit as kit;
use crate::EffectcraftApp;
use crate::theme::Tokens;
pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let t = app.tokens;
let ctx = ui.ctx().clone();
let p = ui.painter().with_clip_rect(rect);
p.rect_filled(rect, 0.0, t.pasteboard);
let Some(view) = app.session.state.footage_panel.clone() else {
p.text(rect.center(), Align2::CENTER_CENTER, "Double-click footage in the Project panel to open it here", Tokens::ui(12.0), t.text_faint);
app.auto.add("footage.empty", rect, "Footage panel (empty)");
return;
};
let Some(item) = app.session.project.item(view.item).cloned() else {
app.session.state.footage_panel = None;
return;
};
let footage = match &item.kind {
ItemKind::Footage(f) => Some(f.clone()),
_ => None,
};
let (dur, fr) = match &footage {
Some(f) if f.kind != FootageKind::Still && f.duration > Tick::ZERO => (f.duration, f.frame_rate),
Some(f) => (Tick::from_seconds_f64(10.0), f.frame_rate),
None => (Tick::from_seconds_f64(10.0), effectcraft_engine::time::FrameRate::FPS_30),
};
// Title strip.
let top = Rect::from_min_size(rect.min, vec2(rect.width(), 24.0));
p.rect_filled(top, 0.0, t.panel_bg);
p.text(pos2(top.min.x + 10.0, top.center().y), Align2::LEFT_CENTER, format!("Footage: {}", item.name), Tokens::semibold(12.0), t.text);
app.auto.add("footage.title", top, &item.name);
// Bottom: ruler and controls.
// Rows, bottom up: Edit Target buttons, transport, ruler.
let edit_row = Rect::from_min_max(pos2(rect.min.x, rect.max.y - 30.0), rect.max);
let bar = Rect::from_min_max(pos2(rect.min.x, edit_row.min.y - 28.0), pos2(rect.max.x, edit_row.min.y));
let ruler = Rect::from_min_max(pos2(rect.min.x + 10.0, bar.min.y - 26.0), pos2(rect.max.x - 10.0, bar.min.y - 4.0));
p.rect_filled(Rect::from_min_max(pos2(rect.min.x, ruler.min.y - 4.0), rect.max), 0.0, t.panel_bg);
// Canvas.
let area = Rect::from_min_max(pos2(rect.min.x, top.max.y), pos2(rect.max.x, ruler.min.y - 4.0));
if let Some(f) = &footage
&& f.has_video
{
let key = (view.item.0, view.time.0, app.session.revision);
let tid = egui::Id::new("footage-panel-tex");
let cached: Option<((u64, i64, u64), egui::TextureHandle, [u32; 2])> = ctx.data(|d| d.get_temp(tid));
let tex = match cached {
Some((k, tex, size)) if k == key => Some((tex, size)),
_ => app.session.footage.frame(view.item, f, view.time).map(|img| {
let ci = egui::ColorImage::from_rgba_unmultiplied([img.width as usize, img.height as usize], &img.to_rgba8());
let tex = ctx.load_texture("footage-panel", ci, egui::TextureOptions::LINEAR);
ctx.data_mut(|d| d.insert_temp(tid, (key, tex.clone(), [img.width, img.height])));
(tex, [img.width, img.height])
}),
};
if let Some((tex, [w, h])) = tex {
let s = ((area.width() - 20.0) / w as f32).min((area.height() - 20.0) / h as f32).max(0.01);
let r = Rect::from_center_size(area.center(), vec2(w as f32 * s, h as f32 * s));
super::viewer::checker(&p.with_clip_rect(area), r);
p.image(tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
}
} else if let ItemKind::Solid(so) = &item.kind {
let c = so.color;
p.rect_filled(area.shrink(20.0), 0.0, Color32::from_rgb((c[0] * 255.0) as u8, (c[1] * 255.0) as u8, (c[2] * 255.0) as u8));
} else {
p.text(area.center(), Align2::CENTER_CENTER, "No video", Tokens::ui(12.0), t.text_faint);
}
// Ruler: ticks, In/Out span, CTI; click or drag to scrub.
let x_of = |tt: Tick| ruler.min.x + (tt.seconds() / dur.seconds().max(1e-9)) as f32 * ruler.width();
p.rect_filled(ruler, 2.0, t.tl_ruler_bg);
let secs = dur.seconds().max(0.001);
let step = [0.04, 0.2, 1.0, 5.0, 10.0, 30.0, 60.0, 300.0].into_iter().find(|s| (secs / s) as f32 * 50.0 < ruler.width()).unwrap_or(600.0);
let mut k = 0.0;
while k <= secs {
let x = ruler.min.x + (k / secs) as f32 * ruler.width();
p.line_segment([pos2(x, ruler.max.y - 6.0), pos2(x, ruler.max.y)], Stroke::new(1.0, t.tl_ruler_tick));
p.text(pos2(x + 2.0, ruler.min.y + 1.0), Align2::LEFT_TOP, kit::seconds(k), Tokens::ui(9.0), t.tl_ruler_text);
k += step;
}
let (a, b) = (view.in_point.unwrap_or(Tick::ZERO), view.out_point.unwrap_or(dur));
p.rect_filled(Rect::from_min_max(pos2(x_of(a), ruler.max.y - 4.0), pos2(x_of(b), ruler.max.y)), 0.0, t.work_area);
let cx = x_of(view.time);
p.line_segment([pos2(cx, ruler.min.y), pos2(cx, ruler.max.y)], Stroke::new(1.5, t.cti));
let resp = ui.interact(ruler, egui::Id::new("footage-ruler"), Sense::click_and_drag());
app.auto.add("footage.ruler", ruler, "Time ruler");
if (resp.clicked() || resp.dragged())
&& let Some(pt) = resp.interact_pointer_pos()
{
let s = ((pt.x - ruler.min.x) / ruler.width()).clamp(0.0, 1.0) as f64 * dur.seconds();
kit::exec(app, "footage.setTime", json!({"time": s}));
}
// Playback.
let play_id = egui::Id::new("footage-playing");
let playing: bool = ctx.data(|d| d.get_temp(play_id).unwrap_or(false));
if playing {
let dt = ctx.input(|i| i.stable_dt).min(0.1) as f64;
let next = view.time.seconds() + dt;
let next = if next >= dur.seconds() - fr.frame_duration().seconds() { 0.0 } else { next };
let _ = app.session.execute("footage.setTime", json!({"time": next}));
ctx.request_repaint();
}
// Controls.
let y = bar.min.y + 5.0;
let mut x = bar.min.x + 10.0;
p.text(
pos2(x, bar.center().y),
Align2::LEFT_CENTER,
effectcraft_engine::time::format_timecode_ae(fr.frame_at(view.time), fr, false),
Tokens::mono(12.0),
t.timecode,
);
x += 92.0;
if kit::button(app, ui, Rect::from_min_size(pos2(x, y), vec2(54.0, 20.0)), "footage.play", if playing { "Pause" } else { "Play" }, false) {
ctx.data_mut(|d| d.insert_temp(play_id, !playing));
}
x += 60.0;
if kit::button(app, ui, Rect::from_min_size(pos2(x, y), vec2(28.0, 20.0)), "footage.setIn", "{", false) {
kit::exec(app, "footage.setIn", json!({}));
}
x += 32.0;
if kit::button(app, ui, Rect::from_min_size(pos2(x, y), vec2(28.0, 20.0)), "footage.setOut", "}", false) {
kit::exec(app, "footage.setOut", json!({}));
}
x += 36.0;
let span = format!("Δ {}", kit::seconds((b - a).seconds()));
p.text(pos2(x, bar.center().y), Align2::LEFT_CENTER, span, Tokens::ui(11.0), t.text_dim);
let comp_ok = app.session.active_comp_id().is_some();
let target = app.session.active_comp_id().and_then(|c| app.session.project.item(c)).map(|i| i.name.clone()).unwrap_or_default();
let ey = edit_row.min.y + 5.0;
let bx = (edit_row.max.x - 238.0).max(edit_row.min.x + 10.0);
if !target.is_empty() && bx > edit_row.min.x + 140.0 {
p.text(pos2(bx - 8.0, edit_row.center().y), Align2::RIGHT_CENTER, format!("Edit Target: {target}"), Tokens::ui(11.0), t.text_dim);
}
if kit::button(app, ui, Rect::from_min_size(pos2(bx, ey), vec2(110.0, 20.0)), "footage.rippleInsertEdit", "Ripple Insert Edit", false) && comp_ok {
kit::exec(app, "footage.rippleInsertEdit", json!({}));
}
if kit::button(app, ui, Rect::from_min_size(pos2(bx + 116.0, ey), vec2(110.0, 20.0)), "footage.overlayEdit", "Overlay Edit", true) && comp_ok {
kit::exec(app, "footage.overlayEdit", json!({}));
}
}
+54
View File
@@ -397,6 +397,60 @@ pub fn open_form(app: &mut EffectcraftApp, id: &str, p: &Value) -> bool {
],
)
}
"layer.autoTrace" if !has(p, &["channel", "timeSpan", "threshold"]) => (
"Auto-trace".into(),
vec![
Field::choice("timeSpan", "Time Span", &[("Current Frame", json!("currentFrame")), ("Work Area", json!("workArea"))], 0),
Field::choice(
"channel",
"Channel",
&[("Alpha", json!("alpha")), ("Red", json!("red")), ("Green", json!("green")), ("Blue", json!("blue")), ("Luminance", json!("luminance"))],
0,
),
Field::bool("invert", "Invert", false),
Field::num("blur", "Blur (pixels before auto-trace)", 1.0),
Field::num("tolerance", "Tolerance (pixels)", 1.0),
Field::num("threshold", "Threshold (%)", 50.0),
Field::num("minimumArea", "Minimum Area (pixels)", 10.0),
Field::num("cornerRoundness", "Corner Roundness (%)", 50.0),
Field::bool("applyToNewLayer", "Apply To New Layer", false),
],
),
"layer.sceneEditDetection" if !has(p, &["mode"]) => (
"Scene Edit Detection".into(),
vec![
Field::choice(
"mode",
"Action",
&[("Create Markers", json!("markers")), ("Split Layers", json!("split")), ("Split and Precompose", json!("splitPrecompose"))],
0,
),
Field::num("threshold", "Sensitivity threshold (0–1, lower finds more)", 0.25),
],
),
"layer.alignVideoToData" if !has(p, &["data", "videoStart"]) => {
let data: Vec<(String, Value)> = s
.project
.items
.values()
.filter(|i| matches!(&i.kind, effectcraft_engine::project::ItemKind::Footage(f) if f.kind == effectcraft_engine::project::FootageKind::Data))
.map(|i| (i.name.clone(), json!(i.id.0)))
.collect();
if data.is_empty() {
info(app, "Align Video to Data", "Import a data file (JSON, CSV or TSV with a time column) first: File ▸ Import.");
return true;
}
let opts: Vec<(&str, Value)> = data.iter().map(|(n, v)| (n.as_str(), v.clone())).collect();
(
"Align Video to Data".into(),
vec![
Field::choice("data", "Data", &opts, 0),
Field::text("key", "Time field (empty: automatic)", ""),
Field::text("videoStart", "Video start (ISO date-time, hh:mm:ss, timecode; empty: file date)", ""),
Field::num("dataStart", "First sample at (comp seconds)", 0.0),
],
)
}
"file.importPlaceholder" | "file.replaceWithPlaceholder" if p.as_object().is_none_or(|m| m.is_empty()) => (
"New Placeholder".into(),
vec![
+368
View File
@@ -0,0 +1,368 @@
//! Media Browser, Metadata and Progress panels (Window menu).
//!
//! - **Media Browser**: favourites and the folder tree on the left, the folder's files on the
//! right with thumbnails (images and video, decoded through the media layer's probe), double-
//! click to open a folder or import a file, drag files into the Project panel or the timeline.
//! Desktop only (the web build has no file system to browse).
//! - **Metadata**: what we read from the selected item's file (codec, size, rate, duration,
//! colour profile, dates) and the project's, with editable item and project comments.
//! - **Progress**: every background job (render queue, track / mask track / Warp Stabilizer /
//! 3D Camera Tracker / Roto Brush analyses, Content-Aware Fill, Scene Edit Detection) with a
//! progress bar and a cancel button, and the recently finished ones.
use effectcraft_engine::media_browser as mb;
use effectcraft_engine::project::ItemId;
use egui::{Align2, Color32, Rect, Sense, Stroke, pos2, vec2};
use serde_json::{Value, json};
use super::DragPayload;
use super::panel_kit as kit;
use crate::EffectcraftApp;
use crate::theme::Tokens;
// ---------------------------------------------------------------- Media Browser
type Thumb = Option<(egui::TextureHandle, [u32; 2])>;
/// Thumbnail of a file (cached per path; `None` while not decoded or not decodable).
fn thumbnail(app: &EffectcraftApp, ctx: &egui::Context, path: &str, budget: &mut u32) -> Thumb {
let id = egui::Id::new(("mb-thumb", path));
if let Some(t) = ctx.data(|d| d.get_temp::<Thumb>(id)) {
return t;
}
if *budget == 0 {
return None;
}
*budget -= 1;
let thumb = (|| {
let imp = app.session.importer.clone()?;
let f = imp.probe(path).ok()?;
if !f.has_video {
return None;
}
// A synthetic item id keyed by the path (the frame cache keys on the path).
let hid = path.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ b as u64).wrapping_mul(0x100_0000_01b3)) | (1 << 62);
let img = app.session.footage.frame(ItemId(hid), &f, effectcraft_engine::time::Tick::ZERO)?;
let step = (img.width.max(img.height) as f32 / 128.0).ceil().max(1.0) as u32;
let (w, h) = (img.width.div_ceil(step), img.height.div_ceil(step));
let full = img.to_rgba8();
let mut px = Vec::with_capacity((w * h * 4) as usize);
for y in 0..h {
for x in 0..w {
let i = (((y * step) * img.width + x * step) * 4) as usize;
px.extend_from_slice(&full[i..i + 4]);
}
}
let tex = ctx.load_texture(format!("mb-{path}"), egui::ColorImage::from_rgba_unmultiplied([w as usize, h as usize], &px), egui::TextureOptions::LINEAR);
Some((tex, [w, h]))
})();
ctx.data_mut(|d| d.insert_temp(id, thumb.clone()));
thumb
}
pub fn media_browser(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let t = app.tokens;
let ctx = ui.ctx().clone();
let p = ui.painter().with_clip_rect(rect);
p.rect_filled(rect, 0.0, t.panel_bg);
if !mb::available() {
p.text(rect.center(), Align2::CENTER_CENTER, "The Media Browser needs the desktop app (use File ▸ Import here)", Tokens::ui(12.0), t.text_faint);
app.auto.add("mediaBrowser.unavailable", rect, "Media Browser unavailable");
return;
}
let st = app.session.state.media_browser.clone();
let dir = st.folder.clone().unwrap_or_else(mb::home);
// Listing cached per folder for a second.
let lid = egui::Id::new(("mb-list", dir.clone(), st.importable_only));
let now = ctx.input(|i| i.time);
let listing: Option<(f64, Result<Vec<mb::Entry>, String>)> = ctx.data(|d| d.get_temp(lid));
let entries = match listing {
Some((at, l)) if now - at < 1.0 => l,
_ => {
let l = mb::list(&dir, st.importable_only);
ctx.data_mut(|d| d.insert_temp(lid, (now, l.clone())));
l
}
};
// Toolbar: up, home, path, favourite, importable only.
let y = rect.min.y + 6.0;
let mut x = rect.min.x + 8.0;
if kit::button(app, ui, Rect::from_min_size(pos2(x, y), vec2(30.0, 20.0)), "mediaBrowser.up", "↑", false) {
kit::exec(app, "mediaBrowser.go", json!({"path": ".."}));
}
x += 34.0;
if kit::button(app, ui, Rect::from_min_size(pos2(x, y), vec2(48.0, 20.0)), "mediaBrowser.home", "Home", false) {
kit::exec(app, "mediaBrowser.go", json!({}));
}
x += 54.0;
let fav = st.favorites.contains(&dir);
if kit::button(app, ui, Rect::from_min_size(pos2(x, y), vec2(24.0, 20.0)), "mediaBrowser.favorite", if fav { "★" } else { "☆" }, false) {
kit::exec(app, if fav { "mediaBrowser.removeFavorite" } else { "mediaBrowser.addFavorite" }, json!({"path": dir}));
}
x += 30.0;
let only = kit::checkbox(app, ui, pos2(x, y + 2.0), "mediaBrowser.importableOnly", "Media only", st.importable_only);
if only != st.importable_only {
kit::exec(app, "mediaBrowser.go", json!({"path": dir, "importableOnly": only}));
}
// The path on its own row.
let _ = x;
let py = y + 24.0;
p.text(pos2(rect.min.x + 10.0, py + 9.0), Align2::LEFT_CENTER, &dir, Tokens::ui(11.5), t.text_dim);
app.auto.add("mediaBrowser.path", Rect::from_min_max(pos2(rect.min.x + 8.0, py), pos2(rect.max.x - 8.0, py + 18.0)), &dir);
// Left column: favourites.
let side = Rect::from_min_max(pos2(rect.min.x, rect.min.y + 54.0), pos2(rect.min.x + 160.0_f32.min(rect.width() * 0.3), rect.max.y));
p.line_segment([side.right_top(), side.right_bottom()], Stroke::new(1.0, t.separator));
p.text(pos2(side.min.x + 10.0, side.min.y + 10.0), Align2::LEFT_CENTER, "Favorites", Tokens::semibold(11.5), t.text_dim);
let mut fy = side.min.y + 22.0;
let mut places: Vec<(String, String)> = vec![("Home".into(), mb::home())];
places.extend(
st.favorites.iter().map(|f| (std::path::Path::new(f).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| f.clone()), f.clone())),
);
for (i, (name, path)) in places.iter().enumerate() {
let r = Rect::from_min_size(pos2(side.min.x, fy), vec2(side.width(), 20.0));
let resp = ui.interact(r, egui::Id::new(("mb-fav", i)), Sense::click());
if *path == dir {
p.rect_filled(r, 0.0, t.row_selected);
} else if resp.hovered() {
p.rect_filled(r, 0.0, t.hover);
}
p.text(pos2(r.min.x + 14.0, r.center().y), Align2::LEFT_CENTER, name, Tokens::ui(12.0), t.text);
app.auto.add(&format!("mediaBrowser.place.{i}"), r, name);
if resp.clicked() {
kit::exec(app, "mediaBrowser.go", json!({"path": path}));
}
fy += 20.0;
}
// Files.
let list = Rect::from_min_max(pos2(side.max.x + 1.0, side.min.y), rect.max);
let entries = match entries {
Ok(e) => e,
Err(e) => {
p.text(list.center(), Align2::CENTER_CENTER, e, Tokens::ui(12.0), t.danger);
return;
}
};
let tile = vec2(140.0, 112.0);
let cols = ((list.width() - 8.0) / tile.x).floor().max(1.0) as usize;
let mut budget = 2u32;
let scroll_id = egui::Id::new("mb-scroll");
let mut scroll: f32 = ctx.data(|d| d.get_temp(scroll_id).unwrap_or(0.0));
if ui.rect_contains_pointer(list) {
scroll -= ctx.input(|i| i.smooth_scroll_delta.y);
}
let rows = entries.len().div_ceil(cols);
scroll = scroll.clamp(0.0, (rows as f32 * tile.y - list.height() + 8.0).max(0.0));
ctx.data_mut(|d| d.insert_temp(scroll_id, scroll));
let lp = p.with_clip_rect(list);
let mut actions: Vec<(&str, Value)> = vec![];
for (i, e) in entries.iter().enumerate() {
let r = Rect::from_min_size(
pos2(list.min.x + 8.0 + (i % cols) as f32 * tile.x, list.min.y + 8.0 + (i / cols) as f32 * tile.y - scroll),
tile - vec2(8.0, 8.0),
);
if !r.intersects(list) {
continue;
}
let resp = ui.interact(r.intersect(list), egui::Id::new(("mb-entry", &e.path)), Sense::click_and_drag());
app.auto.add(&format!("mediaBrowser.entry.{}", e.name), r, &e.name);
lp.rect_filled(r, 4.0, if resp.hovered() { t.hover } else { t.row });
let thumb = Rect::from_min_max(r.min + vec2(6.0, 6.0), pos2(r.max.x - 6.0, r.max.y - 26.0));
lp.rect_filled(thumb, 3.0, Color32::from_rgb(0x18, 0x18, 0x18));
let kind = if e.is_dir { "Folder" } else { e.kind.unwrap_or("File") };
match (e.is_dir, e.kind) {
(false, Some("image" | "video")) => match thumbnail(app, &ctx, &e.path, &mut budget) {
Some((tex, [w, h])) => {
let s = (thumb.width() / w as f32).min(thumb.height() / h as f32);
lp.image(
tex.id(),
Rect::from_center_size(thumb.center(), vec2(w as f32 * s, h as f32 * s)),
Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)),
Color32::WHITE,
);
}
None => {
lp.text(thumb.center(), Align2::CENTER_CENTER, kind, Tokens::ui(11.0), t.text_faint);
}
},
_ => {
lp.text(thumb.center(), Align2::CENTER_CENTER, if e.is_dir { "▣" } else { kind }, Tokens::ui(if e.is_dir { 28.0 } else { 11.0 }), t.text_faint);
}
}
let name = if e.name.chars().count() > 20 { format!("{}…", e.name.chars().take(19).collect::<String>()) } else { e.name.clone() };
lp.text(pos2(r.min.x + 8.0, r.max.y - 12.0), Align2::LEFT_CENTER, name, Tokens::ui(11.5), t.text);
if resp.double_clicked() {
if e.is_dir {
actions.push(("mediaBrowser.go", json!({"path": e.path})));
} else if e.kind.is_some() {
actions.push(("mediaBrowser.import", json!({"paths": [e.path]})));
}
}
if resp.drag_started() && !e.is_dir && e.kind.is_some() {
egui::DragAndDrop::set_payload(&ctx, DragPayload::Files(vec![e.path.clone()]));
}
resp.context_menu(|ui| {
if !e.is_dir && ui.button("Import").clicked() {
actions.push(("mediaBrowser.import", json!({"paths": [e.path]})));
ui.close();
}
if !e.is_dir && ui.button("Import and Add to Composition").clicked() {
actions.push(("mediaBrowser.import", json!({"paths": [e.path], "addToComp": true})));
ui.close();
}
if e.is_dir && ui.button("Add to Favorites").clicked() {
actions.push(("mediaBrowser.addFavorite", json!({"path": e.path})));
ui.close();
}
});
}
if entries.is_empty() {
lp.text(list.center(), Align2::CENTER_CENTER, "Empty folder", Tokens::ui(12.0), t.text_faint);
}
if budget == 0 {
ctx.request_repaint();
}
for (id, p) in actions {
kit::exec(app, id, p);
}
}
// ---------------------------------------------------------------- Metadata
fn rows_of(v: &Value) -> Vec<(String, String)> {
let Some(o) = v.as_object() else { return vec![] };
o.iter()
.filter(|(k, v)| !v.is_null() && !matches!(k.as_str(), "comment" | "id"))
.map(|(k, v)| {
let s = match v {
Value::String(s) => s.clone(),
Value::Number(n) => n.as_f64().map(|f| if f.fract() == 0.0 { format!("{f:.0}") } else { format!("{f:.3}") }).unwrap_or_default(),
other => other.to_string(),
};
(k.clone(), s)
})
.collect()
}
/// An editable comment field; returns the edited text when it changes.
fn comment_field(ui: &mut egui::Ui, r: Rect, id: &str, text: &str) -> Option<String> {
let key = egui::Id::new(("meta-comment", id));
let mut buf: String = ui.data(|d| d.get_temp(key)).unwrap_or_else(|| text.to_string());
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(r));
let resp = child.add(egui::TextEdit::multiline(&mut buf).desired_width(r.width()).desired_rows(2).hint_text("Add a comment"));
if resp.has_focus() || resp.changed() {
ui.data_mut(|d| d.insert_temp(key, buf.clone()));
} else {
ui.data_mut(|d| d.remove::<String>(key));
}
(resp.lost_focus() && buf != text).then_some(buf)
}
pub fn metadata(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let t = app.tokens;
let p = ui.painter().with_clip_rect(rect);
p.rect_filled(rect, 0.0, t.panel_bg);
let Ok(v) = app.session.execute("item.metadata", json!({})) else { return };
let mut y = rect.min.y + 8.0;
let x0 = rect.min.x + 12.0;
let xv = x0 + 120.0;
let section = |p: &egui::Painter, y: &mut f32, title: &str| {
p.text(pos2(x0, *y + 8.0), Align2::LEFT_CENTER, title, Tokens::semibold(12.0), t.text);
*y += 22.0;
};
if let Some(item) = v.get("item").filter(|i| !i.is_null()) {
let name = item["name"].as_str().unwrap_or_default().to_string();
let id = item["id"].as_u64().unwrap_or(0);
section(&p, &mut y, &format!("{name} ({})", item["type"].as_str().unwrap_or("")));
kit::label(ui, pos2(x0, y), "Comment", &t);
let r = Rect::from_min_size(pos2(xv, y), vec2((rect.max.x - xv - 12.0).max(80.0), 40.0));
app.auto.add("metadata.itemComment", r, item["comment"].as_str().unwrap_or(""));
if let Some(c) = comment_field(ui, r, &format!("item{id}"), item["comment"].as_str().unwrap_or("")) {
kit::exec(app, "project.setComment", json!({"items": [id], "comment": c}));
}
y += 48.0;
for (k, val) in rows_of(item) {
if matches!(k.as_str(), "name" | "type") {
continue;
}
p.text(pos2(x0, y + 8.0), Align2::LEFT_CENTER, &k, Tokens::ui(11.5), t.text_dim);
p.text(pos2(xv, y + 8.0), Align2::LEFT_CENTER, &val, Tokens::ui(11.5), t.text);
app.auto.add(&format!("metadata.item.{k}"), Rect::from_min_size(pos2(xv, y), vec2(200.0, 16.0)), &val);
y += 18.0;
}
y += 10.0;
} else {
p.text(pos2(x0, y + 8.0), Align2::LEFT_CENTER, "Select an item in the Project panel", Tokens::ui(12.0), t.text_faint);
y += 28.0;
}
let proj = v["project"].clone();
section(&p, &mut y, "Project");
kit::label(ui, pos2(x0, y), "Comment", &t);
let r = Rect::from_min_size(pos2(xv, y), vec2((rect.max.x - xv - 12.0).max(80.0), 40.0));
app.auto.add("metadata.projectComment", r, proj["comment"].as_str().unwrap_or(""));
if let Some(c) = comment_field(ui, r, "project", proj["comment"].as_str().unwrap_or("")) {
kit::exec(app, "project.setProjectComment", json!({"comment": c}));
}
y += 48.0;
for (k, val) in rows_of(&proj) {
p.text(pos2(x0, y + 8.0), Align2::LEFT_CENTER, &k, Tokens::ui(11.5), t.text_dim);
p.text(pos2(xv, y + 8.0), Align2::LEFT_CENTER, &val, Tokens::ui(11.5), t.text);
y += 18.0;
}
}
// ---------------------------------------------------------------- Progress
pub fn progress(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let t = app.tokens;
let p = ui.painter().with_clip_rect(rect);
p.rect_filled(rect, 0.0, t.panel_bg);
if !app.session.tasks.is_empty() {
app.session.poll_jobs();
}
let jobs = app.session.jobs();
let mut y = rect.min.y + 8.0;
let x0 = rect.min.x + 12.0;
let w = (rect.width() - 24.0).max(60.0);
if jobs.is_empty() {
p.text(pos2(x0, y + 10.0), Align2::LEFT_CENTER, "No background jobs running", Tokens::ui(12.0), t.text_faint);
y += 28.0;
} else {
ui.ctx().request_repaint_after(std::time::Duration::from_millis(150));
}
for j in &jobs {
p.text(pos2(x0, y + 8.0), Align2::LEFT_CENTER, &j.label, Tokens::medium(12.0), t.text);
let frac = j.fraction.unwrap_or(0.0) as f32;
let pct = j.fraction.map(|f| format!("{:.0} %", f * 100.0)).unwrap_or_else(|| "…".into());
p.text(pos2(x0 + w - 70.0, y + 8.0), Align2::RIGHT_CENTER, format!("{pct} {}", j.message), Tokens::ui(11.0), t.text_dim);
let bar = Rect::from_min_size(pos2(x0, y + 20.0), vec2(w - 76.0, 6.0));
p.rect_filled(bar, 3.0, t.field_bg);
p.rect_filled(Rect::from_min_size(bar.min, vec2(bar.width() * frac.clamp(0.0, 1.0), bar.height())), 3.0, t.accent);
app.auto.add(&format!("progress.job.{}", j.id), Rect::from_min_size(pos2(x0, y), vec2(w, 28.0)), &j.label);
if j.cancellable
&& kit::button(app, ui, Rect::from_min_size(pos2(x0 + w - 64.0, y + 12.0), vec2(64.0, 18.0)), &format!("progress.cancel.{}", j.id), "Cancel", false)
{
kit::exec(app, "jobs.cancel", json!({"job": j.id}));
}
y += 38.0;
}
if !app.session.job_log.is_empty() {
p.line_segment([pos2(x0, y), pos2(x0 + w, y)], Stroke::new(1.0, t.separator));
y += 6.0;
p.text(pos2(x0, y + 8.0), Align2::LEFT_CENTER, "Finished", Tokens::semibold(11.5), t.text_dim);
y += 20.0;
for r in app.session.job_log.iter().rev().take(20) {
let col = match r.status.as_str() {
"done" => t.text,
"cancelled" => t.text_dim,
_ => t.danger,
};
let msg = if r.message.is_empty() { format!("{} · {:.1} s", r.status, r.seconds) } else { format!("{} · {}", r.status, r.message) };
p.text(pos2(x0, y + 8.0), Align2::LEFT_CENTER, &r.label, Tokens::ui(11.5), col);
p.text(pos2(x0 + w, y + 8.0), Align2::RIGHT_CENTER, msg, Tokens::ui(11.0), t.text_faint);
y += 18.0;
if y > rect.max.y {
break;
}
}
}
}
+14
View File
@@ -3,13 +3,16 @@
pub mod anim_tools;
pub mod camera_tracker_ui;
pub mod comp_settings;
pub mod content_fill_panel;
pub mod dialogs;
pub mod dialogs_3d;
pub mod effect_controls;
pub mod effects_presets;
pub mod essential;
pub mod expr_bar;
pub mod expr_editor;
pub mod flowchart;
pub mod footage_panel;
pub mod forms;
pub mod fx_widgets;
pub mod graph;
@@ -20,14 +23,17 @@ pub mod key_dialogs;
pub mod layer_panel;
pub mod layer_styles_dialog;
pub mod markers_ui;
pub mod media_panels;
pub mod misc;
pub mod paint_panels;
pub mod panel_kit;
pub mod precomp;
pub mod project;
pub mod properties;
pub mod puppet_tool;
pub mod render_queue;
pub mod roto_tool;
pub mod scopes_panel;
pub mod script_console;
pub mod settings;
pub mod shortcut_editor;
@@ -57,6 +63,8 @@ pub enum DragPayload {
Effect(String),
/// A property dragged from the timeline (to the Essential Graphics panel).
Property { layer: u64, prop: u64 },
/// Files from the Media Browser (import; into the timeline: import and add).
Files(Vec<String>),
}
/// The current time formatted per project settings (timecode with `;` for drop-frame, frames
@@ -99,6 +107,12 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: PanelKind, rect: Rec
PanelKind::Brushes => paint_panels::brushes(app, ui, rect),
PanelKind::EssentialGraphics => essential::show(app, ui, rect),
PanelKind::Flowchart => flowchart::show(app, ui, rect),
PanelKind::LumetriScopes => scopes_panel::show(app, ui, rect),
PanelKind::Footage => footage_panel::show(app, ui, rect),
PanelKind::MediaBrowser => media_panels::media_browser(app, ui, rect),
PanelKind::Metadata => media_panels::metadata(app, ui, rect),
PanelKind::Progress => media_panels::progress(app, ui, rect),
PanelKind::ContentAwareFill => content_fill_panel::show(app, ui, rect),
}
}
+70
View File
@@ -0,0 +1,70 @@
//! Small immediate-mode controls shared by the Lumetri Scopes, Footage, Media Browser, Metadata,
//! Progress and Content-Aware Fill panels. Each registers its automation id.
use egui::{Align2, Rect, pos2, vec2};
use crate::theme::Tokens;
use crate::{EffectcraftApp, widgets};
/// A dropdown; returns the newly chosen index.
pub fn dropdown(app: &mut EffectcraftApp, ui: &mut egui::Ui, r: Rect, auto: &str, options: &[&str], cur: usize) -> Option<usize> {
let t = app.tokens;
let id = egui::Id::new(("kit-dd", auto));
let text = options.get(cur).copied().unwrap_or("");
if widgets::dropdown(ui, r, text, &t, id).clicked() {
widgets::open_popup(ui, id);
}
app.auto.add(auto, r, text);
let opts: Vec<String> = options.iter().map(|s| s.to_string()).collect();
widgets::popup_menu(ui, id, r.left_bottom(), &opts, Some(cur)).filter(|i| *i != cur)
}
/// A checkbox with a label; returns the new state.
pub fn checkbox(app: &mut EffectcraftApp, ui: &mut egui::Ui, at: egui::Pos2, auto: &str, text: &str, on: bool) -> bool {
let t = app.tokens;
let r = Rect::from_min_size(at, vec2(16.0, 16.0));
let clicked = widgets::checkbox(ui, r, on, &t, egui::Id::new(("kit-cb", auto))).clicked();
ui.painter().text(pos2(r.max.x + 6.0, r.center().y), Align2::LEFT_CENTER, text, Tokens::ui(12.0), t.text);
let full = Rect::from_min_size(at, vec2(22.0 + text.len() as f32 * 6.5, 16.0));
app.auto.add(auto, full, text);
if clicked { !on } else { on }
}
/// A text button; true when clicked.
pub fn button(app: &mut EffectcraftApp, ui: &mut egui::Ui, r: Rect, auto: &str, text: &str, primary: bool) -> bool {
let t = app.tokens;
let clicked = widgets::text_button(ui, r, text, primary, &t, egui::Id::new(("kit-btn", auto))).clicked();
app.auto.add(auto, r, text);
clicked
}
/// A dimmed label at (x, y-row).
pub fn label(ui: &egui::Ui, at: egui::Pos2, text: &str, t: &Tokens) {
ui.painter().text(pos2(at.x, at.y + 9.0), Align2::LEFT_CENTER, text, Tokens::ui(12.0), t.text_dim);
}
/// A draggable number; returns the new value.
#[allow(clippy::too_many_arguments)]
pub fn number(app: &mut EffectcraftApp, ui: &mut egui::Ui, at: egui::Pos2, auto: &str, v: f64, speed: f64, range: (f64, f64), dec: usize, suffix: &str) -> f64 {
let t = app.tokens;
let (r, nv, _) = widgets::hot_number_at(ui, at, egui::Id::new(("kit-n", auto)), v, speed, range, dec, suffix, &t);
app.auto.add(auto, r, &format!("{v}"));
nv.unwrap_or(v)
}
/// Run a command, reporting errors in the status bar.
pub fn exec(app: &mut EffectcraftApp, id: &str, p: serde_json::Value) -> Option<serde_json::Value> {
match app.session.execute(id, p) {
Ok(v) => Some(v),
Err(e) => {
app.ui.status = e.to_string();
None
}
}
}
/// Format seconds as `m:ss.ff`.
pub fn seconds(s: f64) -> String {
let m = (s / 60.0).floor();
format!("{}:{:05.2}", m as i64, s - m * 60.0)
}
+15
View File
@@ -481,6 +481,11 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
ItemKind::Folder if !app.ui.project_open_folders.remove(&id.0) => {
app.ui.project_open_folders.insert(id.0);
}
// Footage (not data) and solids open in the Footage panel.
ItemKind::Footage(f) if f.kind != effectcraft_engine::project::FootageKind::Data => {
actions.push(("footage.open".into(), json!({"item": id.0})))
}
ItemKind::Solid(_) => actions.push(("footage.open".into(), json!({"item": id.0}))),
_ => {}
}
}
@@ -539,6 +544,16 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
egui::DragAndDrop::clear_payload(&ctx);
}
}
// Files dragged from the Media Browser: import.
if let Some(DragPayload::Files(paths)) = egui::DragAndDrop::payload::<DragPayload>(&ctx).as_deref()
&& hover_y.is_some()
{
lp.rect_stroke(list.shrink(1.0), 0.0, Stroke::new(1.0, t.accent.gamma_multiply(0.6)), egui::StrokeKind::Inside);
if ctx.input(|i| i.pointer.any_released()) {
actions.push(("mediaBrowser.import".into(), json!({"paths": paths})));
egui::DragAndDrop::clear_payload(&ctx);
}
}
// Drag ghost.
if let Some(DragPayload::Item(iid)) = egui::DragAndDrop::payload::<DragPayload>(&ctx).as_deref()
&& let Some(pos) = ctx.pointer_hover_pos()
+199
View File
@@ -0,0 +1,199 @@
//! Lumetri Scopes panel (Window ▸ Lumetri Scopes): waveform (RGB / Luma / YC), vectorscope
//! (YUV / HLS), histogram and parade (RGB / YUV) of the active composition's frame at the current
//! time, with the colour standard (Rec. 601 / 709 / 2020), 8-bit or float scale and clamp. The
//! maths is `effectcraft_raster::scopes`; agents read the same numbers with `scopes.analyze`.
use effectcraft_engine::commands::panels_cmds::scope_frame;
use effectcraft_engine::raster::scopes::{self, ColorStandard, Scope, ScopeKind, ScopeOpts};
use egui::{Align2, Color32, Rect, Stroke, pos2, vec2};
use serde::{Deserialize, Serialize};
use super::panel_kit as kit;
use crate::EffectcraftApp;
use crate::theme::Tokens;
/// Panel options (serde in the UI state).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ScopesState {
pub scope: String,
pub standard: String,
pub float: bool,
pub clamp: bool,
}
impl Default for ScopesState {
fn default() -> Self {
ScopesState { scope: "waveformRgb".into(), standard: "rec709".into(), float: false, clamp: true }
}
}
const STANDARDS: [&str; 3] = ["Rec. 601", "Rec. 709", "Rec. 2020"];
#[derive(Clone)]
struct Cached {
key: (u64, u64, i64, String, u32),
scope: Scope,
tex: Option<egui::TextureHandle>,
}
pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let t = app.tokens;
let p = ui.painter().with_clip_rect(rect);
p.rect_filled(rect, 0.0, t.panel_bg);
let mut st = app.ui.scopes.clone();
let kind = ScopeKind::from_name(&st.scope).unwrap_or(ScopeKind::WaveformRgb);
let standard = ColorStandard::from_name(&st.standard).unwrap_or_default();
// Top bar: scope, standard, 8-bit / float, clamp.
let mut x = rect.min.x + 8.0;
let y = rect.min.y + 6.0;
let labels: Vec<&str> = ScopeKind::ALL.iter().map(|k| k.label()).collect();
let cur = ScopeKind::ALL.iter().position(|k| *k == kind).unwrap_or(0);
if let Some(i) = kit::dropdown(app, ui, Rect::from_min_size(pos2(x, y), vec2(150.0, 20.0)), "scopes.kind", &labels, cur) {
st.scope = ScopeKind::ALL[i].name().into();
}
x += 158.0;
let si = ColorStandard::ALL.iter().position(|c| *c == standard).unwrap_or(1);
if let Some(i) = kit::dropdown(app, ui, Rect::from_min_size(pos2(x, y), vec2(90.0, 20.0)), "scopes.standard", &STANDARDS, si) {
st.standard = ColorStandard::ALL[i].name().into();
}
x += 98.0;
if let Some(i) = kit::dropdown(app, ui, Rect::from_min_size(pos2(x, y), vec2(70.0, 20.0)), "scopes.scale", &["8 Bit", "Float"], usize::from(st.float)) {
st.float = i == 1;
}
x += 78.0;
// Narrow panels: Clamp Signal on a second row.
let (cx, cy, top) = if x + 110.0 > rect.max.x { (rect.min.x + 8.0, y + 26.0, 60.0) } else { (x, y, 34.0) };
st.clamp = kit::checkbox(app, ui, pos2(cx, cy + 2.0), "scopes.clamp", "Clamp Signal", st.clamp);
if st != app.ui.scopes {
app.ui.scopes = st.clone();
}
let area = Rect::from_min_max(pos2(rect.min.x + 8.0, rect.min.y + top), pos2(rect.max.x - 8.0, rect.max.y - 8.0));
if area.width() < 40.0 || area.height() < 40.0 {
return;
}
p.rect_filled(area, 2.0, Color32::from_rgb(0x10, 0x10, 0x10));
app.auto.add("scopes.plot", area, kind.label());
let Some(cid) = app.session.active_comp_id() else {
p.text(area.center(), Align2::CENTER_CENTER, "Open a composition to see its scopes", Tokens::ui(12.0), t.text_faint);
return;
};
// Plot rectangle: square for vectorscopes.
let plot = if kind.is_vectorscope() {
let s = area.width().min(area.height()) - 16.0;
Rect::from_center_size(area.center(), vec2(s, s))
} else {
Rect::from_min_max(area.min + vec2(34.0, 8.0), area.max - vec2(8.0, 8.0))
};
let size = (plot.width().max(plot.height()) as u32).clamp(64, 512);
let o = ScopeOpts {
standard,
float: st.float,
clamp: st.clamp,
width: if kind.is_vectorscope() { size } else { (plot.width() as u32).clamp(64, 768) },
height: if kind.is_vectorscope() { size } else { (plot.height() as u32).clamp(32, 512) },
};
let time = app.session.time();
let key = (app.session.revision, cid.0, time.0, format!("{}{}{}{}{}x{}", st.scope, st.standard, st.float, st.clamp, o.width, o.height), 0);
let ctx = ui.ctx().clone();
let id = egui::Id::new("scopes-cache");
let cached: Option<Cached> = ctx.data(|d| d.get_temp(id));
let cached = match cached {
Some(c) if c.key == key => c,
_ => {
let Some(frame) = scope_frame(&app.session, cid, time, 480) else { return };
let scope = scopes::compute(&frame, kind, &o);
let tex = (kind != ScopeKind::Histogram).then(|| {
let mono = matches!(kind, ScopeKind::WaveformLuma | ScopeKind::VectorscopeYuv | ScopeKind::VectorscopeHls);
let img = egui::ColorImage::from_rgba_unmultiplied([scope.width as usize, scope.height as usize], &tint(&scope, mono));
ctx.load_texture("lumetri-scope", img, egui::TextureOptions::LINEAR)
});
let c = Cached { key, scope, tex };
ctx.data_mut(|d| d.insert_temp(id, c.clone()));
c
}
};
graticule(&p, plot, kind, &o, &t);
if let Some(tex) = &cached.tex {
p.image(tex.id(), plot, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
} else {
histogram(&p, plot, &cached.scope);
}
}
/// Trace colours: green-tinted mono for luma/vectorscope, per-channel colours otherwise.
fn tint(s: &Scope, mono: bool) -> Vec<u8> {
let n = s.width as usize * s.height as usize;
let mut out = vec![0u8; n * 4];
for i in 0..n {
let (r, g, b) = (s.planes[0][i], s.planes[1][i], s.planes[2][i]);
let (r, g, b) = if mono {
let m = r.max(g).max(b);
(m * 0.75, m, m * 0.75)
} else {
(r, g, b)
};
let a = r.max(g).max(b).min(1.0);
out[i * 4] = (r.min(1.0) * 255.0) as u8;
out[i * 4 + 1] = (g.min(1.0) * 255.0) as u8;
out[i * 4 + 2] = (b.min(1.0) * 255.0) as u8;
out[i * 4 + 3] = (a * 255.0) as u8;
}
out
}
fn graticule(p: &egui::Painter, plot: Rect, kind: ScopeKind, o: &ScopeOpts, t: &Tokens) {
let line = Stroke::new(1.0, Color32::from_rgba_unmultiplied(255, 255, 255, 28));
if kind.is_vectorscope() {
let c = plot.center();
for r in [0.25f32, 0.5, 0.75, 1.0] {
p.circle_stroke(c, plot.width() / 2.0 * r, line);
}
p.line_segment([pos2(plot.min.x, c.y), pos2(plot.max.x, c.y)], line);
p.line_segment([pos2(c.x, plot.min.y), pos2(c.x, plot.max.y)], line);
for (name, [u, v]) in scopes::vector_targets(o.standard, kind == ScopeKind::VectorscopeHls) {
let q = pos2(plot.min.x + (u + 0.5) * plot.width(), plot.min.y + (0.5 - v) * plot.height());
p.rect_stroke(Rect::from_center_size(q, vec2(8.0, 8.0)), 0.0, Stroke::new(1.0, Color32::from_rgb(0xc8, 0x6a, 0x6a)), egui::StrokeKind::Middle);
p.text(q + vec2(7.0, -7.0), Align2::LEFT_BOTTOM, name, Tokens::ui(10.0), t.text_dim);
}
return;
}
if kind == ScopeKind::Histogram {
return;
}
let (lo, hi) = o.range();
let marks: &[f32] = if o.float { &[-0.25, 0.0, 0.25, 0.5, 0.75, 1.0, 1.25] } else { &[0.0, 0.25, 0.5, 0.75, 1.0] };
for v in marks {
let y = plot.max.y - (v - lo) / (hi - lo) * plot.height();
p.line_segment([pos2(plot.min.x, y), pos2(plot.max.x, y)], line);
let label = if o.float { format!("{v:.2}") } else { format!("{}", (v * 255.0).round() as i32) };
p.text(pos2(plot.min.x - 4.0, y), Align2::RIGHT_CENTER, label, Tokens::ui(9.5), t.text_faint);
}
if matches!(kind, ScopeKind::ParadeRgb | ScopeKind::ParadeYuv) {
for k in 1..3 {
let x = plot.min.x + plot.width() * k as f32 / 3.0;
p.line_segment([pos2(x, plot.min.y), pos2(x, plot.max.y)], line);
}
}
}
fn histogram(p: &egui::Painter, plot: Rect, s: &Scope) {
let bars = scopes::histogram_bars(s);
let max = bars.iter().flat_map(|b| b.iter()).copied().max().unwrap_or(1).max(1) as f32;
let cols = [
Color32::from_rgba_unmultiplied(230, 70, 70, 150),
Color32::from_rgba_unmultiplied(70, 220, 90, 150),
Color32::from_rgba_unmultiplied(80, 120, 255, 150),
];
let n = bars[0].len().max(1) as f32;
for (c, b) in bars.iter().enumerate() {
let pts: Vec<egui::Pos2> =
b.iter().enumerate().map(|(i, v)| pos2(plot.min.x + i as f32 / n * plot.width(), plot.max.y - (*v as f32 / max).sqrt() * plot.height())).collect();
for (i, q) in pts.iter().enumerate() {
p.line_segment([pos2(q.x, plot.max.y), *q], Stroke::new((plot.width() / n).max(1.0), cols[c].gamma_multiply(0.5)));
if i > 0 {
p.line_segment([pts[i - 1], *q], Stroke::new(1.0, cols[c]));
}
}
}
}
+72 -14
View File
@@ -98,9 +98,8 @@ pub fn character(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
widgets::open_popup(ui, pop);
}
app.auto.add("character.font", fr, "Font family");
let fams: Vec<String> = effectcraft_engine::text_families();
if let Some(i) = widgets::popup_menu(ui, pop, fr.left_bottom(), &fams, fams.iter().position(|f| *f == doc.font)) {
actions.push(json!({"font": fams[i]}));
if let Some(f) = font_popup(app, ui, pop, fr.left_bottom(), &doc.font) {
actions.push(json!({"font": f}));
}
y += 28.0;
let sr = Rect::from_min_size(pos2(x0, y), vec2(w - 84.0, 22.0));
@@ -469,20 +468,29 @@ pub fn paragraph(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
}
y += 3.0 * 28.0 + 6.0;
// Direction and composer popups.
let dr = Rect::from_min_size(pos2(x0, y), vec2(w / 2.0 - 4.0, 22.0));
let dirs = vec!["Left-to-Right Text".to_string(), "Right-to-Left Text".to_string()];
let dpop = egui::Id::new("para-direction-pop");
// Direction and composer popups. Settings ▸ Type ▸ Text Engine: the South Asian and Middle
// Eastern engine offers the paragraph direction and the World-Ready composers (the Latin
// engine shows the direction only for right-to-left text already set).
let world_ready = app.session.prefs.type_.text_engine == "southAsian";
let rtl = doc.direction == Direction::Rtl;
if widgets::dropdown(ui, dr, &dirs[rtl as usize], &t, egui::Id::new("para-direction")).clicked() && enabled {
widgets::open_popup(ui, dpop);
}
app.auto.add("paragraph.direction", dr, "Text direction");
if let Some(i) = widgets::popup_menu(ui, dpop, dr.left_bottom(), &dirs, Some(rtl as usize)) {
actions.push(json!({"direction": if i == 1 { "rtl" } else { "ltr" }}));
if world_ready || rtl {
let dr = Rect::from_min_size(pos2(x0, y), vec2(w / 2.0 - 4.0, 22.0));
let dirs = vec!["Left-to-Right Text".to_string(), "Right-to-Left Text".to_string()];
let dpop = egui::Id::new("para-direction-pop");
if widgets::dropdown(ui, dr, &dirs[rtl as usize], &t, egui::Id::new("para-direction")).clicked() && enabled {
widgets::open_popup(ui, dpop);
}
app.auto.add("paragraph.direction", dr, "Text direction");
if let Some(i) = widgets::popup_menu(ui, dpop, dr.left_bottom(), &dirs, Some(rtl as usize)) {
actions.push(json!({"direction": if i == 1 { "rtl" } else { "ltr" }}));
}
}
let cr = Rect::from_min_size(pos2(x0 + w / 2.0, y), vec2(w / 2.0, 22.0));
let comps = vec!["Every-line Composer".to_string(), "Single-line Composer".to_string()];
let comps = if world_ready {
vec!["World-Ready Every-line Composer".to_string(), "World-Ready Single-line Composer".to_string()]
} else {
vec!["Every-line Composer".to_string(), "Single-line Composer".to_string()]
};
let cpop = egui::Id::new("para-composer-pop");
let single = doc.composer == Composer::SingleLine;
if widgets::dropdown(ui, cr, &comps[single as usize], &t, egui::Id::new("para-composer")).clicked() && enabled {
@@ -510,6 +518,56 @@ pub fn paragraph(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
}
/// The font menu: recent fonts first, names in English or the fonts' own language, and a
/// "Sample" preview in each font (Settings ▸ Type).
fn font_popup(app: &EffectcraftApp, ui: &mut egui::Ui, id: egui::Id, pos: egui::Pos2, current: &str) -> Option<String> {
if !ui.data(|d| d.get_temp::<bool>(id.with("open")).unwrap_or(false)) {
return None;
}
let rows = effectcraft_engine::font_menu(&app.session.prefs);
let preview = app.session.prefs.type_.font_preview;
let t = app.tokens;
let mut chosen = None;
let area = egui::Area::new(id.with("area")).order(egui::Order::Foreground).fixed_pos(pos).show(ui.ctx(), |ui| {
egui::Frame::popup(ui.style()).show(ui, |ui| {
ui.set_min_width(if preview { 300.0 } else { 180.0 });
egui::ScrollArea::vertical().max_height(420.0).show(ui, |ui| {
for r in &rows {
if r.family.is_empty() {
ui.separator();
continue;
}
let resp = ui.selectable_label(r.family == current, &r.display);
if preview && ui.is_rect_visible(resp.rect) {
let key = egui::Id::new(("font-preview", &r.family));
let lines: std::sync::Arc<Vec<Vec<[f32; 2]>>> = match ui.data(|d| d.get_temp(key)) {
Some(l) => l,
None => {
let l = std::sync::Arc::new(effectcraft_engine::font_preview(&r.family, 14.0));
ui.data_mut(|d| d.insert_temp(key, l.clone()));
l
}
};
let o = pos2(resp.rect.max.x - 120.0, resp.rect.center().y + 5.0);
for poly in lines.iter() {
let pts: Vec<egui::Pos2> = poly.iter().map(|p| o + vec2(p[0], p[1])).collect();
ui.painter().add(egui::Shape::line(pts, egui::Stroke::new(1.0, t.text_dim)));
}
}
if resp.clicked() {
chosen = Some(r.family.clone());
}
}
});
});
});
let outside = ui.input(|i| i.pointer.any_pressed()) && !area.response.contains_pointer() && !area.response.hovered();
if chosen.is_some() || outside || ui.input(|i| i.key_pressed(egui::Key::Escape)) {
ui.data_mut(|d| d.insert_temp(id.with("open"), false));
}
chosen
}
/// Align panel: align selected layers to the composition (or to the selection).
pub fn align(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let t = app.tokens;
+12 -9
View File
@@ -1573,15 +1573,17 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let er = Rect::from_min_max(pos2(graph_x0 + 8.0, r.min.y + 3.0), pos2(rect.max.x - 14.0, r.max.y - 3.0));
let buf_id = egui::Id::new(("expr-buf", uid));
let mut buf: String = ctx.data(|d| d.get_temp(buf_id)).unwrap_or_else(|| ex.text.clone());
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(er));
let resp = child.add(
egui::TextEdit::multiline(&mut buf)
.id(egui::Id::new(("expr-edit", uid)))
.font(Tokens::mono(11.5))
.text_color(if ex.enabled { expr_col } else { t.text_dim })
.desired_width(er.width())
.desired_rows((*lines).clamp(1, 8))
.frame(egui::Frame::NONE),
// Settings ▸ Scripting & Expressions ▸ Expressions Editor.
let sp = app.session.prefs.scripting.clone();
let resp = super::expr_editor::editor(
ui,
egui::Id::new(("expr-edit", uid)),
&mut buf,
er,
&sp,
if ex.enabled { expr_col } else { t.text_dim },
(*lines).clamp(1, 8),
&t,
);
app.auto.add(&format!("timeline.prop.{uid}.expression"), er, &prop.name);
let commit = resp.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter) && (i.modifiers.command || i.modifiers.ctrl));
@@ -1986,6 +1988,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
actions.push(("effect.apply".into(), json!({"effect": e, "layers": [l.0]})));
}
}
crate::panels::DragPayload::Files(paths) => actions.push(("mediaBrowser.import".into(), json!({"paths": paths, "addToComp": true}))),
crate::panels::DragPayload::Property { .. } => {}
}
egui::DragAndDrop::clear_payload(&ctx);
+93 -8
View File
@@ -517,12 +517,14 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let sub = g.grid_subdivisions.max(1) as f32;
let sstep = step / sub;
let draw_minor = sstep >= 4.0;
// Settings ▸ Grids & Guides ▸ Grid Style (lines, dashed lines or dots).
let style = g.grid_style.clone();
let mut i = 0u32;
let mut gx = comp_rect.min.x;
while gx <= comp_rect.max.x {
let is_major = i.is_multiple_of(g.grid_subdivisions.max(1));
if is_major || draw_minor {
painter.line_segment([pos2(gx, comp_rect.min.y), pos2(gx, comp_rect.max.y)], if is_major { major } else { minor });
styled_line(&painter, [pos2(gx, comp_rect.min.y), pos2(gx, comp_rect.max.y)], if is_major { major } else { minor }, &style);
}
gx += sstep;
i += 1;
@@ -532,7 +534,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
while gy <= comp_rect.max.y {
let is_major = i.is_multiple_of(g.grid_subdivisions.max(1));
if is_major || draw_minor {
painter.line_segment([pos2(comp_rect.min.x, gy), pos2(comp_rect.max.x, gy)], if is_major { major } else { minor });
styled_line(&painter, [pos2(comp_rect.min.x, gy), pos2(comp_rect.max.x, gy)], if is_major { major } else { minor }, &style);
}
gy += sstep;
i += 1;
@@ -545,13 +547,15 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
if app.ui.viewer.guides {
let [r, gg, b] = hex_rgb(&app.session.prefs.grids.guide_color).unwrap_or([0x3c, 0xc8, 0xf0]);
let stroke = Stroke::new(1.0, Color32::from_rgb(r, gg, b));
// Settings ▸ Grids & Guides ▸ Guide Style.
let style = app.session.prefs.grids.guide_style.clone();
for g in &comp.guides {
if g.vertical {
let x = comp_rect.min.x + g.position as f32 * zoom;
painter.line_segment([pos2(x, area.min.y), pos2(x, area.max.y)], stroke);
styled_line(&painter, [pos2(x, area.min.y), pos2(x, area.max.y)], stroke, &style);
} else {
let y = comp_rect.min.y + g.position as f32 * zoom;
painter.line_segment([pos2(area.min.x, y), pos2(area.max.x, y)], stroke);
styled_line(&painter, [pos2(area.min.x, y), pos2(area.max.x, y)], stroke, &style);
}
}
}
@@ -613,6 +617,28 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
let hover = ui.input(|i| i.pointer.hover_pos());
ov::draw_paths(app, &painter, &map, &ectx, l, col, &sel_vertices, pen, hover, &mut vertex_hits, &mut paths);
}
// Settings ▸ Previews ▸ Show Internal Wireframes: outlines of the layers inside a
// selected collapsed precomp.
if app.session.prefs.previews.show_internal_wireframes
&& l.switches.collapse
&& let effectcraft_engine::project::LayerSource::Comp { item } = &l.source
&& let Some(nc) = app.session.project.comp(*item)
{
let (outer, _) = l2c(&ectx, l);
let nctx = EvalCtx::new(&app.session.project, *item, nc, ectx.source_time(l));
for nl in nc.layers.iter().filter(|nl| nl.is_active_at(nctx.time) && !nl.is_3d()) {
if let Some((_, q, _)) = layer_quad(&nctx, nl) {
let sq: Vec<Pos2> = q
.iter()
.map(|p| {
let c = outer.apply(gv2(p[0], p[1]));
map.to_screen([c.x, c.y])
})
.collect();
painter.add(egui::Shape::closed_line(sq, Stroke::new(1.0, col.gamma_multiply(0.6))));
}
}
}
let Some((m, q, _)) = layer_quad(&ectx, l) else {
// Cameras, lights, empty layers: just the anchor.
if let Some(tr) = l.transform() {
@@ -661,6 +687,41 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
}
// Settings ▸ 3D: Extended Viewer (3D layers outlined beyond the comp frame) and Show 3D
// Reference Axes (world X/Y/Z in the corner, turning with the view).
let has_3d = comp.layers.iter().any(|l| l.is_3d() && l.is_active_at(time));
if has_3d && app.session.prefs.three_d.extended_viewer {
for l in comp.layers.iter().filter(|l| l.is_3d() && l.is_active_at(time) && l.has_video()) {
if let Some((_, q, _)) = layer_quad(&ectx, l) {
let sq: Vec<Pos2> = q.iter().map(|p| map.to_screen(*p)).collect();
let outside = sq.iter().any(|p| !comp_rect.contains(*p));
if outside {
painter.add(egui::Shape::closed_line(sq, Stroke::new(1.0, t.label(l.label).gamma_multiply(0.55))));
}
}
}
}
if has_3d && app.session.prefs.three_d.show_reference_axes {
let pc = cam_state(&ectx).projection(cw as f64, ch as f64);
let o3 = effectcraft_engine::geom::vec3(cw as f64 / 2.0, ch as f64 / 2.0, 0.0);
let o = pc.apply(o3);
let corner = pos2(area.min.x + 34.0, area.max.y - 34.0);
for (axis, col, name) in [
(effectcraft_engine::geom::vec3(1.0, 0.0, 0.0), Color32::from_rgb(0xe0, 0x50, 0x50), "X"),
(effectcraft_engine::geom::vec3(0.0, 1.0, 0.0), Color32::from_rgb(0x60, 0xd0, 0x60), "Y"),
(effectcraft_engine::geom::vec3(0.0, 0.0, 1.0), Color32::from_rgb(0x50, 0x8c, 0xf0), "Z"),
] {
let e = pc.apply(o3 + axis * 10.0);
let d = vec2((e.x - o.x) as f32, (e.y - o.y) as f32);
let d = if d.length() > 1e-4 { d.normalized() * 22.0 } else { vec2(0.0, 0.0) };
painter.arrow(corner, d, Stroke::new(1.5, col));
painter.text(corner + d * 1.25, Align2::CENTER_CENTER, name, Tokens::ui(10.0), col);
}
app.auto.add("viewer.referenceAxes", Rect::from_center_size(corner, vec2(56.0, 56.0)), "3D reference axes");
}
super::expr_editor::error_banner(app, ui, area);
// Track points of the current track (Tracker panel) on its layer, while that layer is selected.
let mut track_hits = vec![];
let track_cur = super::tracker::viewer_track(app);
@@ -1564,6 +1625,26 @@ fn empty_state(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
/// `#rrggbb` → sRGB bytes.
/// A grid or guide line in the Grids & Guides style: `lines`, `dashed` or `dots`.
pub(crate) fn styled_line(painter: &egui::Painter, pts: [Pos2; 2], stroke: Stroke, style: &str) {
match style {
"dashed" => {
painter.add(egui::Shape::dashed_line(&pts, stroke, 6.0, 4.0));
}
"dots" => {
painter.add(egui::Shape::dotted_line(&pts, stroke.color, 4.0, stroke.width.max(1.0) * 0.75));
}
_ => {
painter.line_segment(pts, stroke);
}
}
}
/// Texture filtering for Viewer Zoom Quality: More Accurate = bilinear, Faster = nearest.
pub(crate) fn zoom_texture_options(smooth: bool) -> egui::TextureOptions {
if smooth { egui::TextureOptions::LINEAR } else { egui::TextureOptions::NEAREST }
}
pub(crate) fn hex_rgb(s: &str) -> Option<[u8; 3]> {
let h = s.trim().trim_start_matches('#');
if h.len() != 6 || !h.is_ascii() {
@@ -1577,14 +1658,17 @@ pub(crate) fn hex_rgb(s: &str) -> Option<[u8; 3]> {
/// straight from their wgpu texture (registered with egui-wgpu, no readback).
fn show_frame(app: &mut EffectcraftApp, ctx: &egui::Context, key: crate::frames::FrameKey, img: crate::frames::FrameImage) {
use crate::frames::FrameImage;
// Settings ▸ Previews ▸ Viewer Zoom Quality.
let smooth = app.session.prefs.viewer_zoom_smooth();
let opts = zoom_texture_options(smooth);
match img {
FrameImage::Cpu(img) => {
match &mut app.viewer_tex {
Some((tex, k)) if tex.size() == img.size => {
tex.set((*img).clone(), egui::TextureOptions::LINEAR);
tex.set((*img).clone(), opts);
*k = key;
}
_ => app.viewer_tex = Some((ctx.load_texture("viewer-frame", (*img).clone(), egui::TextureOptions::LINEAR), key)),
_ => app.viewer_tex = Some((ctx.load_texture("viewer-frame", (*img).clone(), opts), key)),
}
app.viewer_shown = app.viewer_tex.as_ref().map(|(t, k)| (t.id(), *k));
app.viewer_image = Some(img);
@@ -1594,12 +1678,13 @@ fn show_frame(app: &mut EffectcraftApp, ctx: &egui::Context, key: crate::frames:
let Some(rs) = &app.wgpu else { return };
let view = f.texture.create_view(&Default::default());
let mut ren = rs.renderer.write();
let filter = if smooth { eframe::wgpu::FilterMode::Linear } else { eframe::wgpu::FilterMode::Nearest };
let id = match &app.viewer_native {
Some((id, _, _)) => {
ren.update_egui_texture_from_wgpu_texture(&rs.device, &view, eframe::wgpu::FilterMode::Linear, *id);
ren.update_egui_texture_from_wgpu_texture(&rs.device, &view, filter, *id);
*id
}
None => ren.register_native_texture(&rs.device, &view, eframe::wgpu::FilterMode::Linear),
None => ren.register_native_texture(&rs.device, &view, filter),
};
drop(ren);
app.viewer_native = Some((id, key, f));
+6 -1
View File
@@ -269,7 +269,9 @@ pub(crate) fn motion_path(app: &mut EffectcraftApp, painter: &egui::Painter, map
let c = p2c.apply(gv2(v[0], v[1]));
map.to_screen([c.x, c.y])
};
let (lt0, lt1) = (pos.keys[0].time, pos.keys[pos.keys.len() - 1].time);
// Settings ▸ Composition ▸ Motion Path: all keyframes, none, or a window around the CTI.
let times: Vec<Tick> = pos.keys.iter().map(|k| k.time).collect();
let Some((lt0, lt1)) = app.session.prefs.motion_path_span(&times, l.layer_time(ectx.time)) else { return };
let fd = ectx.comp.frame_duration();
let mut pts = vec![];
let mut lt = lt0;
@@ -285,6 +287,9 @@ pub(crate) fn motion_path(app: &mut EffectcraftApp, painter: &egui::Painter, map
}
let sel = &app.session.state.selected_keys;
for (i, k) in pos.keys.iter().enumerate() {
if k.time < lt0 || k.time > lt1 {
continue;
}
let v = k.value.as_vec3();
let s = to_scr(v);
let (tin, tout) = effectcraft_engine::keyframe::spatial_tangents(&pos.keys, i);
+9 -3
View File
@@ -282,11 +282,11 @@ pub(crate) fn proportional_grid(app: &EffectcraftApp, painter: &egui::Painter, c
let (nx, ny) = (g.proportional_horizontal.max(1), g.proportional_vertical.max(1));
for i in 1..nx {
let x = comp_rect.min.x + comp_rect.width() * i as f32 / nx as f32;
painter.line_segment([pos2(x, comp_rect.min.y), pos2(x, comp_rect.max.y)], s);
super::viewer::styled_line(painter, [pos2(x, comp_rect.min.y), pos2(x, comp_rect.max.y)], s, &g.grid_style);
}
for i in 1..ny {
let y = comp_rect.min.y + comp_rect.height() * i as f32 / ny as f32;
painter.line_segment([pos2(comp_rect.min.x, y), pos2(comp_rect.max.x, y)], s);
super::viewer::styled_line(painter, [pos2(comp_rect.min.x, y), pos2(comp_rect.max.x, y)], s, &g.grid_style);
}
}
@@ -324,6 +324,11 @@ fn transformed(img: &egui::ColorImage, ch: Channel, colorized: bool, stops: f32,
pub(crate) fn draw_frame(app: &mut EffectcraftApp, ctx: &egui::Context, painter: &egui::Painter, comp_rect: Rect, cid: ItemId, ectx: &EvalCtx) {
let opts = app.session.state.viewer.clone();
let snap = showing_snapshot(app, ctx);
// Settings ▸ Video ▸ Mirror on Computer Monitor off: playback goes to Video Preview only.
if crate::prefs_live::main_viewer_hidden(app) && !snap {
painter.text(comp_rect.center(), Align2::CENTER_CENTER, "Playing on Video Preview", Tokens::ui(13.0), Color32::from_gray(150));
return;
}
if opts.fast_previews == FastPreviews::Wireframe && !snap {
let zoom = comp_rect.width() / ectx.comp.width.max(1) as f32;
let map = ViewerMap { origin: comp_rect.min, zoom, comp: [ectx.comp.width as f32, ectx.comp.height as f32], area: comp_rect };
@@ -400,6 +405,7 @@ pub(crate) fn draw_frame(app: &mut EffectcraftApp, ctx: &egui::Context, painter:
rect
};
let Some(src) = app.viewer_image.clone() else { return };
let zoom_opts = super::viewer::zoom_texture_options(app.session.prefs.viewer_zoom_smooth());
let key = {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
@@ -410,7 +416,7 @@ pub(crate) fn draw_frame(app: &mut EffectcraftApp, ctx: &egui::Context, painter:
let tex = match ctx.data(|d| d.get_temp::<(u64, egui::TextureHandle)>(id)) {
Some((k, tex)) if k == key => tex,
_ => {
let tex = ctx.load_texture("viewer-display", transformed(&src, opts.channel, opts.colorized, opts.exposure, dc), egui::TextureOptions::LINEAR);
let tex = ctx.load_texture("viewer-display", transformed(&src, opts.channel, opts.colorized, opts.exposure, dc), zoom_opts);
ctx.data_mut(|d| d.insert_temp(id, (key, tex.clone())));
tex
}
+16 -1
View File
@@ -47,10 +47,25 @@ pub fn summary(app: &EffectcraftApp, ctx: &egui::Context, item: ItemId) -> Optio
let ItemKind::Footage(f) = &app.session.project.item(item)?.kind else { return None };
m.insert(item.0, None);
let (f, footage, map, ctx) = (f.clone(), app.session.footage.clone(), app.waveforms.map.clone(), ctx.clone());
// Settings ▸ Disk ▸ Database and Cache Folder: summaries are kept on disk between sessions.
let cache = app.session.media_cache_folder();
std::thread::Builder::new()
.name("ec-waveform".into())
.spawn(move || {
let peaks = effectcraft_engine::render::audio::footage_peaks(footage.as_ref(), item, &f, f.duration, BINS_PER_SEC);
use effectcraft_engine::media_cache;
let file = cache.and_then(|d| media_cache::peaks_path(&d, &f.path, BINS_PER_SEC));
let peaks = match file.as_deref().and_then(media_cache::load_peaks) {
Some(p) => p,
None => {
let p = effectcraft_engine::render::audio::footage_peaks(footage.as_ref(), item, &f, f.duration, BINS_PER_SEC);
if let Some(file) = &file
&& let Err(e) = media_cache::store_peaks(file, &p)
{
log::warn!("media cache: {}: {e}", file.display());
}
p
}
};
if let Ok(mut m) = map.lock() {
m.insert(item.0, Some(Arc::new(Summary { bins_per_sec: BINS_PER_SEC, peaks })));
}
+141
View File
@@ -0,0 +1,141 @@
//! 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, json};
use crate::EffectcraftApp;
use crate::frames::FrameKey;
/// Run once per frame, before the panels draw.
pub fn frame(app: &mut EffectcraftApp, ctx: &egui::Context) {
dropped_files(app, ctx);
memory_watch(app, ctx);
home_on_open(app, ctx);
video_preview(app, ctx);
}
/// Files dropped on the window are imported (layered files as Default Drag Import As says).
fn dropped_files(app: &mut EffectcraftApp, ctx: &egui::Context) {
let paths: Vec<String> =
ctx.input(|i| i.raw.dropped_files.iter().map(|f| f.path().to_string_lossy().to_string()).filter(|p| std::path::Path::new(p).is_absolute()).collect());
if paths.is_empty() {
return;
}
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 let Some(p) = proj.first()
&& let Err(e) = crate::menus::invoke(app, ctx, "file.open", json!({"path": p}))
{
app.ui.status = e;
}
if !rest.is_empty() {
let params = json!({"paths": rest, "drag": true, "importAs": app.session.prefs.drag_import_as()});
if let Err(e) = crate::menus::invoke(app, ctx, "file.import", params) {
app.ui.status = e;
}
}
}
/// Re-read the system's free memory every few seconds (cache budgets follow it).
fn memory_watch(app: &mut EffectcraftApp, ctx: &egui::Context) {
let now = ctx.input(|i| i.time);
let id = egui::Id::new("prefs-memory-watch");
let last = ctx.data(|d| d.get_temp::<f64>(id));
if last.is_some_and(|t| now - t < 10.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.
fn home_on_open(app: &mut EffectcraftApp, ctx: &egui::Context) {
let id = egui::Id::new("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::new("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((*img).clone(), opts);
t
}
None => ctx.load_texture("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;
}
}
+4
View File
@@ -612,6 +612,9 @@ pub struct UiState {
/// Flowchart panel options (layers, effects, solids, direction, root comp).
#[serde(default)]
pub flowchart: crate::panels::flowchart::FlowOptions,
/// Lumetri Scopes panel options.
#[serde(default)]
pub scopes: crate::panels::scopes_panel::ScopesState,
}
impl Default for UiState {
@@ -665,6 +668,7 @@ impl Default for UiState {
anim_tools: AnimToolsState::default(),
mini_flowchart: None,
flowchart: Default::default(),
scopes: Default::default(),
}
}
}
+25
View File
@@ -75,6 +75,29 @@ pub struct Tokens {
pub gap: f32,
pub tab_h: f32,
pub row_h: f32,
/// Settings ▸ Appearance ▸ Use Gradients: panel tab strips and buttons get a soft vertical
/// gradient (off: flat fills).
pub gradients: bool,
}
/// A vertical gradient fill (`top` → `bottom`) over `rect`.
pub fn gradient_rect(painter: &egui::Painter, rect: egui::Rect, top: Color32, bottom: Color32) {
let mut m = egui::Mesh::default();
m.colored_vertex(rect.left_top(), top);
m.colored_vertex(rect.right_top(), top);
m.colored_vertex(rect.right_bottom(), bottom);
m.colored_vertex(rect.left_bottom(), bottom);
m.add_triangle(0, 1, 2);
m.add_triangle(0, 2, 3);
painter.add(egui::Shape::mesh(m));
}
impl Tokens {
/// The gradient top colour for a fill (a little lighter), or the fill itself when gradients
/// are off.
pub fn grad_top(&self, c: Color32) -> Color32 {
if self.gradients { c.lerp_to_gamma(Color32::WHITE, 0.06) } else { c }
}
}
impl Tokens {
@@ -123,6 +146,7 @@ impl Tokens {
gap: 4.0,
tab_h: 30.0,
row_h: 22.0,
gradients: true,
};
match kind {
ThemeKind::Dark => dark,
@@ -192,6 +216,7 @@ impl Tokens {
let [r, g, b] = p.label_rgb(*l);
t.labels[i] = Color32::from_rgb(r, g, b);
}
t.gradients = p.appearance.use_gradients;
t
}