UI.9: retain shared docking across upstream workspace changes
This commit is contained in:
@@ -0,0 +1,411 @@
|
||||
//! The colour picker every colour input opens, laid out like After Effects' Color Picker: a
|
||||
//! square and a slider for the channel chosen with the H / S / B / R / G / B buttons, the new
|
||||
//! colour over the original, the HSB and RGB values, the hex code, and OK / Cancel.
|
||||
//!
|
||||
//! Colours are sRGB components (0–1), as the project stores them. Changes apply as they are made
|
||||
//! (After Effects' Preview); Cancel or Escape goes back to the colour the picker opened with.
|
||||
|
||||
use egui::{Color32, Rect, Response, Sense, Stroke, StrokeKind, Ui, pos2, vec2};
|
||||
|
||||
use crate::i18n::tr;
|
||||
use crate::widgets::{open_popup, popup_is_open, pressed_outside, select_all};
|
||||
|
||||
/// A colour button for egui-laid-out rows and dialogs: a swatch that opens [`color_popup`]. Don't
|
||||
/// use egui's `color_edit_button_rgb(a)` for project colours: they read linear values, so the
|
||||
/// swatch shows lighter and a picked colour is stored darker. The value is only rewritten when the
|
||||
/// user picks a colour.
|
||||
pub fn srgb_color_button(ui: &mut Ui, c: &mut [f32; 3]) -> Response {
|
||||
let (rect, mut resp) = ui.allocate_exact_size(ui.spacing().interact_size, Sense::click());
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::ColorButton, ui.is_enabled(), srgb_hex(*c)));
|
||||
let stroke = if resp.hovered() { ui.visuals().widgets.hovered.fg_stroke } else { ui.visuals().widgets.inactive.bg_stroke };
|
||||
ui.painter().rect_filled(rect, 2.0, srgb32(*c));
|
||||
ui.painter().rect_stroke(rect, 2.0, stroke, StrokeKind::Inside);
|
||||
if resp.clicked() {
|
||||
open_popup(ui, resp.id);
|
||||
}
|
||||
if color_popup(ui, resp.id, rect.left_bottom(), c) {
|
||||
resp.mark_changed();
|
||||
}
|
||||
resp
|
||||
}
|
||||
|
||||
/// The colour picker as a popup at `pos`, bound to `c`, opened with [`open_popup`]. Returns true
|
||||
/// when the colour changed (Cancel, Escape and the original swatch change it back).
|
||||
pub fn color_popup(ui: &mut Ui, id: egui::Id, pos: egui::Pos2, c: &mut [f32; 3]) -> bool {
|
||||
if !popup_is_open(ui, id) {
|
||||
return false;
|
||||
}
|
||||
let orig_id = id.with("original");
|
||||
let original = ui.data_mut(|d| *d.get_temp_mut_or_insert_with(orig_id, || *c));
|
||||
let mut out = Outcome::default();
|
||||
let area = egui::Area::new(id.with("area")).order(egui::Order::Foreground).fixed_pos(pos + vec2(0.0, 4.0)).show(ui.ctx(), |ui| {
|
||||
egui::Frame::popup(ui.style()).show(ui, |ui| out = color_picker(ui, id, c, original));
|
||||
});
|
||||
if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
out.close = Some(false);
|
||||
}
|
||||
if pressed_outside(ui.ctx(), &area.response) {
|
||||
out.close.get_or_insert(true);
|
||||
}
|
||||
if let Some(keep) = out.close {
|
||||
if !keep && *c != original {
|
||||
*c = original;
|
||||
out.changed = true;
|
||||
}
|
||||
ui.data_mut(|d| {
|
||||
d.insert_temp(id.with("open"), false);
|
||||
d.remove::<[f32; 3]>(orig_id);
|
||||
});
|
||||
}
|
||||
out.changed
|
||||
}
|
||||
|
||||
/// What the picker did this frame.
|
||||
#[derive(Default)]
|
||||
struct Outcome {
|
||||
changed: bool,
|
||||
/// Close the picker, keeping the colour (OK) or not (Cancel).
|
||||
close: Option<bool>,
|
||||
}
|
||||
|
||||
/// The channel the slider sets; the square sets the other two of its model.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Chan {
|
||||
H,
|
||||
S,
|
||||
V,
|
||||
R,
|
||||
G,
|
||||
B,
|
||||
}
|
||||
|
||||
impl Chan {
|
||||
/// The square's (across, up) channels while `self` is on the slider (After Effects' layout).
|
||||
fn square(self) -> (Chan, Chan) {
|
||||
match self {
|
||||
Chan::H => (Chan::S, Chan::V),
|
||||
Chan::S => (Chan::H, Chan::V),
|
||||
Chan::V => (Chan::H, Chan::S),
|
||||
Chan::R => (Chan::B, Chan::G),
|
||||
Chan::G => (Chan::B, Chan::R),
|
||||
Chan::B => (Chan::R, Chan::G),
|
||||
}
|
||||
}
|
||||
|
||||
fn index(self) -> usize {
|
||||
match self {
|
||||
Chan::H | Chan::R => 0,
|
||||
Chan::S | Chan::G => 1,
|
||||
Chan::V | Chan::B => 2,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_hsv(self) -> bool {
|
||||
matches!(self, Chan::H | Chan::S | Chan::V)
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour as both HSB and RGB: HSB keeps the hue (and saturation) of greys and black, where
|
||||
/// RGB has none, so moving off black returns to the hue that was chosen.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct Pick {
|
||||
hsv: [f32; 3],
|
||||
rgb: [f32; 3],
|
||||
}
|
||||
|
||||
impl Pick {
|
||||
fn get(&self, ch: Chan) -> f32 {
|
||||
let v = if ch.is_hsv() { self.hsv } else { self.rgb };
|
||||
v.get(ch.index()).copied().unwrap_or(0.0)
|
||||
}
|
||||
|
||||
fn set(mut self, ch: Chan, v: f32) -> Pick {
|
||||
let v = v.clamp(0.0, 1.0);
|
||||
if ch.is_hsv() {
|
||||
if let Some(x) = self.hsv.get_mut(ch.index()) {
|
||||
*x = v;
|
||||
}
|
||||
self.rgb = hsv_to_rgb(self.hsv);
|
||||
} else {
|
||||
if let Some(x) = self.rgb.get_mut(ch.index()) {
|
||||
*x = v;
|
||||
}
|
||||
self.hsv = keep_hue(rgb_to_hsv(self.rgb), self.hsv);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// The colour at (`u` across, `v` up) on the square, or `t` up the slider.
|
||||
fn at(&self, ch: Chan, u: f32, v: f32) -> Pick {
|
||||
let (x, y) = ch.square();
|
||||
self.set(x, u).set(y, v)
|
||||
}
|
||||
}
|
||||
|
||||
const SQUARE: f32 = 200.0;
|
||||
const SLIDER_W: f32 = 16.0;
|
||||
|
||||
fn color_picker(ui: &mut Ui, id: egui::Id, c: &mut [f32; 3], original: [f32; 3]) -> Outcome {
|
||||
let state_id = id.with("pick");
|
||||
let mut pick = match ui.data(|d| d.get_temp::<([f32; 3], [f32; 3])>(state_id)) {
|
||||
Some((hsv, rgb)) if rgb == *c => Pick { hsv, rgb },
|
||||
Some((hsv, _)) => Pick { hsv: keep_hue(rgb_to_hsv(*c), hsv), rgb: *c },
|
||||
None => Pick { hsv: rgb_to_hsv(*c), rgb: *c },
|
||||
};
|
||||
// The slider's channel is remembered between pickers, as After Effects does.
|
||||
let chan_id = egui::Id::new("color-picker-channel");
|
||||
let mut chan = ui.data(|d| d.get_temp::<usize>(chan_id)).and_then(|i| CHANS.get(i).map(|c| c.0)).unwrap_or(Chan::H);
|
||||
let before = pick;
|
||||
let mut out = Outcome::default();
|
||||
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 10.0;
|
||||
// The square and slider, with OK and Cancel under the square's left edge.
|
||||
ui.vertical(|ui| {
|
||||
ui.horizontal_top(|ui| {
|
||||
square(ui, chan, &mut pick);
|
||||
slider(ui, chan, &mut pick);
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 6.0;
|
||||
if ui.add_sized(vec2(72.0, 20.0), egui::Button::new(tr("OK"))).clicked() {
|
||||
out.close = Some(true);
|
||||
}
|
||||
if ui.add_sized(vec2(72.0, 20.0), egui::Button::new(tr("Cancel"))).clicked() {
|
||||
out.close = Some(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.vertical(|ui| {
|
||||
ui.spacing_mut().item_spacing.y = 4.0;
|
||||
if swatches(ui, pick.rgb, original) {
|
||||
pick = Pick { hsv: keep_hue(rgb_to_hsv(original), pick.hsv), rgb: original };
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
let mut field = |ui: &mut Ui, ch: Chan, name: &str, scale: f32, suffix: &str| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 2.0;
|
||||
let radio = ui.radio(chan == ch, format!("{name}:"));
|
||||
// Line the fields up whatever each label's width.
|
||||
ui.add_space((40.0 - radio.rect.width()).max(0.0));
|
||||
if radio.clicked() {
|
||||
chan = ch;
|
||||
}
|
||||
// Rounded as the hex code rounds, and 360° shows as 0°.
|
||||
let mut v = (pick.get(ch) * scale).round();
|
||||
if ch == Chan::H && v >= 360.0 {
|
||||
v = 0.0;
|
||||
}
|
||||
let drag = egui::DragValue::new(&mut v).range(0.0..=scale).fixed_decimals(0).suffix(suffix).speed(scale / 255.0);
|
||||
if ui.add_sized(vec2(56.0, 18.0), drag).labelled_by(radio.id).changed() {
|
||||
pick = pick.set(ch, v.round() / scale);
|
||||
}
|
||||
});
|
||||
};
|
||||
field(ui, Chan::H, "H", 360.0, "°");
|
||||
field(ui, Chan::S, "S", 100.0, "%");
|
||||
field(ui, Chan::V, "B", 100.0, "%");
|
||||
ui.add_space(4.0);
|
||||
field(ui, Chan::R, "R", 255.0, "");
|
||||
field(ui, Chan::G, "G", 255.0, "");
|
||||
field(ui, Chan::B, "B", 255.0, "");
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 4.0;
|
||||
let mut rgb = pick.rgb;
|
||||
if hex_field(ui, id.with("hex"), &mut rgb) {
|
||||
pick = Pick { hsv: keep_hue(rgb_to_hsv(rgb), pick.hsv), rgb };
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
if let Some(i) = CHANS.iter().position(|(c, _)| *c == chan) {
|
||||
ui.data_mut(|d| d.insert_temp(chan_id, i));
|
||||
}
|
||||
if pick != before && pick.rgb != *c {
|
||||
*c = pick.rgb;
|
||||
out.changed = true;
|
||||
}
|
||||
ui.data_mut(|d| d.insert_temp(state_id, (pick.hsv, pick.rgb)));
|
||||
out
|
||||
}
|
||||
|
||||
/// The channels in the order of their buttons.
|
||||
const CHANS: [(Chan, &str); 6] = [(Chan::H, "H"), (Chan::S, "S"), (Chan::V, "B"), (Chan::R, "R"), (Chan::G, "G"), (Chan::B, "B")];
|
||||
|
||||
/// Drag or click on the square to set its two channels.
|
||||
fn square(ui: &mut Ui, chan: Chan, pick: &mut Pick) {
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(SQUARE, SQUARE), Sense::click_and_drag());
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Slider, true, "Color field"));
|
||||
let (x, y) = chan.square();
|
||||
if let Some(p) = resp.interact_pointer_pos().filter(|_| resp.is_pointer_button_down_on()) {
|
||||
*pick = pick.at(chan, (p.x - rect.min.x) / rect.width(), 1.0 - (p.y - rect.min.y) / rect.height());
|
||||
}
|
||||
// Hue changes unevenly across a row, so the HSB squares get a finer grid.
|
||||
let n: u32 = if chan.is_hsv() { 24 } else { 8 };
|
||||
let row = n + 1;
|
||||
let mut mesh = egui::Mesh::default();
|
||||
for yi in 0..=n {
|
||||
for xi in 0..=n {
|
||||
let (u, v) = (xi as f32 / n as f32, yi as f32 / n as f32);
|
||||
mesh.colored_vertex(rect.lerp_inside(vec2(u, v)), srgb32(pick.at(chan, u, 1.0 - v).rgb));
|
||||
if xi < n && yi < n {
|
||||
let k = yi * row + xi;
|
||||
mesh.add_triangle(k, k + 1, k + row);
|
||||
mesh.add_triangle(k + 1, k + row + 1, k + row);
|
||||
}
|
||||
}
|
||||
}
|
||||
ui.painter().add(mesh);
|
||||
let at = rect.lerp_inside(vec2(pick.get(x), 1.0 - pick.get(y)));
|
||||
let light = pick.rgb[0] * 0.3 + pick.rgb[1] * 0.59 + pick.rgb[2] * 0.11 > 0.6;
|
||||
ui.painter().circle_stroke(at, 5.0, Stroke::new(1.5, if light { Color32::BLACK } else { Color32::WHITE }));
|
||||
}
|
||||
|
||||
/// Drag or click on the slider to set `chan`; arrows on both sides mark its value.
|
||||
fn slider(ui: &mut Ui, chan: Chan, pick: &mut Pick) {
|
||||
let (outer, resp) = ui.allocate_exact_size(vec2(SLIDER_W + 12.0, SQUARE), Sense::click_and_drag());
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Slider, true, "Color slider"));
|
||||
let bar = Rect::from_center_size(outer.center(), vec2(SLIDER_W, SQUARE));
|
||||
if let Some(p) = resp.interact_pointer_pos().filter(|_| resp.is_pointer_button_down_on()) {
|
||||
*pick = pick.set(chan, 1.0 - (p.y - bar.min.y) / bar.height());
|
||||
}
|
||||
let n: u32 = if chan == Chan::H { 36 } else { 16 };
|
||||
let mut mesh = egui::Mesh::default();
|
||||
for i in 0..=n {
|
||||
let t = i as f32 / n as f32;
|
||||
// The hue slider shows pure hues; the others vary their channel in the current colour.
|
||||
let col = if chan == Chan::H { hsv_to_rgb([1.0 - t, 1.0, 1.0]) } else { pick.set(chan, 1.0 - t).rgb };
|
||||
let y = bar.min.y + t * bar.height();
|
||||
mesh.colored_vertex(pos2(bar.min.x, y), srgb32(col));
|
||||
mesh.colored_vertex(pos2(bar.max.x, y), srgb32(col));
|
||||
if i < n {
|
||||
let k = 2 * i;
|
||||
mesh.add_triangle(k, k + 1, k + 2);
|
||||
mesh.add_triangle(k + 1, k + 3, k + 2);
|
||||
}
|
||||
}
|
||||
ui.painter().add(mesh);
|
||||
let y = bar.min.y + (1.0 - pick.get(chan)) * bar.height();
|
||||
let fg = ui.visuals().strong_text_color();
|
||||
let stroke = Stroke::new(1.2, fg);
|
||||
for (edge, dir) in [(outer.min.x + 1.0, 1.0), (outer.max.x - 1.0, -1.0)] {
|
||||
let tip = pos2(edge + dir * 4.0, y);
|
||||
ui.painter().line_segment([pos2(edge, y - 4.0), tip], stroke);
|
||||
ui.painter().line_segment([pos2(edge, y + 4.0), tip], stroke);
|
||||
}
|
||||
}
|
||||
|
||||
/// The new colour over the original; returns true when the original is clicked (to go back to it).
|
||||
fn swatches(ui: &mut Ui, new: [f32; 3], original: [f32; 3]) -> bool {
|
||||
let (rect, _) = ui.allocate_exact_size(vec2(64.0, 64.0), Sense::hover());
|
||||
let (top, bottom) = rect.split_top_bottom_at_fraction(0.5);
|
||||
let new_resp = ui.interact(top, ui.id().with("new-swatch"), Sense::hover());
|
||||
new_resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Other, true, "New color"));
|
||||
let old = ui.interact(bottom, ui.id().with("original-swatch"), Sense::click()).on_hover_text(tr("Original color: click to go back to it"));
|
||||
old.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "Original color"));
|
||||
ui.painter().rect_filled(top, 0.0, srgb32(new));
|
||||
ui.painter().rect_filled(bottom, 0.0, srgb32(original));
|
||||
ui.painter().rect_stroke(rect, 0.0, ui.visuals().widgets.inactive.bg_stroke, StrokeKind::Outside);
|
||||
old.clicked()
|
||||
}
|
||||
|
||||
/// `hsv` with `old`'s hue where `hsv` has none (a grey or black), and `old`'s saturation where it
|
||||
/// has neither (black).
|
||||
fn keep_hue(mut hsv: [f32; 3], old: [f32; 3]) -> [f32; 3] {
|
||||
if hsv[1] == 0.0 || hsv[2] == 0.0 {
|
||||
hsv[0] = old[0];
|
||||
}
|
||||
if hsv[2] == 0.0 {
|
||||
hsv[1] = old[1];
|
||||
}
|
||||
hsv
|
||||
}
|
||||
|
||||
/// The hex field. While it has focus it keeps what was typed (`id` holds the text); otherwise it
|
||||
/// shows the colour. Focusing it selects the code, so typing replaces it; a valid code applies as
|
||||
/// it is typed.
|
||||
fn hex_field(ui: &mut Ui, id: egui::Id, c: &mut [f32; 3]) -> bool {
|
||||
let mut text = ui.data(|d| d.get_temp::<String>(id)).unwrap_or_else(|| srgb_hex(*c).trim_start_matches('#').to_string());
|
||||
let mut changed = false;
|
||||
let label = ui.label("#");
|
||||
let resp = ui
|
||||
.add(egui::TextEdit::singleline(&mut text).id(id.with("edit")).desired_width(62.0).char_limit(7).font(egui::TextStyle::Monospace))
|
||||
.labelled_by(label.id);
|
||||
if resp.gained_focus() {
|
||||
select_all(ui.ctx(), resp.id, &text);
|
||||
}
|
||||
if resp.changed()
|
||||
&& let Some(rgb) = hex_rgb(&text)
|
||||
{
|
||||
let v = rgb.map(|b| b as f32 / 255.0);
|
||||
if v != *c {
|
||||
*c = v;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if resp.has_focus() {
|
||||
ui.data_mut(|d| d.insert_temp(id, text.clone()));
|
||||
} else {
|
||||
ui.data_mut(|d| d.remove::<String>(id));
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// An sRGB colour (components 0–1) as an egui colour.
|
||||
pub fn srgb32(c: [f32; 3]) -> Color32 {
|
||||
let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
Color32::from_rgb(b(c[0]), b(c[1]), b(c[2]))
|
||||
}
|
||||
|
||||
/// An sRGB colour (components 0–1) as `#RRGGBB`.
|
||||
pub fn srgb_hex(c: [f32; 3]) -> String {
|
||||
let col = srgb32(c);
|
||||
format!("#{:02X}{:02X}{:02X}", col.r(), col.g(), col.b())
|
||||
}
|
||||
|
||||
/// Parse a hex colour: `#RRGGBB`, `RRGGBB`, `#RGB` or `RGB` (any case, surrounding space ignored).
|
||||
pub fn hex_rgb(s: &str) -> Option<[u8; 3]> {
|
||||
let h = s.trim().trim_start_matches('#');
|
||||
if !h.is_ascii() {
|
||||
return None;
|
||||
}
|
||||
let digit = |i: usize| h.get(i..i + 1).and_then(|d| u8::from_str_radix(d, 16).ok());
|
||||
let pair = |i: usize| h.get(i..i + 2).and_then(|d| u8::from_str_radix(d, 16).ok());
|
||||
match h.len() {
|
||||
3 => Some([digit(0)? * 17, digit(1)? * 17, digit(2)? * 17]),
|
||||
6 => Some([pair(0)?, pair(2)?, pair(4)?]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// sRGB (components 0–1) to hue, saturation and value (0–1).
|
||||
pub fn rgb_to_hsv([r, g, b]: [f32; 3]) -> [f32; 3] {
|
||||
let (r, g, b) = (r.clamp(0.0, 1.0), g.clamp(0.0, 1.0), b.clamp(0.0, 1.0));
|
||||
let max = r.max(g).max(b);
|
||||
let d = max - r.min(g).min(b);
|
||||
if d <= 0.0 {
|
||||
return [0.0, 0.0, max];
|
||||
}
|
||||
let h = if max == r {
|
||||
((g - b) / d).rem_euclid(6.0)
|
||||
} else if max == g {
|
||||
(b - r) / d + 2.0
|
||||
} else {
|
||||
(r - g) / d + 4.0
|
||||
};
|
||||
[h / 6.0, d / max, max]
|
||||
}
|
||||
|
||||
/// Hue, saturation and value (0–1) to sRGB (components 0–1).
|
||||
pub fn hsv_to_rgb([h, s, v]: [f32; 3]) -> [f32; 3] {
|
||||
let h = h.clamp(0.0, 1.0) * 6.0;
|
||||
let (s, v) = (s.clamp(0.0, 1.0), v.clamp(0.0, 1.0));
|
||||
let f = |n: f32| {
|
||||
let k = (n + h) % 6.0;
|
||||
v - v * s * k.min(4.0 - k).clamp(0.0, 1.0)
|
||||
};
|
||||
[f(5.0), f(3.0), f(1.0)]
|
||||
}
|
||||
+409
-40
@@ -180,15 +180,66 @@ impl SplitSize {
|
||||
}
|
||||
}
|
||||
|
||||
/// One panel in a [`DockNode::Stack`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
/// One frame in a [`DockNode::Stack`]: a header with one tab per panel (a panel dropped onto a
|
||||
/// stacked panel joins its frame as a tab, as in After Effects).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(from = "StackEntryRepr")]
|
||||
pub struct StackEntry {
|
||||
pub panel: PanelKind,
|
||||
pub panels: Vec<PanelKind>,
|
||||
/// The shown tab.
|
||||
pub active: usize,
|
||||
pub open: bool,
|
||||
/// Content height when open (set by dragging the gaps); `None` = share the remaining height.
|
||||
pub height: Option<f32>,
|
||||
}
|
||||
|
||||
/// A saved [`StackEntry`]: workspaces saved before stacked frames held tabs name one `panel`.
|
||||
#[derive(Deserialize)]
|
||||
struct StackEntryRepr {
|
||||
#[serde(default)]
|
||||
panel: Option<PanelKind>,
|
||||
#[serde(default)]
|
||||
panels: Vec<PanelKind>,
|
||||
#[serde(default)]
|
||||
active: usize,
|
||||
open: bool,
|
||||
#[serde(default)]
|
||||
height: Option<f32>,
|
||||
}
|
||||
|
||||
impl From<StackEntryRepr> for StackEntry {
|
||||
fn from(r: StackEntryRepr) -> StackEntry {
|
||||
let mut panels = r.panels;
|
||||
if let Some(p) = r.panel
|
||||
&& !panels.contains(&p)
|
||||
{
|
||||
panels.insert(0, p);
|
||||
}
|
||||
let active = r.active.min(panels.len().saturating_sub(1));
|
||||
StackEntry { panels, active, open: r.open, height: r.height }
|
||||
}
|
||||
}
|
||||
|
||||
impl StackEntry {
|
||||
/// A frame showing just `panel`.
|
||||
pub fn new(panel: PanelKind, open: bool, height: Option<f32>) -> StackEntry {
|
||||
StackEntry { panels: vec![panel], active: 0, open, height }
|
||||
}
|
||||
pub fn contains(&self, p: PanelKind) -> bool {
|
||||
self.panels.contains(&p)
|
||||
}
|
||||
/// The frame's shown panel.
|
||||
pub fn shown(&self) -> Option<PanelKind> {
|
||||
self.panels.get(self.active).or(self.panels.first()).copied()
|
||||
}
|
||||
/// Show `p` (one of its tabs).
|
||||
fn show(&mut self, p: PanelKind) {
|
||||
if let Some(i) = self.panels.iter().position(|x| *x == p) {
|
||||
self.active = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum DockNode {
|
||||
/// `vertical`: children stacked top/bottom; else side by side.
|
||||
@@ -214,7 +265,7 @@ fn tabs(p: &[PanelKind], active: usize) -> DockNode {
|
||||
DockNode::Tabs { panels: p.to_vec(), active }
|
||||
}
|
||||
fn stack(e: &[(PanelKind, bool, Option<f32>)]) -> DockNode {
|
||||
DockNode::Stack { entries: e.iter().map(|&(panel, open, height)| StackEntry { panel, open, height }).collect() }
|
||||
DockNode::Stack { entries: e.iter().map(|&(panel, open, height)| StackEntry::new(panel, open, height)).collect() }
|
||||
}
|
||||
fn hsplit(size: SplitSize, a: DockNode, b: DockNode) -> DockNode {
|
||||
DockNode::Split { vertical: false, size, a: Box::new(a), b: Box::new(b) }
|
||||
@@ -413,7 +464,7 @@ impl DockNode {
|
||||
b.panels(out);
|
||||
}
|
||||
DockNode::Tabs { panels, .. } => out.extend(panels.iter().copied()),
|
||||
DockNode::Stack { entries } => out.extend(entries.iter().map(|e| e.panel)),
|
||||
DockNode::Stack { entries } => out.extend(entries.iter().flat_map(|e| e.panels.iter().copied())),
|
||||
}
|
||||
}
|
||||
pub fn contains(&self, p: PanelKind) -> bool {
|
||||
@@ -423,49 +474,139 @@ impl DockNode {
|
||||
}
|
||||
/// Make `p` the active tab of its group. Returns false if not present.
|
||||
pub fn activate(&mut self, p: PanelKind) -> bool {
|
||||
crate::dock_shared::apply_tree(self, craft_ui::docking::Action::Activate { panel: p })
|
||||
}
|
||||
/// Expand or collapse a stacked panel. Returns false if `p` is not in a stack.
|
||||
pub fn toggle_stacked(&mut self, p: PanelKind) -> bool {
|
||||
if crate::dock_shared::encode(self, &[]).is_err() {
|
||||
if !crate::dock_shared::valid_tree(self) {
|
||||
return false;
|
||||
}
|
||||
let open = !self.is_visible(p);
|
||||
crate::dock_shared::apply_tree(self, craft_ui::docking::Action::SetStackOpen { panel: p, open })
|
||||
match self {
|
||||
DockNode::Split { a, b, .. } => a.activate(p) || b.activate(p),
|
||||
DockNode::Tabs { panels, active } => {
|
||||
if let Some(i) = panels.iter().position(|x| *x == p) {
|
||||
*active = i;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
DockNode::Stack { entries } => match entries.iter_mut().find(|e| e.contains(p)) {
|
||||
Some(e) => {
|
||||
e.show(p);
|
||||
e.open = true;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
},
|
||||
}
|
||||
}
|
||||
/// Expand or collapse a stacked panel's frame (showing `p`). Returns false if `p` is not in
|
||||
/// a stack.
|
||||
pub fn toggle_stacked(&mut self, p: PanelKind) -> bool {
|
||||
if !crate::dock_shared::valid_tree(self) {
|
||||
return false;
|
||||
}
|
||||
match self {
|
||||
DockNode::Split { a, b, .. } => a.toggle_stacked(p) || b.toggle_stacked(p),
|
||||
DockNode::Tabs { .. } => false,
|
||||
DockNode::Stack { entries } => match entries.iter_mut().find(|e| e.contains(p)) {
|
||||
Some(e) => {
|
||||
e.show(p);
|
||||
e.open = !e.open;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_visible(&self, p: PanelKind) -> bool {
|
||||
match self {
|
||||
DockNode::Split { a, b, .. } => a.is_visible(p) || b.is_visible(p),
|
||||
DockNode::Tabs { panels, active } => panels.get(*active) == Some(&p),
|
||||
DockNode::Stack { entries } => entries.iter().any(|e| e.panel == p && e.open),
|
||||
DockNode::Stack { entries } => entries.iter().any(|e| e.open && e.shown() == Some(p)),
|
||||
}
|
||||
}
|
||||
/// Close a panel (remove its tab; empty groups collapse their split).
|
||||
pub fn close(&mut self, p: PanelKind) {
|
||||
crate::dock_shared::close_tree(self, p);
|
||||
if !crate::dock_shared::valid_for_close(self) {
|
||||
return;
|
||||
}
|
||||
if let DockNode::Split { a, b, .. } = self {
|
||||
a.close(p);
|
||||
b.close(p);
|
||||
let empty = |n: &DockNode| match n {
|
||||
DockNode::Tabs { panels, .. } => panels.is_empty(),
|
||||
DockNode::Stack { entries } => entries.is_empty(),
|
||||
DockNode::Split { .. } => false,
|
||||
};
|
||||
if empty(a) {
|
||||
*self = (**b).clone();
|
||||
} else if empty(b) {
|
||||
*self = (**a).clone();
|
||||
}
|
||||
} else if let DockNode::Tabs { panels, active } = self {
|
||||
let shown = panels.get(*active).copied();
|
||||
panels.retain(|x| *x != p);
|
||||
*active = shown.and_then(|shown| panels.iter().position(|x| *x == shown)).unwrap_or((*active).min(panels.len().saturating_sub(1)));
|
||||
} else if let DockNode::Stack { entries } = self {
|
||||
for e in entries.iter_mut() {
|
||||
let shown = e.shown();
|
||||
e.panels.retain(|x| *x != p);
|
||||
e.active = shown.and_then(|shown| e.panels.iter().position(|x| *x == shown)).unwrap_or(e.active.min(e.panels.len().saturating_sub(1)));
|
||||
}
|
||||
entries.retain(|e| !e.panels.is_empty());
|
||||
}
|
||||
}
|
||||
/// Add a panel as a tab next to `near` (or into the first group).
|
||||
pub fn open_near(&mut self, p: PanelKind, near: PanelKind) {
|
||||
if crate::dock_shared::encode(self, &[]).is_err() {
|
||||
if !crate::dock_shared::valid_tree(self) {
|
||||
return;
|
||||
}
|
||||
let anchor = [near, PanelKind::EffectsPresets, PanelKind::Project].into_iter().find(|panel| self.contains(*panel));
|
||||
fn in_stack(node: &DockNode, panel: PanelKind) -> bool {
|
||||
match node {
|
||||
DockNode::Split { a, b, .. } => in_stack(a, panel) || in_stack(b, panel),
|
||||
DockNode::Stack { entries } => entries.iter().any(|entry| entry.panel == panel),
|
||||
DockNode::Tabs { .. } => false,
|
||||
if self.contains(p) {
|
||||
self.activate(p);
|
||||
return;
|
||||
}
|
||||
fn add(n: &mut DockNode, p: PanelKind, near: PanelKind) -> bool {
|
||||
match n {
|
||||
DockNode::Split { a, b, .. } => add(a, p, near) || add(b, p, near),
|
||||
DockNode::Tabs { panels, active } => {
|
||||
if panels.contains(&near) {
|
||||
panels.push(p);
|
||||
*active = panels.len() - 1;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
DockNode::Stack { entries } => match entries.iter().position(|e| e.contains(near)) {
|
||||
Some(i) => {
|
||||
entries.insert(i + 1, StackEntry::new(p, true, None));
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
},
|
||||
}
|
||||
}
|
||||
// Accordion entries open immediately after their anchor; ordinary tab groups append.
|
||||
let action = match anchor {
|
||||
Some(anchor) if !self.contains(p) && in_stack(self, anchor) => {
|
||||
craft_ui::docking::Action::OpenAt { panel: p, anchor, placement: craft_ui::docking::Placement::Split(craft_ui::docking::Zone::Center) }
|
||||
fn add_first(n: &mut DockNode, p: PanelKind) -> bool {
|
||||
match n {
|
||||
DockNode::Split { a, b, .. } => add_first(a, p) || add_first(b, p),
|
||||
DockNode::Tabs { panels, active } if !panels.is_empty() => {
|
||||
panels.push(p);
|
||||
*active = panels.len() - 1;
|
||||
true
|
||||
}
|
||||
DockNode::Stack { entries } if !entries.is_empty() => {
|
||||
entries.push(StackEntry::new(p, true, None));
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
_ => craft_ui::docking::Action::Open { panel: p, anchor },
|
||||
};
|
||||
crate::dock_shared::apply_tree(self, action);
|
||||
}
|
||||
if self.panel_count() == 0 {
|
||||
// Every panel was closed: there is no anchor, so the panel becomes the whole dock.
|
||||
*self = tabs(&[p], 0);
|
||||
} else if !add(self, p, near) && !add(self, p, PanelKind::EffectsPresets) && !add(self, p, PanelKind::Project) {
|
||||
// None of the anchors is docked (e.g. Minimal with Timeline closed): use the first group.
|
||||
add_first(self, p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -531,16 +672,99 @@ pub struct Floating {
|
||||
|
||||
impl DockNode {
|
||||
/// Insert panel `p` relative to the group that holds `anchor`: as a tab next to it
|
||||
/// (Center) or in a new group split off to one side. `p` is removed from its old place
|
||||
/// first. Returns false (tree unchanged) if `anchor` isn't docked or is `p` itself alone.
|
||||
/// (Center) or in a new group split off to one side. In a stack, the group is `anchor`'s
|
||||
/// frame: Center adds a tab to that frame and Top / Bottom add a frame above or below it
|
||||
/// (#302); Left / Right split the column. `p` is removed from its old place first. Returns
|
||||
/// false (tree unchanged) if `anchor` isn't docked or is `p` itself alone.
|
||||
pub fn dock_panel(&mut self, p: PanelKind, anchor: PanelKind, zone: Zone) -> bool {
|
||||
crate::dock_shared::move_in_tree(self, p, anchor, craft_ui::docking::Placement::Split(zone.shared()))
|
||||
if !crate::dock_shared::valid_tree(self) || p == anchor || !self.contains(anchor) {
|
||||
return false;
|
||||
}
|
||||
let before = self.clone();
|
||||
self.close(p);
|
||||
fn rec(n: &mut DockNode, p: PanelKind, anchor: PanelKind, zone: Zone) -> bool {
|
||||
let here = match n {
|
||||
DockNode::Split { a, b, .. } => return rec(a, p, anchor, zone) || rec(b, p, anchor, zone),
|
||||
DockNode::Tabs { panels, .. } => panels.contains(&anchor),
|
||||
DockNode::Stack { entries } => entries.iter().any(|e| e.contains(anchor)),
|
||||
};
|
||||
if !here {
|
||||
return false;
|
||||
}
|
||||
match (zone, &mut *n) {
|
||||
(Zone::Center, DockNode::Tabs { panels, active }) => {
|
||||
let i = panels.iter().position(|x| *x == anchor).map_or(panels.len(), |i| i + 1);
|
||||
panels.insert(i, p);
|
||||
*active = i;
|
||||
}
|
||||
(Zone::Center, DockNode::Stack { entries }) => {
|
||||
let Some(e) = entries.iter_mut().find(|e| e.contains(anchor)) else { return false };
|
||||
let i = e.panels.iter().position(|x| *x == anchor).map_or(e.panels.len(), |i| i + 1);
|
||||
e.panels.insert(i, p);
|
||||
e.active = i;
|
||||
e.open = true;
|
||||
}
|
||||
(Zone::Top | Zone::Bottom, DockNode::Stack { entries }) => {
|
||||
let Some(i) = entries.iter().position(|e| e.contains(anchor)) else { return false };
|
||||
let at = if zone == Zone::Top { i } else { i + 1 };
|
||||
entries.insert(at, StackEntry::new(p, true, None));
|
||||
}
|
||||
(z, node) => {
|
||||
let new = tabs(&[p], 0);
|
||||
let old = std::mem::replace(node, tabs(&[], 0));
|
||||
let vertical = matches!(z, Zone::Top | Zone::Bottom);
|
||||
let (a, b) = if matches!(z, Zone::Left | Zone::Top) { (new, old) } else { (old, new) };
|
||||
*node = DockNode::Split { vertical, size: SplitSize::Ratio(0.5), a: Box::new(a), b: Box::new(b) };
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
if rec(self, p, anchor, zone) {
|
||||
true
|
||||
} else {
|
||||
*self = before;
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Move panel `p` into the group that holds `anchor` as a tab before `before` (one of that
|
||||
/// group's panels) or last, and show it. False (tree unchanged) if `anchor` isn't docked.
|
||||
pub fn insert_tab(&mut self, p: PanelKind, anchor: PanelKind, before: Option<PanelKind>) -> bool {
|
||||
crate::dock_shared::move_in_tree(self, p, anchor, craft_ui::docking::Placement::Tab { before })
|
||||
if !crate::dock_shared::valid_tree(self) {
|
||||
return false;
|
||||
}
|
||||
if p == anchor || !self.contains(anchor) {
|
||||
return false;
|
||||
}
|
||||
let saved = self.clone();
|
||||
self.close(p);
|
||||
fn rec(n: &mut DockNode, p: PanelKind, anchor: PanelKind, before: Option<PanelKind>) -> bool {
|
||||
match n {
|
||||
DockNode::Split { a, b, .. } => rec(a, p, anchor, before) || rec(b, p, anchor, before),
|
||||
DockNode::Tabs { panels, active } if panels.contains(&anchor) => {
|
||||
let i = before.and_then(|b| panels.iter().position(|x| *x == b)).unwrap_or(panels.len());
|
||||
panels.insert(i, p);
|
||||
*active = i;
|
||||
true
|
||||
}
|
||||
DockNode::Stack { entries } => {
|
||||
// A tab of the anchor's frame.
|
||||
let Some(e) = entries.iter_mut().find(|e| e.contains(anchor)) else { return false };
|
||||
let i = before.and_then(|b| e.panels.iter().position(|x| *x == b)).unwrap_or(e.panels.len());
|
||||
e.panels.insert(i, p);
|
||||
e.active = i;
|
||||
e.open = true;
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
if rec(self, p, anchor, before) {
|
||||
true
|
||||
} else {
|
||||
*self = saved;
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Path of the group containing `p` (as in [`Group::path`]; stacks add `sN`).
|
||||
@@ -549,7 +773,7 @@ impl DockNode {
|
||||
match n {
|
||||
DockNode::Split { a, b, .. } => rec(a, p, &format!("{path}a")).or_else(|| rec(b, p, &format!("{path}b"))),
|
||||
DockNode::Tabs { panels, .. } => panels.contains(&p).then(|| path.to_string()),
|
||||
DockNode::Stack { entries } => entries.iter().position(|e| e.panel == p).map(|i| format!("{path}s{i}")),
|
||||
DockNode::Stack { entries } => entries.iter().position(|e| e.contains(p)).map(|i| format!("{path}s{i}")),
|
||||
}
|
||||
}
|
||||
rec(self, p, "")
|
||||
@@ -598,11 +822,17 @@ impl Layout {
|
||||
|
||||
/// Move or reorder a docked/floating tab through the shared transaction.
|
||||
pub fn insert_tab(&mut self, p: PanelKind, anchor: PanelKind, before: Option<PanelKind>) -> bool {
|
||||
if !crate::dock_shared::valid_tree(&self.root) {
|
||||
return false;
|
||||
}
|
||||
self.apply(craft_ui::docking::Action::Move { panel: p, anchor, placement: craft_ui::docking::Placement::Tab { before } }).is_ok()
|
||||
}
|
||||
|
||||
/// Dock a panel beside an anchor; floating destinations accept tabs only.
|
||||
pub fn dock(&mut self, p: PanelKind, anchor: PanelKind, zone: Zone) -> bool {
|
||||
if !crate::dock_shared::valid_tree(&self.root) {
|
||||
return false;
|
||||
}
|
||||
self.apply(craft_ui::docking::Action::Move { panel: p, anchor, placement: craft_ui::docking::Placement::Split(zone.shared()) }).is_ok()
|
||||
}
|
||||
|
||||
@@ -741,15 +971,17 @@ fn layout_inner(
|
||||
drag = Some((above, below, d));
|
||||
}
|
||||
}
|
||||
out.push(Group { path: group, rect: r, content, panels: vec![e.panel], active: 0, stacked: Some(e.open) });
|
||||
out.push(Group { path: group, rect: r, content, panels: e.panels.clone(), active: e.active, stacked: Some(e.open) });
|
||||
y = r.max.y + g;
|
||||
}
|
||||
if let Some((above, below, d)) = drag {
|
||||
let mut proposed = entries.clone();
|
||||
resize_stacked(&mut proposed, &bodies, above, below, d);
|
||||
for (before, after) in entries.iter().zip(proposed) {
|
||||
if before.height != after.height {
|
||||
actions.push(craft_ui::docking::Action::ResizeStack { panel: after.panel, height: after.height });
|
||||
if before.height != after.height
|
||||
&& let Some(panel) = after.shown()
|
||||
{
|
||||
actions.push(craft_ui::docking::Action::ResizeStack { panel, height: after.height });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -830,6 +1062,29 @@ fn stack_bodies(entries: &[StackEntry], avail: f32) -> Vec<f32> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `v` held to `lo..=hi`, never panicking: when the room is too small for both minimums
|
||||
/// (`hi < lo`), `lo` wins; a non-finite `v` gives `lo`.
|
||||
#[cfg(test)]
|
||||
fn clamp_ordered(v: f32, lo: f32, hi: f32) -> f32 {
|
||||
let lo = if lo.is_finite() { lo } else { 0.0 };
|
||||
let hi = if hi.is_finite() { hi.max(lo) } else { lo };
|
||||
if v.is_finite() { v.max(lo).min(hi) } else { lo }
|
||||
}
|
||||
|
||||
/// The size of a split's first side in `avail` points (both sides keep 20 pt when there is room).
|
||||
/// `f32::clamp` panics when its bounds cross, which a split shorter than 40 pt did (#306).
|
||||
#[cfg(test)]
|
||||
fn split_first(size: SplitSize, avail: f32) -> f32 {
|
||||
let avail = if avail.is_finite() { avail.max(0.0) } else { 0.0 };
|
||||
let first = match size {
|
||||
SplitSize::Ratio(r) => avail * r,
|
||||
SplitSize::FixedA(px) => px.min(avail - 20.0),
|
||||
SplitSize::FixedB(px) => avail - px.min(avail - 20.0),
|
||||
};
|
||||
let lo = 20.0_f32.min(avail);
|
||||
clamp_ordered(first, lo, avail - 20.0).min(avail)
|
||||
}
|
||||
|
||||
/// Drag the gap between the open stacked panels `above` and `below` (laid out at `bodies`) by
|
||||
/// `d` points: one grows as much as the other shrinks, neither below [`STACK_MIN`]. The new sizes
|
||||
/// become the panels' heights, except that the last panel without one keeps sharing the rest
|
||||
@@ -1020,7 +1275,9 @@ pub fn draw_group_chrome(ui: &mut egui::Ui, g: &Group, t: &Tokens, reg: &mut cra
|
||||
}
|
||||
crate::widgets::focus_outline(ui, &resp, t);
|
||||
if resp.clicked() {
|
||||
if g.stacked.is_some() {
|
||||
// A stacked frame's shown tab expands / collapses it; another tab shows that
|
||||
// panel (expanding the frame).
|
||||
if g.stacked.is_some() && (k == ai || entries.len() == 1) {
|
||||
out.actions.push(DockAction::ToggleStacked(*p));
|
||||
} else {
|
||||
out.actions.push(activate(e));
|
||||
@@ -1032,6 +1289,21 @@ pub fn draw_group_chrome(ui: &mut egui::Ui, g: &Group, t: &Tokens, reg: &mut cra
|
||||
}
|
||||
x += w + 8.0;
|
||||
}
|
||||
// A stacked panel's whole header bar expands/collapses it, not just its name (as in After
|
||||
// Effects): the frame with its shown tab.
|
||||
if g.stacked.is_some()
|
||||
&& let Some(e) = entries.get(ai).or(entries.first())
|
||||
{
|
||||
let rest = Rect::from_min_max(pos2((x - 8.0).max(strip.min.x), strip.min.y), strip.max);
|
||||
if rest.width() > 0.0 {
|
||||
let resp = ui.interact(rest, egui::Id::new(("tab-rest", g.path.clone())), Sense::click());
|
||||
reg.add(&format!("panel.header.{}", e.panel.id()), rest, &e.label);
|
||||
if resp.clicked() {
|
||||
out.actions.push(DockAction::ToggleStacked(e.panel));
|
||||
out.actions.push(DockAction::Focus(e.panel));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// clicking anywhere in the panel focuses it
|
||||
if let Some(p) = active_panel
|
||||
@@ -1078,6 +1350,24 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_near_in_an_empty_dock_makes_the_panel_the_dock() {
|
||||
for p in [PanelKind::Composition, PanelKind::Timeline, PanelKind::Project] {
|
||||
let mut d = tabs(&[], 0);
|
||||
d.open_near(p, PanelKind::EffectsPresets);
|
||||
assert!(d.is_visible(p));
|
||||
assert_eq!(d.panel_count(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_near_without_any_anchor_uses_the_first_group() {
|
||||
let mut d = tabs(&[PanelKind::Composition], 0);
|
||||
d.open_near(PanelKind::Timeline, PanelKind::EffectsPresets);
|
||||
assert!(d.is_visible(PanelKind::Timeline));
|
||||
assert_eq!(d.panel_count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stacked_panels_toggle_open_close() {
|
||||
use PanelKind::*;
|
||||
@@ -1098,7 +1388,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn entry(panel: PanelKind, open: bool, height: Option<f32>) -> StackEntry {
|
||||
StackEntry { panel, open, height }
|
||||
StackEntry::new(panel, open, height)
|
||||
}
|
||||
|
||||
fn close_to(a: &[f32], b: &[f32]) -> bool {
|
||||
@@ -1225,6 +1515,38 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_splits_lay_out_without_panicking() {
|
||||
// #306: a split 0 < avail < 40 pt tall made `f32::clamp` panic (its bounds crossed).
|
||||
for avail in [0.0, 5.0, 19.0, 20.0, 30.0, 39.0, 40.0, 41.0, -10.0, f32::NAN, f32::INFINITY] {
|
||||
for size in [SplitSize::Ratio(0.5), SplitSize::Ratio(f32::NAN), SplitSize::FixedA(300.0), SplitSize::FixedB(300.0), SplitSize::FixedA(-5.0)] {
|
||||
let f = split_first(size, avail);
|
||||
assert!(f.is_finite() && f >= 0.0, "{size:?} {avail}: {f}");
|
||||
if avail.is_finite() && avail > 0.0 {
|
||||
assert!(f <= avail, "{size:?} {avail}: {f}");
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(split_first(SplitSize::FixedA(300.0), 30.0), 20.0);
|
||||
assert_eq!(split_first(SplitSize::Ratio(0.5), 200.0), 100.0);
|
||||
assert_eq!(clamp_ordered(5.0, 40.0, -4.0), 40.0);
|
||||
// Every workspace, laid out in rects too short and too narrow for its minimums.
|
||||
let ctx = egui::Context::default();
|
||||
let t = Tokens::for_kind(crate::theme::ThemeKind::Dark);
|
||||
for w in WORKSPACES {
|
||||
for (wd, ht) in [(30.0, 30.0), (800.0, 36.0), (800.0, 45.0), (36.0, 600.0), (1.0, 1.0), (0.0, 0.0)] {
|
||||
let mut node = workspace(w);
|
||||
let mut frame = ctx.run_ui(egui::RawInput::default(), |ui| {
|
||||
let mut out = vec![];
|
||||
let mut reg = crate::automation::Registry::default();
|
||||
layout(ui, &mut node, Rect::from_min_size(pos2(0.0, 0.0), vec2(wd, ht)), &t, "", &mut out, &mut reg);
|
||||
assert!(!out.is_empty(), "{w}");
|
||||
});
|
||||
frame.textures_delta.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_zone_math() {
|
||||
let r = Rect::from_min_size(pos2(100.0, 100.0), vec2(400.0, 300.0));
|
||||
@@ -1268,16 +1590,42 @@ mod tests {
|
||||
assert!(!d.dock_panel(Audio, Audio, Zone::Left));
|
||||
assert!(!d.dock_panel(Audio, Tracker, Zone::Left));
|
||||
assert_eq!(d, before);
|
||||
// Into a stack.
|
||||
// Into a stack: a tab of the anchor's frame (#302).
|
||||
let mut s = workspace("Default");
|
||||
let props = s.path_of(Properties).unwrap();
|
||||
assert!(s.dock_panel(Tracker, Properties, Zone::Center));
|
||||
assert!(s.path_of(Tracker).unwrap().contains('s'));
|
||||
assert_eq!(s.path_of(Tracker), Some(props.clone()));
|
||||
assert!(s.is_visible(Tracker) && !s.is_visible(Properties));
|
||||
assert!(s.activate(Properties) && s.is_visible(Properties));
|
||||
// Top / Bottom: a frame of its own above / below the anchor's, not a split column.
|
||||
assert!(s.dock_panel(Info, Properties, Zone::Bottom));
|
||||
let below = s.path_of(Info).unwrap();
|
||||
assert_ne!(below, props);
|
||||
assert_eq!(s.path_of(Properties), Some(props.clone()));
|
||||
assert!(s.dock_panel(Info, Properties, Zone::Top));
|
||||
assert_eq!(s.path_of(Info), Some(props.clone()), "above Properties: its frame's index");
|
||||
// Closing a tab keeps the frame; closing the frame's last tab removes it.
|
||||
s.close(Tracker);
|
||||
assert!(s.contains(Properties) && !s.contains(Tracker));
|
||||
// A tab dragged onto a stacked frame's tab strip joins that frame.
|
||||
let mut t = workspace("Default");
|
||||
assert!(t.insert_tab(Info, Preview, None));
|
||||
assert_eq!(t.path_of(Info), t.path_of(Preview));
|
||||
// Moving the only panel of a group collapses its split.
|
||||
let mut m = hsplit(SplitSize::Ratio(0.5), tabs(&[Project], 0), tabs(&[Composition], 0));
|
||||
assert!(m.dock_panel(Project, Composition, Zone::Center));
|
||||
assert_eq!(m, tabs(&[Composition, Project], 1));
|
||||
}
|
||||
|
||||
/// #302: workspaces saved when each stacked frame held one `panel` still load.
|
||||
#[test]
|
||||
fn old_stack_entries_load() {
|
||||
let e: StackEntry = serde_json::from_str(r#"{"panel":"Preview","open":true,"height":46.0}"#).unwrap();
|
||||
assert_eq!(e, StackEntry::new(PanelKind::Preview, true, Some(46.0)));
|
||||
let s = serde_json::to_string(&workspace("Default")).unwrap();
|
||||
assert_eq!(serde_json::from_str::<DockNode>(&s).unwrap(), workspace("Default"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn floating_layout_round_trips() {
|
||||
use PanelKind::*;
|
||||
@@ -1316,6 +1664,27 @@ mod tests {
|
||||
assert_eq!(PanelKind::from_name("effects & presets"), Some(PanelKind::EffectsPresets));
|
||||
}
|
||||
|
||||
/// Ported from #630 (Ni-zav): the reporter's reproduction on the Minimal workspace.
|
||||
#[test]
|
||||
fn window_panels_reopen_after_last_panel_is_closed() {
|
||||
use PanelKind::*;
|
||||
for reopen in [Composition, Timeline, Project] {
|
||||
let mut d = workspace("Minimal");
|
||||
d.close(Composition);
|
||||
d.close(Timeline);
|
||||
assert_eq!(d.panel_count(), 0);
|
||||
d.open_near(reopen, EffectsPresets);
|
||||
assert_eq!(d.panel_count(), 1);
|
||||
assert!(d.is_visible(reopen), "{reopen:?} must be visible");
|
||||
}
|
||||
let mut d = tabs(&[Audio], 0);
|
||||
d.open_near(History, Project);
|
||||
assert_eq!(d, tabs(&[Audio, History], 1));
|
||||
let mut d = workspace("Minimal");
|
||||
d.open_near(EffectsPresets, Timeline);
|
||||
assert_eq!(d.path_of(EffectsPresets), d.path_of(Timeline));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_earlier_inactive_tab_keeps_the_shown_panel() {
|
||||
use PanelKind::*;
|
||||
|
||||
@@ -25,7 +25,15 @@ fn encode_node(node: &DockNode, depth: usize, count: &mut usize) -> Result<Node<
|
||||
if entries.len() > MAX_PANELS {
|
||||
return Err("too many workspace stack entries".into());
|
||||
}
|
||||
Node::Stack { entries: entries.iter().map(|entry| SharedStackEntry { panel: entry.panel, open: entry.open, height: entry.height }).collect() }
|
||||
if entries.iter().any(|entry| entry.panels.is_empty() || entry.active >= entry.panels.len() || entry.panels.len() > MAX_PANELS) {
|
||||
return Err("invalid stacked tab selection".into());
|
||||
}
|
||||
Node::Stack {
|
||||
entries: entries
|
||||
.iter()
|
||||
.flat_map(|entry| entry.panels.iter().map(move |panel| SharedStackEntry { panel: *panel, open: entry.open, height: entry.height }))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
DockNode::Split { vertical, size, a, b } => Node::Split {
|
||||
axis: if *vertical { SplitAxis::Vertical } else { SplitAxis::Horizontal },
|
||||
@@ -44,7 +52,7 @@ fn decode_node(node: Node<PanelKind>) -> DockNode {
|
||||
match node {
|
||||
Node::Tabs { panels, active } => DockNode::Tabs { panels, active },
|
||||
Node::Stack { entries } => {
|
||||
DockNode::Stack { entries: entries.into_iter().map(|entry| StackEntry { panel: entry.panel, open: entry.open, height: entry.height }).collect() }
|
||||
DockNode::Stack { entries: entries.into_iter().map(|entry| StackEntry::new(entry.panel, entry.open, entry.height)).collect() }
|
||||
}
|
||||
Node::Split { axis, size, first, second } => DockNode::Split {
|
||||
vertical: axis == SplitAxis::Vertical,
|
||||
@@ -77,75 +85,174 @@ pub(crate) fn decode(layout: SharedLayout<PanelKind>) -> Layout {
|
||||
}
|
||||
}
|
||||
|
||||
/// Restore app-owned accordion tab frames after shared validation/transactions.
|
||||
/// The shared model represents individual stack panels; grouping stays in the persisted app schema.
|
||||
fn restore_frames(node: &mut DockNode, original: &DockNode) {
|
||||
fn collect(node: &DockNode, out: &mut Vec<StackEntry>) {
|
||||
match node {
|
||||
DockNode::Split { a, b, .. } => {
|
||||
collect(a, out);
|
||||
collect(b, out);
|
||||
}
|
||||
DockNode::Stack { entries } => out.extend(entries.iter().cloned()),
|
||||
DockNode::Tabs { .. } => {}
|
||||
}
|
||||
}
|
||||
fn restore(node: &mut DockNode, frames: &[StackEntry]) {
|
||||
match node {
|
||||
DockNode::Split { a, b, .. } => {
|
||||
restore(a, frames);
|
||||
restore(b, frames);
|
||||
}
|
||||
DockNode::Stack { entries } => {
|
||||
let mut result: Vec<StackEntry> = Vec::new();
|
||||
for entry in std::mem::take(entries) {
|
||||
let Some(panel) = entry.shown() else { continue };
|
||||
let old = frames.iter().find(|frame| frame.contains(panel));
|
||||
if let Some(last) = result.last_mut()
|
||||
&& old.is_some_and(|frame| last.panels.iter().all(|p| frame.contains(*p)))
|
||||
{
|
||||
last.panels.push(panel);
|
||||
if old.and_then(StackEntry::shown) == Some(panel) {
|
||||
last.active = last.panels.len().saturating_sub(1);
|
||||
}
|
||||
} else {
|
||||
result.push(entry);
|
||||
}
|
||||
}
|
||||
for entry in &mut result {
|
||||
if let Some(old) = frames.iter().find(|frame| entry.panels.iter().all(|panel| frame.contains(*panel))) {
|
||||
entry.active = old
|
||||
.shown()
|
||||
.and_then(|shown| entry.panels.iter().position(|panel| *panel == shown))
|
||||
.unwrap_or(old.active.min(entry.panels.len().saturating_sub(1)));
|
||||
}
|
||||
}
|
||||
*entries = result;
|
||||
}
|
||||
DockNode::Tabs { .. } => {}
|
||||
}
|
||||
}
|
||||
let mut frames = Vec::new();
|
||||
collect(original, &mut frames);
|
||||
restore(node, &frames);
|
||||
}
|
||||
|
||||
pub(crate) fn apply(layout: &mut Layout, action: Action<PanelKind>) -> Result<(), String> {
|
||||
let mut shared = encode(&layout.root, &layout.floating)?;
|
||||
shared.apply(action).map_err(|error| error.to_string())?;
|
||||
let proposed = decode(shared);
|
||||
encode(&proposed.root, &proposed.floating)?;
|
||||
// Validate the same shared command first. Native stack insertion then retains tabs inside
|
||||
// their accordion frame, including the existing before/after insertion policy.
|
||||
shared.apply(action.clone()).map_err(|error| error.to_string())?;
|
||||
let mut proposed = decode(shared);
|
||||
restore_frames(&mut proposed.root, &layout.root);
|
||||
match action {
|
||||
Action::Move { panel, anchor, placement } | Action::OpenAt { panel, anchor, placement } if layout.root.contains(anchor) => {
|
||||
fn stacked(node: &DockNode, p: PanelKind) -> bool {
|
||||
match node {
|
||||
DockNode::Split { a, b, .. } => stacked(a, p) || stacked(b, p),
|
||||
DockNode::Stack { entries } => entries.iter().any(|e| e.contains(p)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
if stacked(&layout.root, anchor) {
|
||||
let mut native = layout.clone();
|
||||
native.unfloat(panel);
|
||||
let applied = match placement {
|
||||
Placement::Tab { before } => native.root.insert_tab(panel, anchor, before),
|
||||
Placement::Split(zone) => native.root.dock_panel(
|
||||
panel,
|
||||
anchor,
|
||||
match zone {
|
||||
craft_ui::docking::Zone::Left => crate::dock::Zone::Left,
|
||||
craft_ui::docking::Zone::Right => crate::dock::Zone::Right,
|
||||
craft_ui::docking::Zone::Top => crate::dock::Zone::Top,
|
||||
craft_ui::docking::Zone::Bottom => crate::dock::Zone::Bottom,
|
||||
craft_ui::docking::Zone::Center => crate::dock::Zone::Center,
|
||||
},
|
||||
),
|
||||
};
|
||||
if !applied {
|
||||
return Err("stacked panel move failed".into());
|
||||
}
|
||||
proposed = native;
|
||||
}
|
||||
}
|
||||
Action::Activate { panel } => {
|
||||
proposed.root.activate(panel);
|
||||
}
|
||||
Action::SetStackOpen { panel, open } => {
|
||||
fn set(node: &mut DockNode, p: PanelKind, open: bool) {
|
||||
match node {
|
||||
DockNode::Split { a, b, .. } => {
|
||||
set(a, p, open);
|
||||
set(b, p, open);
|
||||
}
|
||||
DockNode::Stack { entries } => {
|
||||
if let Some(e) = entries.iter_mut().find(|e| e.contains(p)) {
|
||||
e.open = open;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
set(&mut proposed.root, panel, open);
|
||||
}
|
||||
Action::ResizeStack { panel, height } => {
|
||||
fn set(node: &mut DockNode, p: PanelKind, h: Option<f32>) {
|
||||
match node {
|
||||
DockNode::Split { a, b, .. } => {
|
||||
set(a, p, h);
|
||||
set(b, p, h);
|
||||
}
|
||||
DockNode::Stack { entries } => {
|
||||
if let Some(e) = entries.iter_mut().find(|e| e.contains(p)) {
|
||||
e.height = h;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
set(&mut proposed.root, panel, height);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
encode(&proposed.root, &proposed.floating)?.validate().map_err(|error| error.to_string())?;
|
||||
*layout = proposed;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn apply_tree(root: &mut DockNode, action: Action<PanelKind>) -> bool {
|
||||
let Ok(mut shared) = encode(root, &[]) else { return false };
|
||||
if shared.apply(action).is_err() {
|
||||
if !valid_tree(root) {
|
||||
return false;
|
||||
}
|
||||
let proposed = decode(shared).root;
|
||||
if encode(&proposed, &[]).is_err() {
|
||||
let mut layout = Layout { root: root.clone(), floating: vec![] };
|
||||
if apply(&mut layout, action).is_err() {
|
||||
return false;
|
||||
}
|
||||
*root = proposed;
|
||||
*root = layout.root;
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn move_in_tree(root: &mut DockNode, panel: PanelKind, anchor: PanelKind, placement: Placement<PanelKind>) -> bool {
|
||||
let Ok(mut shared) = encode(root, &[]) else { return false };
|
||||
if panel == anchor || !root.contains(anchor) {
|
||||
return false;
|
||||
}
|
||||
// This legacy entry point also opens new viewer/ScriptUI panels. Keep that explicit,
|
||||
// separate from Move, and commit only once both shared transactions have succeeded.
|
||||
if !root.contains(panel) && shared.apply(Action::Open { panel, anchor: Some(anchor) }).is_err() {
|
||||
return false;
|
||||
}
|
||||
if shared.apply(Action::Move { panel, anchor, placement }).is_err() {
|
||||
return false;
|
||||
}
|
||||
let proposed = decode(shared).root;
|
||||
if encode(&proposed, &[]).is_err() {
|
||||
return false;
|
||||
}
|
||||
*root = proposed;
|
||||
true
|
||||
pub(crate) fn valid_tree(root: &DockNode) -> bool {
|
||||
encode(root, &[]).is_ok_and(|shared| shared.validate().is_ok())
|
||||
}
|
||||
|
||||
// Legacy close methods repair selection indices. Do that on a bounded encoded copy,
|
||||
// then retain shared validation for geometry, duplicates and all other invariants.
|
||||
fn normalize_selection(node: &mut Node<PanelKind>) {
|
||||
match node {
|
||||
Node::Tabs { panels, active } => *active = (*active).min(panels.len().saturating_sub(1)),
|
||||
Node::Split { first, second, .. } => {
|
||||
normalize_selection(first);
|
||||
normalize_selection(second);
|
||||
pub(crate) fn valid_for_close(root: &DockNode) -> bool {
|
||||
fn normalize(node: &mut Node<PanelKind>) {
|
||||
match node {
|
||||
Node::Tabs { panels, active } => *active = (*active).min(panels.len().saturating_sub(1)),
|
||||
Node::Split { first, second, .. } => {
|
||||
normalize(first);
|
||||
normalize(second);
|
||||
}
|
||||
Node::Stack { .. } => {}
|
||||
}
|
||||
Node::Stack { .. } => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn close_tree(root: &mut DockNode, panel: PanelKind) {
|
||||
let Ok(mut shared) = encode(root, &[]) else { return };
|
||||
if let Some(node) = &mut shared.root {
|
||||
normalize_selection(node);
|
||||
let Ok(mut shared) = encode(root, &[]) else { return false };
|
||||
if let Some(root) = &mut shared.root {
|
||||
normalize(root);
|
||||
}
|
||||
if shared.validate().is_err() {
|
||||
return;
|
||||
}
|
||||
// An absent close still repairs an invalid selection, as the legacy method did.
|
||||
if root.contains(panel) && shared.apply(Action::Close { panel }).is_err() {
|
||||
return;
|
||||
}
|
||||
*root = decode(shared).root;
|
||||
shared.validate().is_ok()
|
||||
}
|
||||
|
||||
pub(crate) fn unfloat(layout: &mut Layout, panel: PanelKind) -> bool {
|
||||
@@ -160,6 +267,46 @@ pub(crate) fn unfloat(layout: &mut Layout, panel: PanelKind) -> bool {
|
||||
if !found || shared.apply(Action::Close { panel }).is_err() {
|
||||
return false;
|
||||
}
|
||||
*layout = decode(shared);
|
||||
let mut proposed = decode(shared);
|
||||
restore_frames(&mut proposed.root, &layout.root);
|
||||
*layout = proposed;
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod stacked_frame_tests {
|
||||
use super::*;
|
||||
use crate::dock::Zone;
|
||||
#[test]
|
||||
fn stacked_tabs_survive_shared_resize_activate_float_and_close() {
|
||||
let mut root = crate::dock::workspace("Default");
|
||||
assert!(root.dock_panel(PanelKind::Info, PanelKind::Properties, Zone::Center));
|
||||
fn group(node: &DockNode) -> Option<&StackEntry> {
|
||||
match node {
|
||||
DockNode::Split { a, b, .. } => group(a).or_else(|| group(b)),
|
||||
DockNode::Stack { entries } => entries.iter().find(|e| e.contains(PanelKind::Properties)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
let before = group(&root).unwrap().clone();
|
||||
assert!(before.contains(PanelKind::Info));
|
||||
let mut layout = Layout { root, floating: vec![] };
|
||||
layout.apply(Action::ResizeSplit { path: vec![], size: SharedSplitSize::Ratio(0.6) }).unwrap();
|
||||
assert_eq!(group(&layout.root).unwrap(), &before);
|
||||
layout.apply(Action::Activate { panel: PanelKind::Properties }).unwrap();
|
||||
assert_eq!(group(&layout.root).unwrap().shown(), Some(PanelKind::Properties));
|
||||
let original_frame = group(&layout.root).unwrap().clone();
|
||||
layout.apply(Action::OpenAt { panel: PanelKind::History, anchor: PanelKind::Properties, placement: Placement::Tab { before: None } }).unwrap();
|
||||
let opened = group(&layout.root).unwrap();
|
||||
assert!(opened.contains(PanelKind::History));
|
||||
assert!(opened.contains(PanelKind::Info));
|
||||
assert_eq!(opened.shown(), Some(PanelKind::History));
|
||||
assert_eq!(opened.height, original_frame.height);
|
||||
layout.apply(Action::Close { panel: PanelKind::History }).unwrap();
|
||||
layout.apply(Action::Float { panel: PanelKind::Info, rect: [20.0, 20.0, 300.0, 300.0] }).unwrap();
|
||||
assert_eq!(group(&layout.root).unwrap().panels, vec![PanelKind::Properties]);
|
||||
layout.apply(Action::Close { panel: PanelKind::Info }).unwrap();
|
||||
assert!(layout.floating.is_empty());
|
||||
assert_eq!(group(&layout.root).unwrap().panels, vec![PanelKind::Properties]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,7 +118,7 @@ impl EffectcraftApp {
|
||||
if shared.validate().is_err() {
|
||||
return false;
|
||||
}
|
||||
let mut l = crate::dock_shared::decode(shared);
|
||||
let mut l = Layout { root: self.ui.dock.clone(), floating: self.ui.floating.clone() };
|
||||
if !f(&mut l) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -280,8 +280,11 @@ fn comp_content_with(project: &Project, comp: ItemId, addr: impl Fn(ItemId, &Arc
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// Hash of render options (part of [`FrameKey`] and of the disk key).
|
||||
/// Hash of render options (part of [`FrameKey`] and of the disk key). The scale counts as the
|
||||
/// key's thousandths ([`FrameKey::scale`]): a series rebuilt from the key (the cache bars) has
|
||||
/// the same options as the frames rendered at 1/3 = 0.333… (#595).
|
||||
pub fn opts_hash(o: &RenderOpts) -> u64 {
|
||||
let o = RenderOpts { scale: (o.scale * 1000.0).round() / 1000.0, ..*o };
|
||||
let mut h = disk_cache::Hash128::default();
|
||||
h.write(format!("{o:?}").as_bytes());
|
||||
h.finish() as u64
|
||||
@@ -765,10 +768,8 @@ impl Frames {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if self.remote.is_none() {
|
||||
let w = self.worker();
|
||||
// One spawn per job; each spawn renders whichever queued job matters most right now.
|
||||
let job = move || {
|
||||
w.run_next();
|
||||
};
|
||||
// One spawn per job; each spawn renders whichever queued jobs matter most right now.
|
||||
let job = move || w.drain();
|
||||
match &self.pool {
|
||||
Some(pool) => pool.spawn(job),
|
||||
None => rayon::spawn(job),
|
||||
@@ -921,7 +922,42 @@ struct Worker {
|
||||
gpu_retired: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
thread_local! {
|
||||
/// This pool thread is inside [`Worker::drain`] (rendering a frame).
|
||||
static DRAINING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// Clears [`DRAINING`] when the drain ends, even by a panic.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
struct Draining;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl Drop for Draining {
|
||||
fn drop(&mut self) {
|
||||
DRAINING.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
impl Worker {
|
||||
/// Render queued jobs, most important first, until the queue is empty.
|
||||
///
|
||||
/// A pool thread waiting inside a render (on a parallel loop's join) runs other pool work
|
||||
/// meanwhile, including the spawns of newer requests: each would start a whole frame render
|
||||
/// on top of the one waiting, with all of its buffers. Dragging a layer asks for a new frame
|
||||
/// every UI frame, so renders piled up on every thread until memory ran out (#647). A spawn
|
||||
/// that lands inside a render returns at once instead; the render below it takes the queued
|
||||
/// jobs when it is done, so each thread renders one frame at a time.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn drain(&self) {
|
||||
if DRAINING.get() {
|
||||
return;
|
||||
}
|
||||
DRAINING.set(true);
|
||||
let _reset = Draining;
|
||||
while self.run_next() {}
|
||||
}
|
||||
|
||||
/// Render the queued job that matters most right now. `false` when the queue was empty.
|
||||
fn run_next(&self) -> bool {
|
||||
let Worker { queue, content_keys, .. } = self;
|
||||
@@ -1231,6 +1267,80 @@ mod tests {
|
||||
assert!(!f.is_cached(&key));
|
||||
}
|
||||
|
||||
/// #647: a pool thread waiting inside a render (on a parallel loop) never starts another
|
||||
/// frame render on top of it. Dragging a layer queues a frame every UI frame; renders used to
|
||||
/// nest on every thread, each holding its buffers, until memory ran out.
|
||||
#[test]
|
||||
fn a_waiting_render_never_starts_another_on_its_thread() {
|
||||
use effectcraft_engine::Session;
|
||||
use effectcraft_engine::project::{Footage, FootageKind};
|
||||
use effectcraft_engine::render::Image;
|
||||
use effectcraft_engine::time::FrameRate;
|
||||
use serde_json::json;
|
||||
use std::cell::Cell;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
thread_local! {
|
||||
static DEPTH: Cell<usize> = const { Cell::new(0) };
|
||||
}
|
||||
/// A decoder that works in parallel, as the renderer does: its thread joins the loop and
|
||||
/// may wait for the parts other threads took.
|
||||
#[derive(Default)]
|
||||
struct Parallel {
|
||||
calls: AtomicUsize,
|
||||
deepest: AtomicUsize,
|
||||
}
|
||||
impl FootageSource for Parallel {
|
||||
fn frame(&self, _: ItemId, _: &Footage, _: Tick) -> Option<Arc<Image>> {
|
||||
let d = DEPTH.get() + 1;
|
||||
DEPTH.set(d);
|
||||
self.deepest.fetch_max(d, Ordering::SeqCst);
|
||||
self.calls.fetch_add(1, Ordering::SeqCst);
|
||||
(0..64).into_par_iter().for_each(|_| std::thread::sleep(std::time::Duration::from_millis(1)));
|
||||
DEPTH.set(d - 1);
|
||||
Some(Arc::new(Image::new(4, 4)))
|
||||
}
|
||||
}
|
||||
let mut s = Session::default();
|
||||
let cid = ItemId(s.execute("comp.new", json!({"name": "A", "width": 8, "height": 8, "duration": 10})).unwrap()["comp"].as_u64().unwrap());
|
||||
let clip = Footage {
|
||||
kind: FootageKind::Video,
|
||||
width: 4,
|
||||
height: 4,
|
||||
has_video: true,
|
||||
frame_rate: FrameRate::FPS_30,
|
||||
duration: Tick::from_seconds_f64(10.0),
|
||||
..Default::default()
|
||||
};
|
||||
let item = Arc::make_mut(&mut s.project).add_item("clip.mov", Default::default(), None, ItemKind::Footage(clip));
|
||||
s.execute("layer.addItem", json!({"item": item.0})).unwrap();
|
||||
let footage = Arc::new(Parallel::default());
|
||||
let src = RenderSource {
|
||||
project: s.project.clone(),
|
||||
footage: footage.clone(),
|
||||
expr: None,
|
||||
layer_cache: Arc::default(),
|
||||
gpu: None,
|
||||
gpu_display: false,
|
||||
disk: None,
|
||||
};
|
||||
let f = Frames::default();
|
||||
let content = f.content_of(&s.project, s.revision, cid);
|
||||
let frames = 60;
|
||||
for frame in 0..frames {
|
||||
let key = FrameKey { revision: s.revision, content, comp: cid.0, frame, scale: 1000, view: 0, opts: 0 };
|
||||
f.request(&src, key, cid, FrameRate::FPS_30.tick_of(frame), RenderOpts::default());
|
||||
}
|
||||
for _ in 0..4000 {
|
||||
if f.inflight() == 0 {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
}
|
||||
assert_eq!(f.inflight(), 0, "every queued frame rendered");
|
||||
assert!(footage.calls.load(Ordering::SeqCst) >= frames as usize);
|
||||
assert_eq!(footage.deepest.load(Ordering::SeqCst), 1, "renders nested on a waiting thread");
|
||||
}
|
||||
|
||||
/// #284: scrubbing asks for a viewer frame at every step; a newer one drops the comp's viewer
|
||||
/// frames still waiting (they would all render first), but not prefetch frames or another
|
||||
/// comp's viewer frame.
|
||||
|
||||
@@ -166,6 +166,9 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
if app.ui.tool.puppet_kind().is_some() {
|
||||
x = puppet_options(app, ui, &p, x, cy);
|
||||
}
|
||||
if app.ui.tool.roto_kind(false).is_some() {
|
||||
x = roto_options(app, ui, &p, x, cy);
|
||||
}
|
||||
let snap = Rect::from_min_size(pos2(x, cy - 10.0), vec2(20.0, 20.0));
|
||||
// The engine owns snapping (View ▸ Snapping); the checkbox mirrors it.
|
||||
app.ui.snapping = app.session.state.snapping;
|
||||
@@ -179,12 +182,15 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
|
||||
// Right side: community buttons, workspaces.
|
||||
let mut rx = rect.max.x - 10.0;
|
||||
let discord = Rect::from_min_max(pos2(rx - 104.0, cy - 13.0), pos2(rx, cy + 13.0));
|
||||
// The pill fits its label (icon, gap, text) with even padding: it was a fixed 104 px with the
|
||||
// text at its left, which left a wide gap on the right (#581).
|
||||
let label = p.layout_no_wrap(tr("Discord").to_string(), Tokens::semibold(12.0), Color32::WHITE);
|
||||
let discord = Rect::from_min_max(pos2(rx - (10.0 + 14.0 + 6.0 + label.size().x + 12.0), cy - 13.0), pos2(rx, cy + 13.0));
|
||||
let dresp = ui.interact(discord, egui::Id::new("hdr-discord"), Sense::click());
|
||||
let dc = Color32::from_rgb(0x58, 0x65, 0xf2);
|
||||
p.rect_filled(discord, 13.0, if dresp.hovered() { dc.gamma_multiply(1.2) } else { dc });
|
||||
icons::paint(&p, Rect::from_center_size(pos2(discord.min.x + 16.0, cy), vec2(14.0, 14.0)), Icon::Chat, Color32::WHITE);
|
||||
p.text(pos2(discord.min.x + 28.0, cy), Align2::LEFT_CENTER, tr("Discord"), Tokens::semibold(12.0), Color32::WHITE);
|
||||
icons::paint(&p, Rect::from_center_size(pos2(discord.min.x + 17.0, cy), vec2(14.0, 14.0)), Icon::Chat, Color32::WHITE);
|
||||
p.galley(pos2(discord.min.x + 30.0, cy - label.size().y / 2.0), label, Color32::WHITE);
|
||||
app.auto.add("header.discord", discord, "Join the ArtCraft Discord");
|
||||
if dresp.on_hover_text(tr("Join the ArtCraft community on Discord")).clicked() {
|
||||
let _ = app.session.execute("help.discord", json!({}));
|
||||
@@ -366,7 +372,7 @@ fn fill_stroke_options(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Pa
|
||||
}
|
||||
}
|
||||
let mut c = tp.color;
|
||||
if color_popup(ui, picker_id(key), sr.left_bottom(), &mut c) {
|
||||
if widgets::color_popup(ui, picker_id(key), sr.left_bottom(), &mut c) {
|
||||
tool_options(app, json!({key: c}));
|
||||
paint(app, key, json!(c));
|
||||
}
|
||||
@@ -447,12 +453,6 @@ fn paint_options_popup(app: &mut EffectcraftApp, ui: &mut egui::Ui, key: &str, t
|
||||
}
|
||||
}
|
||||
|
||||
/// sRGB components (0–1) as a colour.
|
||||
fn srgb32(c: [f32; 3]) -> Color32 {
|
||||
let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
Color32::from_rgb(b(c[0]), b(c[1]), b(c[2]))
|
||||
}
|
||||
|
||||
/// A Fill or Stroke swatch: its colour, a gradient (white to black), or None's red slash.
|
||||
fn paint_swatch(p: &egui::Painter, r: Rect, paint: &ToolPaint, hovered: bool, t: &Tokens) {
|
||||
let clip = p.with_clip_rect(r);
|
||||
@@ -462,7 +462,7 @@ fn paint_swatch(p: &egui::Painter, r: Rect, paint: &ToolPaint, hovered: bool, t:
|
||||
clip.line_segment([r.left_bottom(), r.right_top()], Stroke::new(1.5, Color32::from_rgb(0xe0, 0x30, 0x30)));
|
||||
}
|
||||
PaintKind::Solid => {
|
||||
clip.rect_filled(r, 2.0, srgb32(paint.color));
|
||||
clip.rect_filled(r, 2.0, widgets::srgb32(paint.color));
|
||||
}
|
||||
PaintKind::Linear => {
|
||||
let mut m = egui::Mesh::default();
|
||||
@@ -486,6 +486,26 @@ fn paint_swatch(p: &egui::Painter, r: Rect, paint: &ToolPaint, hovered: bool, t:
|
||||
p.rect_stroke(r, 2.0, Stroke::new(1.0, if hovered { t.text } else { t.field_border }), StrokeKind::Inside);
|
||||
}
|
||||
|
||||
/// Roto Brush / Refine Edge tool options: the brush Diameter (⌘/Ctrl-drag in the Layer panel
|
||||
/// sets it too, as in After Effects). Returns the next x.
|
||||
fn roto_options(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, mut x: f32, cy: f32) -> f32 {
|
||||
let t = app.tokens;
|
||||
let refine = app.ui.tool.roto_kind(false).is_some_and(|k| k.starts_with("refine"));
|
||||
let o = &app.session.state.roto;
|
||||
let (key, v) = if refine { ("refineDiameter", o.refine_diameter) } else { ("diameter", o.diameter) };
|
||||
let label = tr("Diameter:");
|
||||
let lr = p.text(pos2(x, cy), Align2::LEFT_CENTER, label, Tokens::ui(12.0), t.text_dim);
|
||||
x = lr.max.x + 6.0;
|
||||
let (r, nv, _) = widgets::hot_number_at(ui, pos2(x, cy - 9.0), egui::Id::new(("roto-opt", key)), v, 0.5, (1.0, 5000.0), 0, " px", &t);
|
||||
app.auto.add("header.roto.diameter", r, label);
|
||||
if let Some(nv) = nv
|
||||
&& let Err(e) = app.session.execute("roto.options", json!({key: nv}))
|
||||
{
|
||||
app.ui.status = e.to_string();
|
||||
}
|
||||
r.max.x + 12.0
|
||||
}
|
||||
|
||||
/// Puppet tool options: Mesh: Show, Expansion, Density (for new meshes and the selected
|
||||
/// layer's meshes). Returns the next x.
|
||||
fn puppet_options(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, mut x: f32, cy: f32) -> f32 {
|
||||
@@ -557,28 +577,6 @@ fn ws_menu(app: &mut EffectcraftApp, ui: &mut egui::Ui) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A small colour picker popup bound to an RGB value.
|
||||
pub fn color_popup(ui: &mut egui::Ui, id: egui::Id, pos: egui::Pos2, c: &mut [f32; 3]) -> bool {
|
||||
let open_id = id.with("open");
|
||||
if !ui.data(|d| d.get_temp::<bool>(open_id).unwrap_or(false)) {
|
||||
return false;
|
||||
}
|
||||
let mut changed = false;
|
||||
let area = egui::Area::new(id.with("area")).order(egui::Order::Foreground).fixed_pos(pos + vec2(0.0, 4.0)).show(ui.ctx(), |ui| {
|
||||
egui::Frame::popup(ui.style()).show(ui, |ui| {
|
||||
let mut col = srgb32(*c);
|
||||
if egui::color_picker::color_picker_color32(ui, &mut col, egui::color_picker::Alpha::Opaque) {
|
||||
*c = [col.r() as f32 / 255.0, col.g() as f32 / 255.0, col.b() as f32 / 255.0];
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
if widgets::pressed_outside(ui.ctx(), &area.response) || ui.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
ui.data_mut(|d| d.insert_temp(open_id, false));
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The ArtCraft mark as supplied in `docs/brand` (the README's and getartcraft.com's logo; used
|
||||
/// unmodified, see `docs/brand/LICENSE-brand.txt`).
|
||||
static ARTCRAFT_MARK: &[u8] = include_bytes!("../../../docs/brand/artcraft-mark.png");
|
||||
|
||||
@@ -286,6 +286,7 @@ const JAPANESE: &[(&str, &str)] = &[
|
||||
("Maximize Panel", "パネルを最大化"),
|
||||
("Media Replacement", "メディアの置き換え"),
|
||||
("Mesh:", "メッシュ:"),
|
||||
("Diameter:", "直径:"),
|
||||
("Method Used: {} Average Error: {} pixels", "使用した手法:{} 平均誤差:{}ピクセル"),
|
||||
("Models folder: {}", "モデルフォルダー:{}"),
|
||||
("Modifiers:", "修飾キー:"),
|
||||
@@ -320,6 +321,7 @@ const JAPANESE: &[(&str, &str)] = &[
|
||||
("No device list from this host; the system default output is used.", "このホストからはデバイス一覧を取得できないため、システムの既定の出力を使用します。"),
|
||||
("No layer selected", "レイヤーが選択されていません"),
|
||||
("No matching effects or presets", "一致するエフェクトまたはプリセットはありません"),
|
||||
("No matching fonts", "一致するフォントはありません"),
|
||||
("No model credits were built into this copy.", "このビルドにはモデルのクレジットが含まれていません。"),
|
||||
("No nested compositions", "ネストされたコンポジションはありません"),
|
||||
("No shortcut", "ショートカットなし"),
|
||||
@@ -403,6 +405,7 @@ const JAPANESE: &[(&str, &str)] = &[
|
||||
("Select a command to change its shortcut.", "ショートカットを変更するコマンドを選択してください。"),
|
||||
("Select a layer to see its effects", "レイヤーを選択するとエフェクトが表示されます"),
|
||||
("Select a layer to see its properties", "レイヤーを選択するとプロパティが表示されます"),
|
||||
("({}) Selected Objects", "({}) 個の選択されたオブジェクト"),
|
||||
(
|
||||
"Select a layer with a mask or shape path (or the path property), or Puppet pins.",
|
||||
"マスクまたはシェイプパスのあるレイヤー(またはパスプロパティ)か、パペットピンを選択してください。",
|
||||
@@ -720,6 +723,7 @@ const SIMPLIFIED_CHINESE: &[(&str, &str)] = &[
|
||||
("Maximize Panel", "最大化面板"),
|
||||
("Media Replacement", "媒体替换"),
|
||||
("Mesh:", "网格:"),
|
||||
("Diameter:", "直径:"),
|
||||
("Method Used: {} Average Error: {} pixels", "使用方法:{} 平均误差:{} 像素"),
|
||||
("Models folder: {}", "模型文件夹:{}"),
|
||||
("Modifiers:", "修饰键:"),
|
||||
@@ -751,6 +755,7 @@ const SIMPLIFIED_CHINESE: &[(&str, &str)] = &[
|
||||
("No device list from this host; the system default output is used.", "此主机无法获取设备列表;将使用系统默认输出。"),
|
||||
("No layer selected", "未选择图层"),
|
||||
("No matching effects or presets", "没有匹配的效果或预设"),
|
||||
("No matching fonts", "没有匹配的字体"),
|
||||
("No model credits were built into this copy.", "此副本未内置模型致谢。"),
|
||||
("No nested compositions", "没有嵌套合成"),
|
||||
("No shortcut", "无快捷键"),
|
||||
@@ -836,6 +841,7 @@ const SIMPLIFIED_CHINESE: &[(&str, &str)] = &[
|
||||
("Select a command to change its shortcut.", "选择一条命令以更改其快捷键。"),
|
||||
("Select a layer to see its effects", "选择图层以查看其效果"),
|
||||
("Select a layer to see its properties", "选择图层以查看其属性"),
|
||||
("({}) Selected Objects", "({}) 个选定对象"),
|
||||
(
|
||||
"Select a layer with a mask or shape path (or the path property), or Puppet pins.",
|
||||
"请选择带蒙版或形状路径(或路径属性)的图层,或带有人偶定位点的图层。",
|
||||
@@ -996,6 +1002,37 @@ const SIMPLIFIED_CHINESE: &[(&str, &str)] = &[
|
||||
("Use In-Window Menu Bar on macOS", "在 macOS 上使用窗口内菜单栏"),
|
||||
("Wireframe", "线框"),
|
||||
("sRGB IEC61966-2.1 (default)", "sRGB IEC61966-2.1(默认)"),
|
||||
// The Home screen (#574).
|
||||
("New Project", "新建项目"),
|
||||
("Open Project…", "打开项目…"),
|
||||
("Templates", "模板"),
|
||||
("EffectCraft home page", "EffectCraft 主页"),
|
||||
("EffectCraft on GitHub", "GitHub 上的 EffectCraft"),
|
||||
("Motion graphics and visual effects · version {}", "动态图形和视觉效果 · 版本 {}"),
|
||||
("New Composition", "新建合成"),
|
||||
("Open Demo Project", "打开示例项目"),
|
||||
("Import Footage…", "导入素材…"),
|
||||
("Filter recent files", "筛选最近文件"),
|
||||
("NAME", "名称"),
|
||||
("OPENED", "打开时间"),
|
||||
("SIZE", "大小"),
|
||||
("KIND", "类型"),
|
||||
("Your recent files will show here", "你最近使用的文件会显示在这里"),
|
||||
("Create a new project, or open the demo project to look around.", "新建一个项目,或打开示例项目先熟悉一下界面。"),
|
||||
("No recent files match the filter", "没有与筛选条件匹配的最近文件"),
|
||||
("Try another name or folder.", "请尝试其他名称或文件夹。"),
|
||||
("Just now", "刚刚"),
|
||||
("Yesterday", "昨天"),
|
||||
("{} minute ago", "{} 分钟前"),
|
||||
("{} minutes ago", "{} 分钟前"),
|
||||
("{} hour ago", "{} 小时前"),
|
||||
("{} hours ago", "{} 小时前"),
|
||||
("{} day ago", "{} 天前"),
|
||||
("{} days ago", "{} 天前"),
|
||||
("EffectCraft project", "EffectCraft 项目"),
|
||||
("After Effects project", "After Effects 项目"),
|
||||
("Lottie animation", "Lottie 动画"),
|
||||
("Project", "项目"),
|
||||
];
|
||||
|
||||
const TRADITIONAL_CHINESE: &[(&str, &str)] = &[
|
||||
@@ -1211,6 +1248,7 @@ const TRADITIONAL_CHINESE: &[(&str, &str)] = &[
|
||||
("Maximize Panel", "最大化面板"),
|
||||
("Media Replacement", "媒體替換"),
|
||||
("Mesh:", "格點:"),
|
||||
("Diameter:", "直徑:"),
|
||||
("Method Used: {} Average Error: {} pixels", "使用方法:{} 平均誤差:{} 像素"),
|
||||
("Models folder: {}", "模型資料夾:{}"),
|
||||
("Modifiers:", "修飾鍵:"),
|
||||
@@ -1242,6 +1280,7 @@ const TRADITIONAL_CHINESE: &[(&str, &str)] = &[
|
||||
("No device list from this host; the system default output is used.", "此主機無法獲取設備清單;將使用系統預設輸出。"),
|
||||
("No layer selected", "未選取圖層"),
|
||||
("No matching effects or presets", "沒有匹配的效果或預設集"),
|
||||
("No matching fonts", "沒有符合的字體"),
|
||||
("No model credits were built into this copy.", "此副本未內置模型致謝。"),
|
||||
("No nested compositions", "沒有嵌套合成"),
|
||||
("No shortcut", "無快速鍵"),
|
||||
@@ -1327,6 +1366,7 @@ const TRADITIONAL_CHINESE: &[(&str, &str)] = &[
|
||||
("Select a command to change its shortcut.", "選取一條命令以更改其快速鍵。"),
|
||||
("Select a layer to see its effects", "選取圖層以查看其效果"),
|
||||
("Select a layer to see its properties", "選取圖層以查看其屬性"),
|
||||
("({}) Selected Objects", "({}) 個選取的物件"),
|
||||
(
|
||||
"Select a layer with a mask or shape path (or the path property), or Puppet pins.",
|
||||
"請選取帶遮色片或形狀路徑(或路徑屬性)的圖層,或帶有人偶釘選點的圖層。",
|
||||
@@ -1469,7 +1509,7 @@ const TRADITIONAL_CHINESE: &[(&str, &str)] = &[
|
||||
("Import PDF / Illustrator File", "Import PDF / Illustrator File"),
|
||||
("Import Photoshop File", "Import Photoshop File"),
|
||||
("Interpret Unlabeled Alpha As", "Interpret Unlabeled Alpha As"),
|
||||
("Join the ArtCraft Discord", "Join the ArtCraft Discord"),
|
||||
("Join the ArtCraft Discord", "加入 ArtCraft Discord"),
|
||||
("Mercury GPU Acceleration ({})", "Mercury GPU Acceleration ({})"),
|
||||
("Mercury Software Only", "Mercury Software Only"),
|
||||
("OCIO (built-in ACES config)", "OCIO (built-in ACES config)"),
|
||||
@@ -1482,6 +1522,37 @@ const TRADITIONAL_CHINESE: &[(&str, &str)] = &[
|
||||
("Use In-Window Menu Bar on macOS", "Use In-Window Menu Bar on macOS"),
|
||||
("Wireframe", "Wireframe"),
|
||||
("sRGB IEC61966-2.1 (default)", "sRGB IEC61966-2.1 (default)"),
|
||||
// The Home screen (#574).
|
||||
("New Project", "新增專案"),
|
||||
("Open Project…", "開啟專案…"),
|
||||
("Templates", "範本"),
|
||||
("EffectCraft home page", "EffectCraft 首頁"),
|
||||
("EffectCraft on GitHub", "GitHub 上的 EffectCraft"),
|
||||
("Motion graphics and visual effects · version {}", "動態圖形與視覺效果 · 版本 {}"),
|
||||
("New Composition", "新增合成"),
|
||||
("Open Demo Project", "開啟範例專案"),
|
||||
("Import Footage…", "匯入素材…"),
|
||||
("Filter recent files", "篩選最近的檔案"),
|
||||
("NAME", "名稱"),
|
||||
("OPENED", "開啟時間"),
|
||||
("SIZE", "大小"),
|
||||
("KIND", "類型"),
|
||||
("Your recent files will show here", "你最近使用的檔案會顯示在這裡"),
|
||||
("Create a new project, or open the demo project to look around.", "新增一個專案,或開啟範例專案先熟悉一下介面。"),
|
||||
("No recent files match the filter", "沒有符合篩選條件的最近檔案"),
|
||||
("Try another name or folder.", "請嘗試其他名稱或資料夾。"),
|
||||
("Just now", "剛剛"),
|
||||
("Yesterday", "昨天"),
|
||||
("{} minute ago", "{} 分鐘前"),
|
||||
("{} minutes ago", "{} 分鐘前"),
|
||||
("{} hour ago", "{} 小時前"),
|
||||
("{} hours ago", "{} 小時前"),
|
||||
("{} day ago", "{} 天前"),
|
||||
("{} days ago", "{} 天前"),
|
||||
("EffectCraft project", "EffectCraft 專案"),
|
||||
("After Effects project", "After Effects 專案"),
|
||||
("Lottie animation", "Lottie 動畫"),
|
||||
("Project", "專案"),
|
||||
];
|
||||
|
||||
/// Ukrainian (uk): original translations of the same interface rows as the Chinese catalogs.
|
||||
@@ -1692,6 +1763,7 @@ const UKRAINIAN: &[(&str, &str)] = &[
|
||||
("Maximize Panel", "Розгорнути панель"),
|
||||
("Media Replacement", "Заміна матеріалу"),
|
||||
("Mesh:", "Сітка:"),
|
||||
("Diameter:", "Діаметр:"),
|
||||
("Method Used: {} Average Error: {} pixels", "Використаний метод: {} Середня похибка: {} пікселів"),
|
||||
("Models folder: {}", "Тека моделей: {}"),
|
||||
("Modifiers:", "Модифікатори:"),
|
||||
@@ -1729,6 +1801,7 @@ const UKRAINIAN: &[(&str, &str)] = &[
|
||||
),
|
||||
("No layer selected", "Шар не виділено"),
|
||||
("No matching effects or presets", "Не знайдено відповідних ефектів або наборів"),
|
||||
("No matching fonts", "Не знайдено відповідних шрифтів"),
|
||||
("No model credits were built into this copy.", "Ця копія не містить відомостей про моделі."),
|
||||
("No nested compositions", "Немає вкладених композицій"),
|
||||
("No shortcut", "Немає клавіатурного скорочення"),
|
||||
@@ -1812,6 +1885,7 @@ const UKRAINIAN: &[(&str, &str)] = &[
|
||||
("Select a command to change its shortcut.", "Виберіть команду, щоб змінити її клавіатурне скорочення."),
|
||||
("Select a layer to see its effects", "Виділіть шар, щоб переглянути його ефекти"),
|
||||
("Select a layer to see its properties", "Виділіть шар, щоб переглянути його властивості"),
|
||||
("({}) Selected Objects", "Вибрано об’єктів: ({})"),
|
||||
(
|
||||
"Select a layer with a mask or shape path (or the path property), or Puppet pins.",
|
||||
"Виділіть шар із маскою або контуром фігури (або властивість контуру) чи опорні точки деформації.",
|
||||
@@ -1923,9 +1997,11 @@ mod tests {
|
||||
/// The interface text that has moved into this catalog. Add a panel here when you convert it;
|
||||
/// the tests below then keep it translated.
|
||||
const CONVERTED: &[(&str, &str)] = &[
|
||||
("color_picker.rs", include_str!("../color_picker.rs")),
|
||||
("credits.rs", include_str!("../credits.rs")),
|
||||
("header.rs", include_str!("../header.rs")),
|
||||
("menus.rs", include_str!("../menus.rs")),
|
||||
("widgets.rs", include_str!("../widgets.rs")),
|
||||
("panels/anim_tools.rs", include_str!("../panels/anim_tools.rs")),
|
||||
("panels/camera_tracker_ui.rs", include_str!("../panels/camera_tracker_ui.rs")),
|
||||
("panels/comp_settings.rs", include_str!("../panels/comp_settings.rs")),
|
||||
|
||||
+158
-4
@@ -10,6 +10,7 @@
|
||||
pub mod audio;
|
||||
pub mod automation;
|
||||
pub mod bench;
|
||||
pub mod color_picker;
|
||||
pub mod control;
|
||||
pub mod credits;
|
||||
pub mod dock;
|
||||
@@ -24,6 +25,7 @@ pub mod menu_keys;
|
||||
pub mod menus;
|
||||
pub mod native_menu;
|
||||
pub mod panels;
|
||||
mod pointer_wrap;
|
||||
pub mod prefs_live;
|
||||
pub mod state;
|
||||
pub mod theme;
|
||||
@@ -98,6 +100,39 @@ pub enum Dialog {
|
||||
/// winit no theme). `None` = the host does not know.
|
||||
pub type SystemThemeFn = Box<dyn Fn(&egui::Context) -> Option<egui::Theme>>;
|
||||
|
||||
/// A file dialog a host shows without blocking the frame ([`Hooks::file_dialog_async`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum FileDialog {
|
||||
/// Files to open or import with these extensions; several when `many`.
|
||||
Open { exts: Vec<String>, many: bool },
|
||||
/// An EffectCraft project to open.
|
||||
OpenProject,
|
||||
/// A folder.
|
||||
Folder,
|
||||
/// Where to save `default` (a file name or path) with extension `ext` (empty: no filter);
|
||||
/// `project`: the project save dialog, given the file name.
|
||||
Save { default: String, ext: String, project: bool },
|
||||
}
|
||||
|
||||
impl FileDialog {
|
||||
/// The save dialog for `default`, as [`Hooks::save_dialog`] picks it.
|
||||
pub fn save(default: &str) -> Self {
|
||||
let ext = std::path::Path::new(default).extension().map(|e| e.to_string_lossy().to_string()).unwrap_or_default();
|
||||
Self::Save { default: default.to_string(), project: ext.eq_ignore_ascii_case("ecproj"), ext }
|
||||
}
|
||||
}
|
||||
|
||||
/// Called with the paths a [`FileDialog`] picked (empty: cancelled), from any thread.
|
||||
pub type DialogDone = Box<dyn FnOnce(Vec<String>) + Send>;
|
||||
|
||||
/// A non-blocking file dialog's answer for the command that asked (`menus::dialog_answered`).
|
||||
pub(crate) struct DialogAnswer {
|
||||
pub command: String,
|
||||
pub key: &'static str,
|
||||
pub params: serde_json::Value,
|
||||
pub paths: Vec<String>,
|
||||
}
|
||||
|
||||
/// Host hooks provided by the native app (file pickers etc.).
|
||||
#[derive(Default)]
|
||||
pub struct Hooks {
|
||||
@@ -121,6 +156,14 @@ pub struct Hooks {
|
||||
/// Application actions the OS performs (`app.hide`, `app.hideOthers`, `app.showAll` on
|
||||
/// macOS). Returns false when the host doesn't handle the id.
|
||||
pub app_action: Option<Box<dyn Fn(&str) -> bool>>,
|
||||
/// Shows a command's file dialog without blocking the frame and calls `done` with the
|
||||
/// answer (the host then asks for a repaint). Used in place of the blocking pickers above for
|
||||
/// the commands' dialogs (File ▸ Import, Open, Save As…) where a modal dialog's nested event
|
||||
/// loop inside a frame is unsafe: on macOS a drag over the window then aborted the app (#511).
|
||||
pub file_dialog_async: Option<Box<dyn Fn(FileDialog, DialogDone)>>,
|
||||
/// Tells the user the graphics device was lost and the window is closing, once. `saved` is
|
||||
/// the auto-save of unsaved changes (`None`: nothing was unsaved), its path or why it failed.
|
||||
pub device_lost: Option<Box<dyn Fn(Option<Result<String, String>>)>>,
|
||||
}
|
||||
|
||||
impl Hooks {
|
||||
@@ -262,6 +305,11 @@ pub struct EffectcraftApp {
|
||||
gpu_checked: bool,
|
||||
gpu_failures: Option<gpu_failure::GpuFailureBridge>,
|
||||
gpu_failure_applied: Option<bool>,
|
||||
/// The graphics device was lost and the window is closing (see `close_after_device_loss`);
|
||||
/// `true` keeps crash recovery for the next launch.
|
||||
device_lost_close: Option<bool>,
|
||||
/// Answers of file dialogs shown without blocking ([`Hooks::file_dialog_async`]).
|
||||
pub(crate) dialog_answers: (Sender<DialogAnswer>, Receiver<DialogAnswer>),
|
||||
/// Commands from the native menu bar.
|
||||
pub command_inbox: Option<Receiver<String>>,
|
||||
/// Pointer position in comp pixels (Info panel).
|
||||
@@ -298,6 +346,17 @@ pub struct EffectcraftApp {
|
||||
pub(crate) template_list: Option<(Vec<String>, Vec<effectcraft_engine::templates::TemplateInfo>)>,
|
||||
}
|
||||
|
||||
/// The saved workspaces in the settings store ([`effectcraft_engine::config::ConfigStore`]).
|
||||
pub const WORKSPACES_FILE: &str = "workspaces.json";
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
struct SavedWorkspaces {
|
||||
#[serde(default)]
|
||||
workspaces: std::collections::BTreeMap<String, dock::DockNode>,
|
||||
#[serde(default)]
|
||||
floating: std::collections::BTreeMap<String, Vec<dock::Floating>>,
|
||||
}
|
||||
|
||||
impl EffectcraftApp {
|
||||
pub fn new(session: Session) -> Self {
|
||||
let mut ui = UiState::default();
|
||||
@@ -340,6 +399,8 @@ impl EffectcraftApp {
|
||||
gpu_checked: false,
|
||||
gpu_failures: None,
|
||||
gpu_failure_applied: None,
|
||||
device_lost_close: None,
|
||||
dialog_answers: std::sync::mpsc::channel(),
|
||||
command_inbox: None,
|
||||
pointer_comp: None,
|
||||
dialog_state: Default::default(),
|
||||
@@ -361,6 +422,12 @@ impl EffectcraftApp {
|
||||
.with_ui_commands()
|
||||
}
|
||||
|
||||
/// Keep the saved workspaces for the next session (see [`EffectcraftApp::new`]): After
|
||||
/// Effects' saved workspaces last until they are deleted (#320).
|
||||
pub(crate) fn store_saved_workspaces(&mut self) {
|
||||
self.save_workspace_state();
|
||||
}
|
||||
|
||||
/// Offer the frontend's commands (tools, timeline navigation…) for keyboard shortcuts.
|
||||
fn with_ui_commands(mut self) -> Self {
|
||||
let cmds = menus::UI_COMMANDS
|
||||
@@ -392,6 +459,7 @@ impl EffectcraftApp {
|
||||
self.ui.theme = theme::ThemeKind::from_name(p.appearance.resolved_theme(system)).unwrap_or_default();
|
||||
self.tokens = Tokens::from_prefs(p, self.ui.theme);
|
||||
theme::apply_visuals(ctx, &self.tokens);
|
||||
ctx.set_theme(theme::theme_preference(&p.appearance.appearance_mode, self.ui.theme.is_light()));
|
||||
let tips = p.general.show_tool_tips;
|
||||
ctx.all_styles_mut(|s| s.interaction.tooltip_delay = if tips { 0.5 } else { f32::INFINITY });
|
||||
// Settings ▸ Appearance ▸ UI Scale (#284). egui's own Ctrl+= / Ctrl+- / Ctrl+0 zoom stays
|
||||
@@ -607,6 +675,40 @@ impl EffectcraftApp {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
|
||||
/// After the graphics device is lost, eframe's renderer cannot draw again: any mesh makes
|
||||
/// egui-wgpu panic on the main thread when it cannot stage its index buffer (#591). Draw
|
||||
/// nothing from then on, auto-save a project with unsaved changes (keeping the crash
|
||||
/// recovery marker, so the next launch offers it) and close the window.
|
||||
fn close_after_device_loss(&mut self, ctx: &egui::Context) {
|
||||
if self.device_lost_close.is_some() {
|
||||
return;
|
||||
}
|
||||
let keep_recovery = self.session.is_dirty();
|
||||
let saved = keep_recovery.then(|| match self.session.autosave_now().and_then(|path| self.session.autosave_wait().map(|()| path)) {
|
||||
Ok(path) => {
|
||||
log::warn!("graphics device lost: auto-saved {path}; the next launch offers to recover it");
|
||||
Ok(path)
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("graphics device lost: {e}");
|
||||
Err(e.to_string())
|
||||
}
|
||||
});
|
||||
self.device_lost_close = Some(keep_recovery);
|
||||
log::warn!("graphics device lost: closing the window");
|
||||
if let Some(tell) = &self.hooks.device_lost {
|
||||
tell(saved);
|
||||
}
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||
}
|
||||
|
||||
/// Run the commands whose non-blocking file dialogs have been answered.
|
||||
pub(crate) fn run_dialog_answers(&mut self) {
|
||||
while let Ok(answer) = self.dialog_answers.1.try_recv() {
|
||||
menus::dialog_answered(self, answer);
|
||||
}
|
||||
}
|
||||
|
||||
/// Set up the GPU compositor on egui-wgpu's device (once). Without an adapter that runs
|
||||
/// compute shaders (WebGL2, software GL) everything stays on the CPU.
|
||||
pub(crate) fn init_gpu(&mut self, frame: &eframe::Frame) {
|
||||
@@ -618,6 +720,15 @@ impl EffectcraftApp {
|
||||
return;
|
||||
}
|
||||
let Some(rs) = frame.wgpu_render_state() else { return };
|
||||
// Help ▸ System Compatibility Report names the adapter and backend the window got.
|
||||
let info = rs.adapter.get_info();
|
||||
self.session.window_adapter = Some(format!(
|
||||
"{} ({:?}, {:?}{})",
|
||||
info.name,
|
||||
info.backend,
|
||||
info.device_type,
|
||||
if info.driver.is_empty() { String::new() } else { format!(", {} {}", info.driver, info.driver_info) }
|
||||
));
|
||||
// Backend validation can panic on shader compilation even when device creation
|
||||
// succeeded. Keep the document and the egui renderer, and use CPU compositing.
|
||||
let gpu = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| effectcraft_gpu::Gpu::new(&rs.adapter, rs.device.clone(), rs.queue.clone())));
|
||||
@@ -1438,6 +1549,7 @@ impl EffectcraftApp {
|
||||
fn frame(&mut self, ui: &mut egui::Ui) {
|
||||
let ctx = ui.ctx().clone();
|
||||
self.apply_gpu_failure(&ctx);
|
||||
self.run_dialog_answers();
|
||||
self.auto.begin_frame();
|
||||
self.frames.set_context(&ctx);
|
||||
if self.session.render_job.is_some() {
|
||||
@@ -1650,12 +1762,16 @@ impl EffectcraftApp {
|
||||
impl eframe::App for EffectcraftApp {
|
||||
fn on_exit(&mut self) {
|
||||
self.save_workspace_state();
|
||||
// Clean exit: no crash recovery next launch.
|
||||
self.session.end_recovery();
|
||||
// Clean exit: no crash recovery next launch (unless the graphics device was lost with
|
||||
// unsaved changes, which are in the auto-save it offers).
|
||||
if self.device_lost_close != Some(true) {
|
||||
self.session.end_recovery();
|
||||
}
|
||||
}
|
||||
|
||||
fn raw_input_hook(&mut self, _ctx: &egui::Context, raw_input: &mut egui::RawInput) {
|
||||
if !self.synthetic.is_empty() {
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
|
||||
let injected = !self.synthetic.is_empty();
|
||||
if injected {
|
||||
// Pointer events go one per frame so egui sees press → moves → release as a real drag.
|
||||
let pointer = |e: &egui::Event| matches!(e, egui::Event::PointerMoved(_) | egui::Event::PointerButton { .. } | egui::Event::MouseWheel { .. });
|
||||
let n = if pointer(&self.synthetic[0]) {
|
||||
@@ -1668,6 +1784,9 @@ impl eframe::App for EffectcraftApp {
|
||||
};
|
||||
raw_input.events.extend(self.synthetic.drain(..n));
|
||||
}
|
||||
if pointer_wrap::prepare_input(ctx, raw_input, injected) {
|
||||
self.session.history.merge_key = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
@@ -1706,6 +1825,10 @@ impl eframe::App for EffectcraftApp {
|
||||
}
|
||||
|
||||
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
||||
if self.gpu_failure_applied == Some(true) {
|
||||
self.close_after_device_loss(ui.ctx());
|
||||
return;
|
||||
}
|
||||
self.init_gpu(frame);
|
||||
if !self.fonts_ready {
|
||||
ui.ctx().request_repaint();
|
||||
@@ -1713,6 +1836,8 @@ impl eframe::App for EffectcraftApp {
|
||||
}
|
||||
self.frame(ui);
|
||||
let ctx = ui.ctx().clone();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pointer_wrap::finish_native(&ctx, frame);
|
||||
// wasm32: no frame threads; render queued frames now, between UI frames.
|
||||
if cfg!(target_arch = "wasm32") && self.frames.pump(std::time::Duration::from_millis(if self.playback.playing { 24 } else { 40 })) {
|
||||
ctx.request_repaint();
|
||||
@@ -1864,6 +1989,35 @@ mod appearance_tests {
|
||||
assert_eq!(app.ui.theme, ThemeKind::Dark);
|
||||
}
|
||||
|
||||
/// Sync with System leaves egui's theme preference at System, so egui never gives the native
|
||||
/// window an appearance of its own (on macOS that stops system appearance changes reaching
|
||||
/// the app, #642); egui's light and dark styles both carry the resolved theme. Fixed modes
|
||||
/// pin the window to their family.
|
||||
#[test]
|
||||
fn auto_mode_leaves_the_native_window_following_the_system() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = app();
|
||||
app.hooks.system_theme = Some(Box::new(|_| Some(egui::Theme::Light)));
|
||||
app.set_pref("appearance.appearanceMode", json!("auto")).unwrap();
|
||||
app.apply_prefs(&ctx);
|
||||
assert_eq!(app.ui.theme, ThemeKind::Light);
|
||||
assert_eq!(ctx.options(|o| o.theme_preference), egui::ThemePreference::System);
|
||||
for theme in [egui::Theme::Light, egui::Theme::Dark] {
|
||||
assert_eq!(ctx.style_of(theme).visuals.panel_fill, app.tokens.panel_bg, "{theme:?}");
|
||||
}
|
||||
// egui asks the window to follow the system, never to take Light or Dark.
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |_| {});
|
||||
out.textures_delta.clear();
|
||||
let cmds = out.viewport_output.values().flat_map(|v| v.commands.iter()).collect::<Vec<_>>();
|
||||
assert!(!cmds.iter().any(|c| matches!(c, egui::ViewportCommand::SetTheme(t) if t != &egui::SystemTheme::SystemDefault)), "{cmds:?}");
|
||||
for (mode, pref) in [("light", egui::ThemePreference::Light), ("dark", egui::ThemePreference::Dark)] {
|
||||
app.set_pref("appearance.appearanceMode", json!(mode)).unwrap();
|
||||
app.apply_prefs(&ctx);
|
||||
assert_eq!(ctx.options(|o| o.theme_preference), pref, "{mode}");
|
||||
assert_eq!(ctx.global_style().visuals.panel_fill, app.tokens.panel_bg, "{mode}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Picking a theme (`view.theme.*`, `ui.set {theme}`) fixes the mode to its family.
|
||||
#[test]
|
||||
fn picking_a_theme_fixes_its_mode() {
|
||||
|
||||
+142
-14
@@ -123,6 +123,7 @@ pub const UI_COMMANDS: &[UiCommand] = &[
|
||||
uic!("app.home", "Home", [], None),
|
||||
uic!("markers.dialog", "Marker Settings...", [], None),
|
||||
uic!("window.maximizePanel", "Maximize Panel Under Pointer", [], Some("`")),
|
||||
uic!("window.maximizeApp", "Maximize or Restore Application Window", [], Some("Cmd+\\")),
|
||||
uic!("window.dockPanel", "Dock Panel", [], None),
|
||||
uic!("window.floatPanel", "Undock Panel", [], None),
|
||||
uic!("window.closePanel", "Close Panel", [], None),
|
||||
@@ -441,6 +442,10 @@ pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: V
|
||||
}
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
// A UI-only command (not in the engine's menus), so `frontend` gets it from here.
|
||||
if id == "window.maximizeApp" {
|
||||
return frontend(app, ctx, id, params);
|
||||
}
|
||||
// Docking: {panel, anchor, zone: center|left|right|top|bottom}, {panel, rect?}, {panel?}.
|
||||
if let Some(op) = id.strip_prefix("window.").filter(|o| matches!(*o, "maximizePanel" | "dockPanel" | "floatPanel" | "closePanel")) {
|
||||
let panel_of = |k: &str| params.get(k).and_then(Value::as_str).map(|s| PanelKind::from_name(s).ok_or(format!("unknown panel `{s}`")));
|
||||
@@ -659,8 +664,9 @@ pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: V
|
||||
// up Effect Controls on that layer, as in After Effects.
|
||||
if matches!(id, "effect.apply" | "effect.applyLast") {
|
||||
let r = run_engine(app, ctx, id, params.clone());
|
||||
if r.is_ok() {
|
||||
if let Ok(applied) = &r {
|
||||
crate::panels::effect_controls::reveal_applied(app, ¶ms);
|
||||
crate::panels::effect_controls::choose_files_after_apply(app, applied);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
@@ -933,6 +939,12 @@ pub fn frontend(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, p: Valu
|
||||
};
|
||||
Value::Null
|
||||
}
|
||||
// Ctrl+\ / Cmd+\, as in After Effects (#336): `{maximized}`, the window's new state.
|
||||
"window.maximizeApp" => {
|
||||
let maximized = !ctx.input(|i| i.viewport().maximized.unwrap_or(false));
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Maximized(maximized));
|
||||
json!({"maximized": maximized})
|
||||
}
|
||||
"view.fullScreen" => {
|
||||
let full = ctx.input(|i| i.viewport().fullscreen.unwrap_or(false));
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Fullscreen(!full));
|
||||
@@ -967,6 +979,7 @@ pub fn frontend(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, p: Valu
|
||||
let name = app.ui.workspace.clone();
|
||||
app.ui.saved_workspaces.insert(name.clone(), app.ui.dock.clone());
|
||||
app.ui.saved_floating.insert(name.clone(), app.ui.floating.clone());
|
||||
app.store_saved_workspaces();
|
||||
json!({"workspace": name})
|
||||
}
|
||||
"window.saveWorkspaceAs" => {
|
||||
@@ -983,6 +996,7 @@ pub fn frontend(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, p: Valu
|
||||
app.ui.saved_workspaces.insert(name.clone(), app.ui.dock.clone());
|
||||
app.ui.saved_floating.insert(name.clone(), app.ui.floating.clone());
|
||||
app.ui.workspace = name.clone();
|
||||
app.store_saved_workspaces();
|
||||
json!({"workspace": name})
|
||||
}
|
||||
"window.editWorkspaces" => {
|
||||
@@ -1007,6 +1021,7 @@ pub fn frontend(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, p: Valu
|
||||
if app.ui.saved_workspaces.remove(&name).is_none() && !builtin {
|
||||
return Err(format!("no workspace `{name}`"));
|
||||
}
|
||||
app.store_saved_workspaces();
|
||||
if app.ui.workspace == name {
|
||||
app.set_workspace("Default");
|
||||
}
|
||||
@@ -1024,6 +1039,7 @@ pub fn frontend(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, p: Valu
|
||||
if app.ui.workspace == name {
|
||||
app.ui.workspace = new.to_string();
|
||||
}
|
||||
app.store_saved_workspaces();
|
||||
return Ok(json!({"renamed": new}));
|
||||
}
|
||||
json!({"workspaces": app.workspace_names()})
|
||||
@@ -1208,7 +1224,31 @@ fn file_dialog(app: &mut EffectcraftApp, id: &str, params: &Value) -> Option<Res
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut p = params.as_object().cloned().unwrap_or_default();
|
||||
const MEDIA: &[&str] = &[
|
||||
"mp4", "mov", "m4v", "mkv", "webm", "png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "wav", "aif", "aiff", "mp3", "flac", "ogg",
|
||||
"opus", "svg", "pdf", "ai", "eps", "psd", "psb", "gltf", "glb", "obj", "json", "csv", "tsv",
|
||||
];
|
||||
// A host whose modal dialogs would run a nested event loop inside this frame (macOS: a
|
||||
// drag over the window then re-entered winit's event handler and aborted, #511) shows the
|
||||
// dialog without blocking; the command continues when the answer arrives.
|
||||
if let Some(spawn) = app.hooks.file_dialog_async.as_ref() {
|
||||
let request = match ask {
|
||||
Ask::Folder => crate::FileDialog::Folder,
|
||||
Ask::Import => crate::FileDialog::Open { exts: MEDIA.iter().map(|e| e.to_string()).collect(), many: key == "paths" },
|
||||
Ask::OpenProject => crate::FileDialog::OpenProject,
|
||||
Ask::Open(exts) => crate::FileDialog::Open { exts: exts.iter().map(|e| e.to_string()).collect(), many: false },
|
||||
Ask::Save(default) => crate::FileDialog::save(default),
|
||||
};
|
||||
let tx = app.dialog_answers.0.clone();
|
||||
let answer = crate::DialogAnswer { command: id.to_string(), key, params: params.clone(), paths: Vec::new() };
|
||||
spawn(
|
||||
request,
|
||||
Box::new(move |paths| {
|
||||
let _ = tx.send(crate::DialogAnswer { paths, ..answer });
|
||||
}),
|
||||
);
|
||||
return Some(Ok(json!({"dialog": id})));
|
||||
}
|
||||
let picked: Option<Value> = match ask {
|
||||
Ask::Folder => {
|
||||
let Some(f) = app.hooks.pick_folder.as_ref() else { return Some(Err("no folder dialog available (pass `folder`)".into())) };
|
||||
@@ -1216,15 +1256,7 @@ fn file_dialog(app: &mut EffectcraftApp, id: &str, params: &Value) -> Option<Res
|
||||
}
|
||||
Ask::Import => {
|
||||
let Some(f) = app.hooks.pick_files.as_ref() else { return Some(Err("no file dialog available (pass `paths`)".into())) };
|
||||
let paths = f(&[
|
||||
"mp4", "mov", "m4v", "mkv", "webm", "png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "wav", "aif", "aiff", "mp3", "flac",
|
||||
"ogg", "opus", "svg", "pdf", "ai", "eps", "psd", "psb", "gltf", "glb", "obj", "json", "csv", "tsv",
|
||||
]);
|
||||
match (paths.is_empty(), key) {
|
||||
(true, _) => None,
|
||||
(false, "paths") => Some(json!(paths)),
|
||||
(false, _) => paths.first().map(|s| json!(s)),
|
||||
}
|
||||
picked_value(key, f(MEDIA))
|
||||
}
|
||||
Ask::OpenProject => {
|
||||
let Some(f) = app.hooks.pick_open_project.as_ref() else { return Some(Err("no file dialog available (pass `path`)".into())) };
|
||||
@@ -1240,6 +1272,30 @@ fn file_dialog(app: &mut EffectcraftApp, id: &str, params: &Value) -> Option<Res
|
||||
}
|
||||
};
|
||||
let Some(v) = picked else { return Some(Ok(Value::Null)) };
|
||||
Some(run_with_picked(app, id, key, params, v))
|
||||
}
|
||||
|
||||
/// The dialog's answer as the command's `key` parameter (`None`: cancelled).
|
||||
fn picked_value(key: &str, paths: Vec<String>) -> Option<Value> {
|
||||
match (paths.is_empty(), key) {
|
||||
(true, _) => None,
|
||||
(false, "paths") => Some(json!(paths)),
|
||||
(false, _) => paths.into_iter().next().map(Value::from),
|
||||
}
|
||||
}
|
||||
|
||||
/// A file dialog shown without blocking ([`crate::Hooks::file_dialog_async`]) answered: run its
|
||||
/// command with the picked path (nothing when it was cancelled).
|
||||
pub(crate) fn dialog_answered(app: &mut EffectcraftApp, answer: crate::DialogAnswer) {
|
||||
let Some(v) = picked_value(answer.key, answer.paths) else { return };
|
||||
if let Err(e) = run_with_picked(app, &answer.command, answer.key, &answer.params, v) {
|
||||
app.ui.status = e;
|
||||
}
|
||||
}
|
||||
|
||||
/// Run command `id` with the path picked for it in parameter `key`.
|
||||
fn run_with_picked(app: &mut EffectcraftApp, id: &str, key: &str, params: &Value, v: Value) -> Result<Value, String> {
|
||||
let mut p = params.as_object().cloned().unwrap_or_default();
|
||||
p.insert(key.to_string(), v);
|
||||
// Picked files import in the background, with the Importing card showing progress (#270).
|
||||
if matches!(id, "file.import" | "file.importMultiple") {
|
||||
@@ -1251,7 +1307,7 @@ fn file_dialog(app: &mut EffectcraftApp, id: &str, params: &Value) -> Option<Res
|
||||
if id == "file.import" && crate::panels::dialogs::open_form(app, id, &picked)
|
||||
|| matches!(id, "file.import" | "file.importMultiple") && crate::panels::forms::open_import_sequence(app, &picked)
|
||||
{
|
||||
return Some(Ok(json!({"dialog": id})));
|
||||
return Ok(json!({"dialog": id}));
|
||||
}
|
||||
// Save (untitled) becomes Save As.
|
||||
let id = if id == "file.save" { "file.saveAs" } else { id };
|
||||
@@ -1259,7 +1315,7 @@ fn file_dialog(app: &mut EffectcraftApp, id: &str, params: &Value) -> Option<Res
|
||||
if let Err(e) = &r {
|
||||
app.ui.status = e.clone();
|
||||
}
|
||||
Some(r)
|
||||
r
|
||||
}
|
||||
|
||||
/// A menu entry for display / `ui.menu.list`.
|
||||
@@ -1415,7 +1471,16 @@ pub fn shortcut_text(s: &str) -> String {
|
||||
pub fn parse_shortcut(s: &str) -> Option<(egui::Modifiers, egui::Key)> {
|
||||
let mut m = egui::Modifiers::NONE;
|
||||
let mut key = None;
|
||||
let parts: Vec<&str> = if s == "+" { vec!["+"] } else { s.split('+').collect() };
|
||||
// The plus key itself is written `+` or `Cmd++`.
|
||||
let (head, plus) = match s.strip_suffix("++") {
|
||||
Some(h) => (h, true),
|
||||
None if s == "+" => ("", true),
|
||||
None => (s, false),
|
||||
};
|
||||
let mut parts: Vec<&str> = if head.is_empty() { vec![] } else { head.split('+').collect() };
|
||||
if plus {
|
||||
parts.push("+");
|
||||
}
|
||||
for p in parts {
|
||||
match p {
|
||||
"Cmd" => {
|
||||
@@ -1921,6 +1986,34 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// #336: Ctrl+\ (Cmd+\ on macOS) maximizes the application window, and again restores
|
||||
/// it, as in After Effects.
|
||||
#[test]
|
||||
fn ctrl_backslash_maximizes_or_restores_the_window() {
|
||||
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
|
||||
let (m, k) = parse_shortcut("Cmd+\\").unwrap();
|
||||
assert!(m.command && k == egui::Key::Backslash, "{m:?} {k:?}");
|
||||
assert!(bindings(&app.session).iter().any(|b| (b.0, b.1) == (m, k) && b.2 == "window.maximizeApp"));
|
||||
let ctx = egui::Context::default();
|
||||
let run = |app: &mut EffectcraftApp, maximized: bool| {
|
||||
let input = egui::RawInput {
|
||||
viewports: std::iter::once((egui::ViewportId::ROOT, egui::ViewportInfo { maximized: Some(maximized), ..Default::default() })).collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut r = Value::Null;
|
||||
let mut out = ctx.run_ui(input, |ui| r = invoke(app, ui.ctx(), "window.maximizeApp", json!({})).unwrap());
|
||||
out.textures_delta.clear();
|
||||
let cmds = out.viewport_output.get(&egui::ViewportId::ROOT).map(|v| v.commands.clone()).unwrap_or_default();
|
||||
(r, cmds)
|
||||
};
|
||||
let (r, cmds) = run(&mut app, false);
|
||||
assert_eq!(r, json!({"maximized": true}));
|
||||
assert!(cmds.contains(&egui::ViewportCommand::Maximized(true)), "{cmds:?}");
|
||||
let (r, cmds) = run(&mut app, true);
|
||||
assert_eq!(r, json!({"maximized": false}));
|
||||
assert!(cmds.contains(&egui::ViewportCommand::Maximized(false)), "{cmds:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dispatch_uses_the_active_custom_preset() {
|
||||
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
|
||||
@@ -1992,6 +2085,41 @@ mod tests {
|
||||
assert_eq!(*asked.borrow(), ["project Frame.png"]);
|
||||
}
|
||||
|
||||
/// #511: with a host's non-blocking dialogs, a command's file dialog opens without running
|
||||
/// a nested event loop inside the frame (a drag over the window then aborted the app on
|
||||
/// macOS); the command runs on a later frame with the answer, and a cancelled one not at all.
|
||||
#[test]
|
||||
fn file_dialogs_can_answer_on_a_later_frame() {
|
||||
use std::sync::{Arc, Mutex};
|
||||
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
|
||||
app.session.execute("comp.new", json!({"name": "A", "width": 64, "height": 36, "frameRate": 30, "duration": 1})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
app.hooks.pick_save = Some(Box::new(|_: &str| panic!("the blocking dialog is not used")));
|
||||
let pending: Arc<Mutex<Vec<(crate::FileDialog, crate::DialogDone)>>> = Arc::default();
|
||||
let queue = pending.clone();
|
||||
app.hooks.file_dialog_async = Some(Box::new(move |dialog, done| queue.lock().unwrap().push((dialog, done))));
|
||||
assert_eq!(invoke(&mut app, &ctx, "file.saveAs", json!({})).unwrap(), json!({"dialog": "file.saveAs"}));
|
||||
let (dialog, done) = pending.lock().unwrap().pop().expect("a dialog was shown");
|
||||
assert_eq!(dialog, crate::FileDialog::Save { default: "Untitled Project.ecproj".into(), ext: "ecproj".into(), project: true });
|
||||
assert!(app.session.path.is_none(), "nothing saved until the dialog answers");
|
||||
let dir = std::env::temp_dir().join(format!("ec-dialog-answer-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("Answered.ecproj");
|
||||
// Answered from another thread, as the host's dialog does.
|
||||
std::thread::spawn(move || done(vec![path.to_string_lossy().to_string()])).join().unwrap();
|
||||
app.run_dialog_answers();
|
||||
assert_eq!(app.session.path.as_deref(), Some(dir.join("Answered.ecproj").to_string_lossy().as_ref()));
|
||||
assert!(dir.join("Answered.ecproj").is_file());
|
||||
// Cancelled: nothing runs.
|
||||
invoke(&mut app, &ctx, "comp.saveFrameAs", json!({})).unwrap();
|
||||
let (dialog, done) = pending.lock().unwrap().pop().expect("a dialog was shown");
|
||||
assert_eq!(dialog, crate::FileDialog::Save { default: "Frame.png".into(), ext: "png".into(), project: false });
|
||||
done(Vec::new());
|
||||
app.run_dialog_answers();
|
||||
assert!(!dir.join("Frame.png").exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn menu_items_cover_the_tree() {
|
||||
assert_eq!(menus().last(), Some(&"Help"));
|
||||
|
||||
@@ -215,8 +215,22 @@ pub fn viewer_hook(
|
||||
return;
|
||||
}
|
||||
// Interaction over the image.
|
||||
let resp = ui.interact(map.area, egui::Id::new("viewer-camera-tracker"), Sense::click_and_drag());
|
||||
// While Space (Hand tool) is held the overlay only hovers, so the viewer underneath gets the pan drag.
|
||||
let sense = if super::space_hand(&ctx) { Sense::hover() } else { Sense::click_and_drag() };
|
||||
let resp = ui.interact(map.area, egui::Id::new("viewer-camera-tracker"), sense);
|
||||
app.auto.add("viewer.cameraTracker", map.area, "3D Camera Tracker points");
|
||||
// The overlay is on top of the viewer, so a middle-button drag lands here: pan the viewer like the Hand tool.
|
||||
if resp.dragged_by(egui::PointerButton::Middle) {
|
||||
let pid = egui::Id::new("viewer-camera-tracker-pan");
|
||||
if resp.drag_started() {
|
||||
let start_pan = app.ui.viewer.pan;
|
||||
ui.data_mut(|d| d.insert_temp(pid, start_pan));
|
||||
}
|
||||
if let (Some(start_pan), Some(d)) = (ui.data(|m| m.get_temp::<[f32; 2]>(pid)), resp.total_drag_delta()) {
|
||||
app.ui.viewer.pan = [start_pan[0] + d.x, start_pan[1] + d.y];
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (id, sp, r) in hits.iter().take(400) {
|
||||
app.auto.add(&format!("viewer.cameraTracker.point.{id}"), Rect::from_center_size(*sp, vec2(r * 2.0 + 4.0, r * 2.0 + 4.0)), "track point");
|
||||
}
|
||||
|
||||
@@ -212,7 +212,7 @@ pub fn show(ui: &mut egui::Ui, d: &mut CompDraft, t: &Tokens, auto: &mut Registr
|
||||
ui.label(tr("Width:"));
|
||||
ui.horizontal(|ui| {
|
||||
let (ow, oh) = (d.width, d.height);
|
||||
let r = ui.add(egui::DragValue::new(&mut d.width).range(4..=30000).suffix(" px"));
|
||||
let r = ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut d.width).range(4..=30000).suffix(" px")));
|
||||
auto.add("dialog.comp.width", r.rect, "Width");
|
||||
let lbl = format!("Lock Aspect Ratio to {}", aspect_label(ow as f64, oh as f64));
|
||||
let r = ui.checkbox(&mut d.lock_aspect, lbl);
|
||||
@@ -224,7 +224,7 @@ pub fn show(ui: &mut egui::Ui, d: &mut CompDraft, t: &Tokens, auto: &mut Registr
|
||||
ui.end_row();
|
||||
ui.label(tr("Height:"));
|
||||
let (ow, oh) = (d.width, d.height);
|
||||
let r = ui.add(egui::DragValue::new(&mut d.height).range(4..=30000).suffix(" px"));
|
||||
let r = ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut d.height).range(4..=30000).suffix(" px")));
|
||||
auto.add("dialog.comp.height", r.rect, "Height");
|
||||
if d.lock_aspect && oh != d.height && oh > 0 {
|
||||
d.width = ((d.height as f64) * ow as f64 / oh as f64).round().max(4.0) as u32;
|
||||
@@ -254,7 +254,7 @@ pub fn show(ui: &mut egui::Ui, d: &mut CompDraft, t: &Tokens, auto: &mut Registr
|
||||
ui.label(tr("Frame Rate:"));
|
||||
ui.horizontal(|ui| {
|
||||
// Any rate can be typed; the list holds the common ones.
|
||||
let r = ui.add(egui::DragValue::new(&mut d.fps).range(1.0..=999.0).speed(0.01).max_decimals(3));
|
||||
let r = ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut d.fps).range(1.0..=999.0).speed(0.01).max_decimals(3)));
|
||||
auto.add("dialog.comp.frameRate", r.rect, "Frame Rate");
|
||||
let r = egui::ComboBox::from_id_salt("comp-fps").width(18.0).selected_text("").show_ui(ui, |ui| {
|
||||
for f in FRAME_RATES {
|
||||
@@ -320,19 +320,19 @@ pub fn show(ui: &mut egui::Ui, d: &mut CompDraft, t: &Tokens, auto: &mut Registr
|
||||
ui.label(egui::RichText::new(tr("Motion Blur")).strong());
|
||||
ui.end_row();
|
||||
ui.label(tr("Shutter Angle:"));
|
||||
let r = ui.add(egui::DragValue::new(&mut d.shutter_angle).range(0.0..=720.0).suffix("°"));
|
||||
let r = ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut d.shutter_angle).range(0.0..=720.0).suffix("°")));
|
||||
auto.add("dialog.comp.shutterAngle", r.rect, "Shutter Angle");
|
||||
ui.end_row();
|
||||
ui.label(tr("Shutter Phase:"));
|
||||
let r = ui.add(egui::DragValue::new(&mut d.shutter_phase).range(-360.0..=360.0).suffix("°"));
|
||||
let r = ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut d.shutter_phase).range(-360.0..=360.0).suffix("°")));
|
||||
auto.add("dialog.comp.shutterPhase", r.rect, "Shutter Phase");
|
||||
ui.end_row();
|
||||
ui.label(tr("Samples Per Frame:"));
|
||||
let r = ui.add(egui::DragValue::new(&mut d.samples).range(2..=64));
|
||||
let r = ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut d.samples).range(2..=64)));
|
||||
auto.add("dialog.comp.samples", r.rect, "Samples Per Frame");
|
||||
ui.end_row();
|
||||
ui.label(tr("Adaptive Sample Limit:"));
|
||||
let r = ui.add(egui::DragValue::new(&mut d.adaptive_limit).range(16..=256));
|
||||
let r = ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut d.adaptive_limit).range(16..=256)));
|
||||
auto.add("dialog.comp.adaptiveLimit", r.rect, "Adaptive Sample Limit");
|
||||
ui.end_row();
|
||||
});
|
||||
|
||||
@@ -361,14 +361,14 @@ fn solid(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
|
||||
let (ow, oh) = (size[0], size[1]);
|
||||
ui.label(tr("Width:"));
|
||||
ui.horizontal(|ui| {
|
||||
let r = ui.add(egui::DragValue::new(&mut size[0]).range(1..=30000).suffix(" px"));
|
||||
let r = ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut size[0]).range(1..=30000).suffix(" px")));
|
||||
auto.add("dialog.solid.width", r.rect, "Width");
|
||||
let r = ui.checkbox(&mut lock, tr_args("Lock Aspect Ratio to {}", &[&(super::comp_settings::aspect_label(ow as f64, oh as f64))]));
|
||||
auto.add("dialog.solid.lockAspect", r.rect, "Lock Aspect Ratio");
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label(tr("Height:"));
|
||||
let r = ui.add(egui::DragValue::new(&mut size[1]).range(1..=30000).suffix(" px"));
|
||||
let r = ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut size[1]).range(1..=30000).suffix(" px")));
|
||||
auto.add("dialog.solid.height", r.rect, "Height");
|
||||
ui.end_row();
|
||||
if lock && ow > 0 && oh > 0 {
|
||||
|
||||
@@ -188,13 +188,13 @@ pub fn camera(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
|
||||
ui.end_row();
|
||||
ui.label(tr("Zoom"));
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::DragValue::new(&mut d.zoom).range(1.0..=100000.0).speed(1.0).suffix(" px"));
|
||||
ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut d.zoom).range(1.0..=100000.0).speed(1.0).suffix(" px")));
|
||||
let mut aov = angle_of_view(w, d.zoom);
|
||||
if ui.add(egui::DragValue::new(&mut aov).range(0.1..=179.0).speed(0.1).suffix("°")).changed() {
|
||||
if ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut aov).range(0.1..=179.0).speed(0.1).suffix("°"))).changed() {
|
||||
d.zoom = w * 0.5 / (aov.to_radians() * 0.5).tan();
|
||||
}
|
||||
let mut fl = focal_for_zoom(w, d.zoom);
|
||||
if ui.add(egui::DragValue::new(&mut fl).range(0.1..=10000.0).speed(0.1).suffix(" mm")).changed() {
|
||||
if ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut fl).range(0.1..=10000.0).speed(0.1).suffix(" mm"))).changed() {
|
||||
d.zoom = zoom_for_focal(w, fl);
|
||||
}
|
||||
});
|
||||
@@ -204,15 +204,15 @@ pub fn camera(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
|
||||
ui.end_row();
|
||||
ui.label(tr("Focus Distance"));
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_enabled(!d.lock_to_zoom, egui::DragValue::new(&mut d.focus).range(0.0..=100000.0).suffix(" px"));
|
||||
ui.add_enabled(!d.lock_to_zoom, crate::widgets::drag_value(egui::DragValue::new(&mut d.focus).range(0.0..=100000.0).suffix(" px")));
|
||||
ui.checkbox(&mut d.lock_to_zoom, tr("Lock to Zoom"));
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label(tr("Aperture"));
|
||||
ui.add(egui::DragValue::new(&mut d.aperture).range(0.0..=10000.0).speed(0.1).suffix(" px"));
|
||||
ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut d.aperture).range(0.0..=10000.0).speed(0.1).suffix(" px")));
|
||||
ui.end_row();
|
||||
ui.label(tr("Blur Level"));
|
||||
ui.add(egui::DragValue::new(&mut d.blur).range(0.0..=10000.0).suffix(" %"));
|
||||
ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut d.blur).range(0.0..=10000.0).suffix(" %")));
|
||||
ui.end_row();
|
||||
});
|
||||
ui.add_space(14.0);
|
||||
@@ -268,18 +268,18 @@ pub fn light(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label(tr("Color"));
|
||||
ui.color_edit_button_rgb(&mut d.color);
|
||||
crate::widgets::srgb_color_button(ui, &mut d.color);
|
||||
ui.end_row();
|
||||
ui.label(tr("Intensity"));
|
||||
ui.add(egui::DragValue::new(&mut d.intensity).range(-10000.0..=10000.0).suffix(" %"));
|
||||
ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut d.intensity).range(-10000.0..=10000.0).suffix(" %")));
|
||||
ui.end_row();
|
||||
let kind = KINDS[d.kind.min(3)];
|
||||
if kind == LightKind::Spot {
|
||||
ui.label(tr("Cone Angle"));
|
||||
ui.add(egui::DragValue::new(&mut d.cone_angle).range(0.0..=180.0).suffix("°"));
|
||||
ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut d.cone_angle).range(0.0..=180.0).suffix("°")));
|
||||
ui.end_row();
|
||||
ui.label(tr("Cone Feather"));
|
||||
ui.add(egui::DragValue::new(&mut d.cone_feather).range(0.0..=100.0).suffix(" %"));
|
||||
ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut d.cone_feather).range(0.0..=100.0).suffix(" %")));
|
||||
ui.end_row();
|
||||
}
|
||||
if kind != LightKind::Ambient {
|
||||
@@ -292,20 +292,20 @@ pub fn light(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
|
||||
ui.end_row();
|
||||
if d.falloff > 0 {
|
||||
ui.label(tr("Radius"));
|
||||
ui.add(egui::DragValue::new(&mut d.radius).range(0.0..=100000.0).suffix(" px"));
|
||||
ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut d.radius).range(0.0..=100000.0).suffix(" px")));
|
||||
ui.end_row();
|
||||
ui.label(tr("Falloff Distance"));
|
||||
ui.add(egui::DragValue::new(&mut d.falloff_distance).range(0.0..=100000.0).suffix(" px"));
|
||||
ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut d.falloff_distance).range(0.0..=100000.0).suffix(" px")));
|
||||
ui.end_row();
|
||||
}
|
||||
ui.label(tr("Shadows"));
|
||||
ui.checkbox(&mut d.casts_shadows, tr("Casts Shadows"));
|
||||
ui.end_row();
|
||||
ui.label(tr("Shadow Darkness"));
|
||||
ui.add_enabled(d.casts_shadows, egui::DragValue::new(&mut d.shadow_darkness).range(0.0..=100.0).suffix(" %"));
|
||||
ui.add_enabled(d.casts_shadows, crate::widgets::drag_value(egui::DragValue::new(&mut d.shadow_darkness).range(0.0..=100.0).suffix(" %")));
|
||||
ui.end_row();
|
||||
ui.label(tr("Shadow Diffusion"));
|
||||
ui.add_enabled(d.casts_shadows, egui::DragValue::new(&mut d.shadow_diffusion).range(0.0..=1000.0).suffix(" px"));
|
||||
ui.add_enabled(d.casts_shadows, crate::widgets::drag_value(egui::DragValue::new(&mut d.shadow_diffusion).range(0.0..=1000.0).suffix(" px")));
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -79,6 +79,46 @@ pub fn reveal_applied(app: &mut EffectcraftApp, params: &serde_json::Value) {
|
||||
app.raise_panel(crate::dock::PanelKind::EffectControls);
|
||||
}
|
||||
|
||||
/// After Effects asks for an effect's file as it applies it (Apply Color LUT opens the file
|
||||
/// dialog for its LUT). For the instances `effect.apply` made (`applied`, its result), open the
|
||||
/// file dialog for their first empty file parameter and set the file on each; cancelling
|
||||
/// leaves the effect without one. Does nothing without a file dialog (tests, agents).
|
||||
pub fn choose_files_after_apply(app: &mut EffectcraftApp, applied: &serde_json::Value) {
|
||||
let Some(pick) = app.hooks.pick_files.as_ref() else { return };
|
||||
let Some(comp) = app.session.active_comp() else { return };
|
||||
let uids: Vec<u64> = applied.get("effects").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|v| v.as_u64()).collect()).unwrap_or_default();
|
||||
let mut targets = vec![];
|
||||
let mut filters: Vec<String> = vec![];
|
||||
for uid in uids {
|
||||
for l in &comp.layers {
|
||||
let Some(g) = l.props.find_group(uid) else { continue };
|
||||
let mut found = None;
|
||||
g.walk("", &mut |_, pr| {
|
||||
if found.is_none()
|
||||
&& let ParamUi::File { filters } = &pr.ui
|
||||
&& matches!(&pr.value, Value::Str(s) if s.trim().is_empty())
|
||||
{
|
||||
found = Some((pr.uid, filters.clone()));
|
||||
}
|
||||
});
|
||||
if let Some((prop, f)) = found {
|
||||
targets.push((l.id.0, prop));
|
||||
filters = f;
|
||||
}
|
||||
}
|
||||
}
|
||||
if targets.is_empty() {
|
||||
return;
|
||||
}
|
||||
let exts: Vec<&str> = filters.iter().map(String::as_str).collect();
|
||||
let Some(path) = pick(&exts).into_iter().next() else { return };
|
||||
for (layer, prop) in targets {
|
||||
if let Err(e) = app.session.execute("prop.set", json!({"layer": layer, "prop": prop, "value": path})) {
|
||||
app.ui.status = e.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An undo-merge key for one gesture on `id`: a new key each time a drag starts, so separate
|
||||
/// drags are separate undo steps while one drag is one step.
|
||||
pub(super) fn gesture_key(ui: &egui::Ui, id: egui::Id, started: bool) -> String {
|
||||
@@ -140,14 +180,15 @@ fn key_navigator(
|
||||
match what {
|
||||
"prev" => actions.push(("time.go".into(), json!({"to": "prevKey", "prop": uid}))),
|
||||
"next" => actions.push(("time.go".into(), json!({"to": "nextKey", "prop": uid}))),
|
||||
_ => actions.push(("prop.toggleKey".into(), json!({"layer": layer.id.0, "prop": uid}))),
|
||||
_ => actions.push(("prop.toggleKey".into(), json!({"layer": layer.id.0, "prop": uid, "selected": true}))),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Toggle a viewer pick (crosshair / eyedropper) for a parameter.
|
||||
fn toggle_pick(app: &mut EffectcraftApp, kind: &str, layer: &Layer, prop: &Property) {
|
||||
/// Toggle a viewer pick (crosshair / eyedropper) for a parameter (also the Timeline's colour
|
||||
/// eyedroppers).
|
||||
pub(crate) fn toggle_pick(app: &mut EffectcraftApp, kind: &str, layer: &Layer, prop: &Property) {
|
||||
let pick = FxPick { kind: kind.into(), layer: layer.id.0, prop: prop.uid, name: prop.name.clone() };
|
||||
if app.ui.fx_pick.as_ref() == Some(&pick) {
|
||||
app.ui.fx_pick = None;
|
||||
@@ -201,7 +242,7 @@ fn prop_row(
|
||||
);
|
||||
app.auto.add(&format!("effectControls.prop.{uid}.stopwatch"), swr, &prop.name);
|
||||
if resp.clicked() {
|
||||
actions.push(("prop.toggleAnimation".into(), json!({"layer": layer.id.0, "prop": uid})));
|
||||
actions.push(("prop.toggleAnimation".into(), json!({"layer": layer.id.0, "prop": uid, "selected": true})));
|
||||
}
|
||||
}
|
||||
if prop.is_animated() {
|
||||
@@ -233,8 +274,11 @@ fn prop_row(
|
||||
ui.interact(name_clip, egui::Id::new(("ec-prop-name", uid)), Sense::click());
|
||||
app.auto.add(&format!("effectControls.prop.{uid}.name"), name_clip, &prop.name);
|
||||
let merge = format!("ec-{uid}");
|
||||
let set =
|
||||
|actions: &mut Actions, v: serde_json::Value| actions.push(("prop.set".into(), json!({"layer": layer.id.0, "prop": uid, "value": v, "merge": merge})));
|
||||
// With several layers selected the edit applies to the same effect property of each (#491).
|
||||
let scrub = ui.ctx().dragged_id().is_some() && ui.input(|i| i.pointer.is_decidedly_dragging());
|
||||
let set = |actions: &mut Actions, v: serde_json::Value| {
|
||||
actions.push(("prop.set".into(), json!({"layer": layer.id.0, "prop": uid, "value": v, "merge": merge, "selected": true, "offset": scrub})))
|
||||
};
|
||||
let twirl_open = |app: &mut EffectcraftApp, ui: &mut egui::Ui| {
|
||||
let open = app.ui.fx_slider_open.contains(&uid);
|
||||
let tw = Rect::from_center_size(pos2(swr.min.x - 9.0, cy), vec2(10.0, 10.0));
|
||||
@@ -353,7 +397,7 @@ fn prop_row(
|
||||
}
|
||||
app.auto.add(&format!("effectControls.prop.{uid}.eyedropper"), er, &prop.name);
|
||||
let mut rgb = [c[0] as f32, c[1] as f32, c[2] as f32];
|
||||
if crate::header::color_popup(ui, pop, sr.left_bottom(), &mut rgb) {
|
||||
if crate::widgets::color_popup(ui, pop, sr.left_bottom(), &mut rgb) {
|
||||
set(actions, json!([rgb[0], rgb[1], rgb[2], 1.0]));
|
||||
}
|
||||
}
|
||||
@@ -417,6 +461,59 @@ fn prop_row(
|
||||
let dr = Rect::from_min_size(pos2(vx, cy - 9.0), vec2((r.max.x - vx - 56.0).clamp(80.0, 200.0), 18.0));
|
||||
super::fx_editors::channel_popup(app, ui, layer, prop, s, dr, actions);
|
||||
}
|
||||
// A file parameter (Apply Color LUT's LUT, an OCIO config): its file name and Choose…,
|
||||
// as in After Effects.
|
||||
Value::Str(s) if matches!(prop.ui, ParamUi::File { .. }) => {
|
||||
let bw = 70.0;
|
||||
let br = Rect::from_min_size(pos2(vx, cy - 9.0), vec2(bw, 18.0));
|
||||
if widgets::text_button(ui, br, crate::i18n::tr("Choose..."), false, &t, egui::Id::new(("ec-file", uid))).clicked() {
|
||||
let filters: Vec<&str> = match &prop.ui {
|
||||
ParamUi::File { filters } => filters.iter().map(String::as_str).collect(),
|
||||
_ => vec![],
|
||||
};
|
||||
match app.hooks.pick_files.as_ref() {
|
||||
Some(pick) => {
|
||||
if let Some(path) = pick(&filters).into_iter().next() {
|
||||
actions.push(("prop.set".into(), json!({"layer": layer.id.0, "prop": uid, "value": path})));
|
||||
}
|
||||
}
|
||||
None => app.ui.status = "no file dialog available: set the path with prop.set".into(),
|
||||
}
|
||||
}
|
||||
app.auto.add(&format!("effectControls.prop.{uid}.choose"), br, &prop.name);
|
||||
let shown = if s.trim().is_empty() {
|
||||
crate::i18n::tr("None").to_string()
|
||||
} else if s.contains('\n') {
|
||||
prop.name.clone()
|
||||
} else {
|
||||
effectcraft_engine::sequence::file_name(s)
|
||||
};
|
||||
let nr = Rect::from_min_max(pos2(br.max.x + 8.0, r.min.y), pos2(r.max.x - 8.0, r.max.y));
|
||||
let np = p.with_clip_rect(nr.intersect(p.clip_rect()));
|
||||
np.text(pos2(nr.min.x, cy), Align2::LEFT_CENTER, &shown, Tokens::ui(12.0), if s.trim().is_empty() { t.text_dim } else { t.text });
|
||||
let hover = ui.interact(nr, egui::Id::new(("ec-file-name", uid)), Sense::hover());
|
||||
if !s.trim().is_empty() && !s.contains('\n') {
|
||||
hover.on_hover_text(s.as_str());
|
||||
}
|
||||
app.auto.add(&format!("effectControls.prop.{uid}.value"), nr, &shown);
|
||||
}
|
||||
// A text parameter (Cryptomatte's Selection, Colorama's Output Cycle, config names):
|
||||
// typed in a field, set when it loses the focus (Esc keeps the old text).
|
||||
Value::Str(s) if matches!(prop.ui, ParamUi::Text) => {
|
||||
let fr = Rect::from_min_size(pos2(vx, cy - 9.0), vec2((r.max.x - vx - 12.0).clamp(80.0, 320.0), 18.0));
|
||||
let bid = egui::Id::new(("ec-text", uid));
|
||||
let mut buf: String = ui.data(|d| d.get_temp(bid)).unwrap_or_else(|| s.clone());
|
||||
let resp = widgets::text_field(ui, fr, &mut buf, "", &t);
|
||||
app.auto.add(&format!("effectControls.prop.{uid}.value"), fr, &prop.name);
|
||||
if resp.lost_focus() {
|
||||
if buf != *s && !ui.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
actions.push(("prop.set".into(), json!({"layer": layer.id.0, "prop": uid, "value": buf})));
|
||||
}
|
||||
ui.data_mut(|d| d.remove::<String>(bid));
|
||||
} else if resp.has_focus() {
|
||||
ui.data_mut(|d| d.insert_temp(bid, buf));
|
||||
}
|
||||
}
|
||||
Value::Gradient(g) => {
|
||||
let gr = Rect::from_min_size(pos2(vx, cy - 7.0), vec2((r.max.x - vx - 56.0).clamp(60.0, 180.0), 14.0));
|
||||
let n = 48;
|
||||
@@ -1008,7 +1105,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let open = !app.ui.fx_closed.contains(&g.uid);
|
||||
let selected = app.session.state.selected_props.iter().any(|(l, u)| *l == layer.id && *u == g.uid);
|
||||
let active = effect_active(g, layer.id, &app.session.state.selected_props);
|
||||
bp.rect_filled(r, 0.0, if active { Color32::from_rgb(0x2f, 0x3a, 0x52) } else { Color32::from_rgb(0x2a, 0x2a, 0x2a) });
|
||||
bp.rect_filled(r, 0.0, if active { t.fx_header_active } else { t.fx_header });
|
||||
let fxr = Rect::from_center_size(pos2(r.min.x + 14.0, r.center().y), vec2(16.0, 16.0));
|
||||
if widgets::icon_toggle(ui, fxr, Icon::Fx, g.enabled, &t, egui::Id::new(("ec-fx", g.uid)), Sense::click()).clicked() {
|
||||
actions.push(("effect.toggle".into(), json!({"layer": layer.id.0, "effect": g.uid})));
|
||||
|
||||
@@ -422,11 +422,12 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
};
|
||||
match app.session.execute(cmd, params) {
|
||||
Err(e) => app.ui.status = e.to_string(),
|
||||
Ok(_) => {
|
||||
Ok(applied) => {
|
||||
if let Apply::Effect(id) = &apply {
|
||||
push_recent(&mut app.ui.effects_recent, id);
|
||||
app.show_panel(crate::dock::PanelKind::EffectControls);
|
||||
app.ui.focused = crate::dock::PanelKind::EffectsPresets;
|
||||
crate::panels::effect_controls::choose_files_after_apply(app, &applied);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -344,11 +344,10 @@ fn value_widget(app: &mut EffectcraftApp, ui: &mut egui::Ui, auto: &str, ty: Opt
|
||||
}
|
||||
ControlType::Color => {
|
||||
let c = v.as_color();
|
||||
let mut rgba = egui::Rgba::from_rgba_unmultiplied(c[0], c[1], c[2], c[3]);
|
||||
let r = egui::widgets::color_picker::color_edit_button_rgba(ui, &mut rgba, egui::widgets::color_picker::Alpha::Opaque);
|
||||
let mut rgb = [c[0], c[1], c[2]];
|
||||
let r = crate::widgets::srgb_color_button(ui, &mut rgb);
|
||||
if r.changed() {
|
||||
let u = rgba.to_rgba_unmultiplied();
|
||||
out = Some(json!([u[0], u[1], u[2], u[3]]));
|
||||
out = Some(json!([rgb[0], rgb[1], rgb[2], c[3]]));
|
||||
}
|
||||
r.rect
|
||||
}
|
||||
@@ -375,10 +374,41 @@ fn value_widget(app: &mut EffectcraftApp, ui: &mut egui::Ui, auto: &str, ty: Opt
|
||||
});
|
||||
r.response.rect
|
||||
}
|
||||
// Scale keeps its Constrain Proportions link, on by default, as in After Effects (#338).
|
||||
// The link is the property's own, shared with the Timeline's chain link.
|
||||
ControlType::Point if p.match_id == "scale" && matches!(p.ui, ParamUi::Percent) => {
|
||||
let comps = v.components();
|
||||
let linked = !app.ui.timeline.unlinked.contains(&p.uid);
|
||||
let (lr, link) = ui.allocate_exact_size(egui::vec2(14.0, 14.0), egui::Sense::click());
|
||||
let t = app.tokens;
|
||||
crate::icons::paint(ui.painter(), lr, crate::icons::Icon::Link, if linked { t.accent } else { t.text_faint });
|
||||
let link = link.on_hover_text(tr("Constrain Proportions"));
|
||||
app.auto.add(&format!("{auto}.link"), lr, "Constrain Proportions");
|
||||
if link.clicked() && !app.ui.timeline.unlinked.remove(&p.uid) {
|
||||
app.ui.timeline.unlinked.insert(p.uid);
|
||||
}
|
||||
let mut rect = lr;
|
||||
for (d, &old) in comps.iter().enumerate() {
|
||||
let mut x = old;
|
||||
let r = ui.add(egui::DragValue::new(&mut x).speed(0.5).suffix(if d + 1 == comps.len() { "%" } else { "" }).max_decimals(1));
|
||||
app.auto.add(&format!("{auto}.{d}"), r.rect, &p.name);
|
||||
rect = rect.union(r.rect);
|
||||
if r.changed() {
|
||||
// Alt edits one value of a linked pair, as in the Timeline.
|
||||
let next = if linked && !ui.input(|i| i.modifiers.alt) {
|
||||
widgets::constrained(&comps, d, x)
|
||||
} else {
|
||||
comps.iter().enumerate().map(|(e, &c)| if e == d { x } else { c }).collect()
|
||||
};
|
||||
out = Some(json!(next));
|
||||
}
|
||||
}
|
||||
rect
|
||||
}
|
||||
ControlType::Point => {
|
||||
let mut a = v.as_vec2();
|
||||
let r1 = ui.add(egui::DragValue::new(&mut a[0]).speed(1.0).max_decimals(1));
|
||||
let r2 = ui.add(egui::DragValue::new(&mut a[1]).speed(1.0).max_decimals(1));
|
||||
let r1 = ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut a[0]).speed(1.0).max_decimals(1)));
|
||||
let r2 = ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut a[1]).speed(1.0).max_decimals(1)));
|
||||
if r1.changed() || r2.changed() {
|
||||
out = Some(json!(a));
|
||||
}
|
||||
@@ -386,7 +416,7 @@ fn value_widget(app: &mut EffectcraftApp, ui: &mut egui::Ui, auto: &str, ty: Opt
|
||||
}
|
||||
ControlType::Angle => {
|
||||
let mut a = v.as_f64();
|
||||
let r = ui.add(egui::DragValue::new(&mut a).speed(1.0).suffix("°").max_decimals(1));
|
||||
let r = ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut a).speed(1.0).suffix("°").max_decimals(1)));
|
||||
if r.changed() {
|
||||
out = Some(json!(a));
|
||||
}
|
||||
@@ -415,7 +445,7 @@ fn value_widget(app: &mut EffectcraftApp, ui: &mut egui::Ui, auto: &str, ty: Opt
|
||||
}
|
||||
}
|
||||
});
|
||||
let r3 = ui.add(egui::DragValue::new(&mut d.size).speed(0.5).range(1.0..=2000.0).suffix(" px").max_decimals(1));
|
||||
let r3 = ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut d.size).speed(0.5).range(1.0..=2000.0).suffix(" px").max_decimals(1)));
|
||||
app.auto.add(&format!("{auto}.font"), r1.response.rect, "Font");
|
||||
app.auto.add(&format!("{auto}.style"), r2.response.rect, "Style");
|
||||
app.auto.add(&format!("{auto}.size"), r3.rect, "Size");
|
||||
@@ -428,7 +458,7 @@ fn value_widget(app: &mut EffectcraftApp, ui: &mut egui::Ui, auto: &str, ty: Opt
|
||||
// One percentage for every axis.
|
||||
let comps = v.components();
|
||||
let mut x = comps.first().copied().unwrap_or(100.0);
|
||||
let r = ui.add(egui::DragValue::new(&mut x).speed(0.5).suffix("%").max_decimals(1));
|
||||
let r = ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut x).speed(0.5).suffix("%").max_decimals(1)));
|
||||
if r.changed() {
|
||||
out = Some(json!(vec![x; comps.len().max(1)]));
|
||||
}
|
||||
@@ -438,7 +468,7 @@ fn value_widget(app: &mut EffectcraftApp, ui: &mut egui::Ui, auto: &str, ty: Opt
|
||||
let mut x = v.as_f64();
|
||||
let r = match p.ui {
|
||||
ParamUi::Slider { slider_min, slider_max, .. } => ui.add(egui::Slider::new(&mut x, slider_min..=slider_max).max_decimals(2)),
|
||||
_ => ui.add(egui::DragValue::new(&mut x).speed(0.5).max_decimals(2)),
|
||||
_ => ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut x).speed(0.5).max_decimals(2))),
|
||||
};
|
||||
if r.changed() {
|
||||
out = Some(json!(x));
|
||||
|
||||
@@ -9,13 +9,42 @@ 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);
|
||||
/// Syntax colours, and the matched brackets' background.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Syntax {
|
||||
pub keyword: Color32,
|
||||
pub number: Color32,
|
||||
pub string: Color32,
|
||||
pub comment: Color32,
|
||||
pub api: Color32,
|
||||
pub bracket_bg: Color32,
|
||||
}
|
||||
|
||||
impl Syntax {
|
||||
/// The colours for the theme: on the Light theme's light expression field, darker ones that
|
||||
/// stay readable (#644).
|
||||
pub fn for_tokens(t: &Tokens) -> Syntax {
|
||||
if t.kind.is_light() {
|
||||
Syntax {
|
||||
keyword: Color32::from_rgb(0x7a, 0x2f, 0xa8),
|
||||
number: Color32::from_rgb(0x8a, 0x4b, 0x00),
|
||||
string: Color32::from_rgb(0x2c, 0x6a, 0x10),
|
||||
comment: Color32::from_rgb(0x52, 0x5a, 0x62),
|
||||
api: Color32::from_rgb(0x0a, 0x57, 0x94),
|
||||
bracket_bg: Color32::from_rgb(0xd0, 0xdc, 0xf0),
|
||||
}
|
||||
} else {
|
||||
Syntax {
|
||||
keyword: Color32::from_rgb(0xc6, 0x8a, 0xe6),
|
||||
number: Color32::from_rgb(0xe0, 0xb4, 0x6c),
|
||||
string: Color32::from_rgb(0x9c, 0xd0, 0x7a),
|
||||
comment: Color32::from_rgb(0x80, 0x88, 0x90),
|
||||
api: Color32::from_rgb(0x6c, 0xb8, 0xf0),
|
||||
bracket_bg: Color32::from_rgb(0x4a, 0x55, 0x6a),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const KEYWORDS: &[&str] = &[
|
||||
"var",
|
||||
@@ -184,7 +213,7 @@ pub fn completions(text: &str, cursor: usize) -> (String, Vec<&'static str>) {
|
||||
}
|
||||
|
||||
/// Colour runs for JavaScript: (byte start, byte end, colour).
|
||||
pub fn highlight(text: &str, base: Color32) -> Vec<(usize, usize, Color32)> {
|
||||
pub fn highlight(text: &str, base: Color32, sx: &Syntax) -> Vec<(usize, usize, Color32)> {
|
||||
let b = text.as_bytes();
|
||||
let mut out = vec![];
|
||||
let mut i = 0;
|
||||
@@ -195,35 +224,35 @@ pub fn highlight(text: &str, base: Color32) -> Vec<(usize, usize, Color32)> {
|
||||
while i < b.len() && b[i] != b'\n' {
|
||||
i += 1;
|
||||
}
|
||||
COMMENT
|
||||
sx.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
|
||||
sx.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
|
||||
sx.string
|
||||
} else if c.is_ascii_digit() {
|
||||
while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'.') {
|
||||
i += 1;
|
||||
}
|
||||
NUMBER
|
||||
sx.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
|
||||
sx.keyword
|
||||
} else if COMPLETIONS.contains(&w) {
|
||||
API
|
||||
sx.api
|
||||
} else {
|
||||
base
|
||||
}
|
||||
@@ -246,9 +275,9 @@ fn byte_of(text: &str, ci: usize) -> usize {
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
fn layout(text: &str, font: FontId, base: Color32, sx: &Syntax, 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 runs = if p.syntax_highlighting { highlight(text, base, sx) } 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.
|
||||
@@ -263,7 +292,7 @@ fn layout(text: &str, font: FontId, base: Color32, p: &Scripting, brackets: Opti
|
||||
cuts.sort_unstable();
|
||||
cuts.dedup();
|
||||
for w in cuts.windows(2) {
|
||||
let bg = if marks.contains(&w[0]) { BRACKET_BG } else { Color32::TRANSPARENT };
|
||||
let bg = if marks.contains(&w[0]) { sx.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() });
|
||||
}
|
||||
}
|
||||
@@ -281,8 +310,9 @@ pub fn editor(ui: &mut egui::Ui, id: egui::Id, buf: &mut String, rect: Rect, p:
|
||||
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 sx = Syntax::for_tokens(t);
|
||||
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);
|
||||
let job = layout(text.as_str(), font.clone(), color, &sx, &pc, brackets, wrap);
|
||||
ui.fonts_mut(|f| f.layout_job(job))
|
||||
};
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(er));
|
||||
@@ -392,3 +422,70 @@ pub fn error_banner(app: &mut crate::EffectcraftApp, ui: &egui::Ui, area: Rect)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod contrast_tests {
|
||||
use super::*;
|
||||
use crate::theme::ThemeKind;
|
||||
|
||||
/// WCAG contrast ratio of two opaque sRGB colours.
|
||||
fn contrast(a: Color32, b: Color32) -> f32 {
|
||||
let lum = |c: Color32| {
|
||||
let f = |v: u8| {
|
||||
let v = v as f32 / 255.0;
|
||||
if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
|
||||
};
|
||||
0.2126 * f(c.r()) + 0.7152 * f(c.g()) + 0.0722 * f(c.b())
|
||||
};
|
||||
let (x, y) = (lum(a), lum(b));
|
||||
(x.max(y) + 0.05) / (x.min(y) + 0.05)
|
||||
}
|
||||
|
||||
/// #644: on every theme, effect names stay readable on Effect Controls' headers, and the
|
||||
/// expression field's text (every syntax colour, enabled and disabled expressions, matched
|
||||
/// brackets, line numbers) on its background; the switch icons show on their wells.
|
||||
#[test]
|
||||
fn custom_painted_surfaces_keep_text_readable_on_every_theme() {
|
||||
for kind in [ThemeKind::Dark, ThemeKind::Darker, ThemeKind::Light] {
|
||||
let t = Tokens::for_kind(kind);
|
||||
let sx = Syntax::for_tokens(&t);
|
||||
for (what, bg) in [("effect header", t.fx_header), ("active effect header", t.fx_header_active)] {
|
||||
assert!(contrast(t.text, bg) >= 4.5, "{kind:?}: effect name on {what}: {:.2}", contrast(t.text, bg));
|
||||
}
|
||||
assert!(contrast(t.icon, t.switch_well) >= 3.0, "{kind:?}: switch icons on their wells");
|
||||
if !kind.is_light() {
|
||||
continue;
|
||||
}
|
||||
let fg = [
|
||||
("keyword", sx.keyword),
|
||||
("number", sx.number),
|
||||
("string", sx.string),
|
||||
("comment", sx.comment),
|
||||
("api", sx.api),
|
||||
("enabled expression", t.expr_text),
|
||||
("disabled expression", t.text_dim),
|
||||
("line numbers", t.text_faint),
|
||||
];
|
||||
for (what, c) in fg {
|
||||
assert!(contrast(c, t.expr_bg) >= 4.5, "{kind:?}: {what} on the expression field: {:.2}", contrast(c, t.expr_bg));
|
||||
assert!(contrast(c, sx.bracket_bg) >= 4.0, "{kind:?}: {what} on a matched bracket: {:.2}", contrast(c, sx.bracket_bg));
|
||||
}
|
||||
// The dark theme's syntax colours would not do on the light field.
|
||||
let dark = Syntax::for_tokens(&Tokens::for_kind(ThemeKind::Dark));
|
||||
assert!([dark.keyword, dark.number, dark.string, dark.api].iter().all(|c| contrast(*c, t.expr_bg) < 4.5));
|
||||
}
|
||||
}
|
||||
|
||||
/// Syntax highlighting uses the theme's colours.
|
||||
#[test]
|
||||
fn highlight_uses_the_theme_palette() {
|
||||
let t = Tokens::for_kind(ThemeKind::Light);
|
||||
let sx = Syntax::for_tokens(&t);
|
||||
let text = "var amount = 12; // note";
|
||||
let runs = highlight(text, t.expr_text, &sx);
|
||||
let col = |s: &str| runs.iter().find(|(a, e, _)| text.get(*a..*e) == Some(s)).map(|r| r.2);
|
||||
assert_eq!(col("var"), Some(sx.keyword));
|
||||
assert_eq!(col("12"), Some(sx.number));
|
||||
assert_eq!(col("// note"), Some(sx.comment));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -154,8 +154,9 @@ fn is_pdf(p: &Value) -> bool {
|
||||
/// File ▸ Import ▸ File… picked numbered stills that import as image sequences: ask, as After
|
||||
/// Effects' "<format> Sequence" checkbox in its Import dialog does (rfd's native dialog can't
|
||||
/// carry a checkbox), with Force Alphabetical Order and the frame rate. `p`: the import's
|
||||
/// parameters. Returns whether the dialog opened. Dropped files and agents' `file.import`
|
||||
/// don't ask (`sequence` defaults to on).
|
||||
/// parameters. Returns whether the dialog opened. The checkbox starts off, as in After Effects:
|
||||
/// unticked, the picked files import as stills. Dropped files and agents' `file.import` don't
|
||||
/// ask (files import as stills, folders' runs as sequences).
|
||||
pub fn open_import_sequence(app: &mut EffectcraftApp, p: &Value) -> bool {
|
||||
if has(p, &["sequence", "alphabetical"]) {
|
||||
return false;
|
||||
@@ -187,7 +188,7 @@ fn sequence_fields(app: &EffectcraftApp, runs: &[Vec<String>]) -> Vec<Field> {
|
||||
};
|
||||
vec![
|
||||
Field::note("note", ¬e),
|
||||
Field::bool("sequence", &format!("{ext} Sequence"), true),
|
||||
Field::bool("sequence", &format!("{ext} Sequence"), false),
|
||||
Field::bool("alphabetical", "Force alphabetical order", false),
|
||||
Field::num("frameRate", "Frame rate (fps)", app.session.prefs.import.sequence_fps),
|
||||
Field::note("after", "Change the frame rate, alpha and start frame later with File ▸ Interpret Footage."),
|
||||
@@ -546,6 +547,8 @@ pub fn open_form(app: &mut EffectcraftApp, id: &str, p: &Value) -> bool {
|
||||
],
|
||||
st.working_space.map_or(0, |c| 1 + effectcraft_engine::project::ColorSpace::WORKING.iter().position(|x| *x == c).unwrap_or(0)),
|
||||
),
|
||||
// With Working Space None (After Effects' Working Gamma, 2.2 or 2.4).
|
||||
Field::choice("workingGamma", "Working gamma", &[("2.2", json!(2.2)), ("2.4", json!(2.4))], usize::from(st.working_gamma_24())),
|
||||
Field::bool("linearize", "Linearize working space", st.linearize),
|
||||
Field::bool("blendLinear", "Blend colors using 1.0 gamma", st.blend_linear),
|
||||
Field::choice(
|
||||
@@ -771,7 +774,7 @@ pub fn show_form(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
|
||||
let r = match &mut fl.kind {
|
||||
FieldKind::Number { value, speed } => {
|
||||
let dec = if *speed < 0.01 { 5 } else { 3 };
|
||||
ui.add(egui::DragValue::new(value).speed(*speed).max_decimals(dec)).rect
|
||||
ui.add(crate::widgets::drag_value(egui::DragValue::new(value).speed(*speed).max_decimals(dec))).rect
|
||||
}
|
||||
FieldKind::Text(s) => ui.add(egui::TextEdit::singleline(s).desired_width(220.0)).rect,
|
||||
FieldKind::Path { value, .. } => {
|
||||
|
||||
@@ -581,7 +581,7 @@ fn colorama_wheel(
|
||||
t.text_dim,
|
||||
);
|
||||
let mut rgb = [col[0], col[1], col[2]];
|
||||
if crate::header::color_popup(ui, pop, sr.left_bottom(), &mut rgb) {
|
||||
if crate::widgets::color_popup(ui, pop, sr.left_bottom(), &mut rgb) {
|
||||
let mut st = pal.stops.clone();
|
||||
st[sel].1 = [rgb[0], rgb[1], rgb[2], col[3]];
|
||||
new_stops = Some(st);
|
||||
|
||||
@@ -41,6 +41,17 @@ pub fn parse_angle(s: &str) -> Option<f64> {
|
||||
s.parse().ok()
|
||||
}
|
||||
|
||||
/// The angle after the degrees field of `v` (which shows `shown`, the remainder's size) went to
|
||||
/// `new`. A drag moves the angle by the pointer's distance, so it runs through zero into negative
|
||||
/// angles; a typed number is a size, so the remainder keeps its sign.
|
||||
fn degrees_edit(v: f64, shown: f64, new: f64, dragging: bool) -> f64 {
|
||||
if dragging {
|
||||
return v + (new - shown);
|
||||
}
|
||||
let (rev, deg) = split_angle(v);
|
||||
rev as f64 * 360.0 + if deg < 0.0 || (deg == 0.0 && v < 0.0) { -new } else { new }
|
||||
}
|
||||
|
||||
/// An angle value, `0x+45.0°`, at `at` (top left): the revolutions and the degrees
|
||||
/// are hot numbers of their own (drag to scrub, click to type) and changing one keeps the other.
|
||||
/// Returns the revolutions' rect, the degrees' rect and the new angle when either changed.
|
||||
@@ -49,10 +60,10 @@ pub fn angle_field(ui: &mut egui::Ui, at: Pos2, id: egui::Id, v: f64, decimals:
|
||||
let (rr, new_rev, _) = widgets::hot_int_at(ui, at, id.with("rev"), rev, 0.1, "x", t);
|
||||
let sign = ui.painter().text(pos2(rr.max.x - 2.0, rr.center().y), Align2::LEFT_CENTER, if deg < 0.0 { "-" } else { "+" }, Tokens::ui(12.0), t.hot_text);
|
||||
let (dr, new_deg, _) = widgets::hot_number_at(ui, pos2(sign.max.x - 2.0, at.y), id, deg.abs(), 0.5, (-1e9, 1e9), decimals, "°", t);
|
||||
let dragging = new_deg.is_some() && ui.ctx().is_being_dragged(id);
|
||||
let out = match (new_rev, new_deg) {
|
||||
(Some(r), _) => Some(r as f64 * 360.0 + deg),
|
||||
// The degrees field shows the remainder's size; its sign stays.
|
||||
(None, Some(d)) => Some(rev as f64 * 360.0 + if deg < 0.0 || (deg == 0.0 && v < 0.0) { -d } else { d }),
|
||||
(None, Some(d)) => Some(degrees_edit(v, deg.abs(), d, dragging)),
|
||||
(None, None) => None,
|
||||
};
|
||||
(rr, dr, out)
|
||||
@@ -551,6 +562,23 @@ mod tests {
|
||||
assert_eq!(split_angle(-360.0), (-1, 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dragging_degrees_crosses_zero_into_negative_angles() {
|
||||
// The field shows the size (0.3), so a 1-degree drag left lands on -0.7, and keeps going.
|
||||
let mut v = 0.3;
|
||||
for _ in 0..3 {
|
||||
let (_, deg) = split_angle(v);
|
||||
v = degrees_edit(v, deg.abs(), deg.abs() - 1.0, true);
|
||||
}
|
||||
assert!((v + 2.7).abs() < 1e-9, "{v}");
|
||||
// And back up through zero.
|
||||
let (_, deg) = split_angle(v);
|
||||
assert!((degrees_edit(v, deg.abs(), deg.abs() + 3.0, true) - 0.3).abs() < 1e-9);
|
||||
// Typing keeps the sign shown.
|
||||
assert_eq!(degrees_edit(-30.0, 30.0, 45.0, false), -45.0);
|
||||
assert_eq!(degrees_edit(405.0, 45.0, 10.0, false), 370.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn angle_parsing_round_trips() {
|
||||
for v in [0.0, 45.0, 405.0, -30.5, -400.0, 1080.25] {
|
||||
|
||||
@@ -14,8 +14,8 @@ use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
|
||||
use serde_json::json;
|
||||
|
||||
use super::timeline::TMap;
|
||||
use crate::EffectcraftApp;
|
||||
use crate::theme::Tokens;
|
||||
use crate::{EffectcraftApp, widgets};
|
||||
|
||||
type Actions = Vec<(String, serde_json::Value)>;
|
||||
|
||||
@@ -162,10 +162,88 @@ fn curves<'a>(app: &EffectcraftApp, comp: &'a Comp, ectx: &EvalCtx, tm: TMap, pl
|
||||
out
|
||||
}
|
||||
|
||||
fn text_button(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, x: &mut f32, y: f32, label: &str, on: bool, id: &str, tip: &str) -> bool {
|
||||
/// The Graph Editor's button bar, laid out left to right. Buttons that would run past the right
|
||||
/// edge (a Timeline narrower than the whole row, #457) go to the "»" menu at its end instead of
|
||||
/// being clipped, so every one stays reachable.
|
||||
struct ButtonBar {
|
||||
x: f32,
|
||||
/// Where the next button must end to stay on the bar (the "»" button's room is kept free).
|
||||
limit: f32,
|
||||
/// Buttons moved to the "»" menu: (automation id, label, on, tooltip).
|
||||
hidden: Vec<(String, String, bool, String)>,
|
||||
/// The id picked from the "»" menu last frame, run by its button this frame.
|
||||
chosen: Option<String>,
|
||||
}
|
||||
|
||||
/// The "»" menu's popup and the id it picked (read by the next frame's buttons).
|
||||
const MORE_POPUP: &str = "graph-more";
|
||||
|
||||
impl ButtonBar {
|
||||
const MORE_W: f32 = 24.0;
|
||||
|
||||
fn new(ctx: &egui::Context, bar: Rect) -> Self {
|
||||
let chosen = ctx.data_mut(|d| d.remove_temp::<String>(egui::Id::new(MORE_POPUP).with("chosen")));
|
||||
ButtonBar { x: bar.min.x + 8.0, limit: bar.max.x - 8.0 - Self::MORE_W - 4.0, hidden: Vec::new(), chosen }
|
||||
}
|
||||
|
||||
/// The "»" button and its menu, when buttons did not fit.
|
||||
fn more(&mut self, app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, bar: Rect) {
|
||||
if self.hidden.is_empty() {
|
||||
return;
|
||||
}
|
||||
let t = app.tokens;
|
||||
let r = Rect::from_min_size(pos2(bar.max.x - 8.0 - Self::MORE_W, bar.center().y - 9.0), vec2(Self::MORE_W, 18.0));
|
||||
let pid = egui::Id::new(MORE_POPUP);
|
||||
let resp = ui.interact(r, pid.with("button"), Sense::click()).on_hover_text(crate::i18n::tr("More"));
|
||||
p.rect_filled(r, 3.0, if resp.hovered() { t.hover } else { Color32::from_rgb(0x2c, 0x2c, 0x2c) });
|
||||
p.text(r.center(), Align2::CENTER_CENTER, "»", Tokens::ui(12.0), t.text);
|
||||
app.auto.add("timeline.graph.more", r, "More");
|
||||
if resp.clicked() {
|
||||
let open = widgets::popup_is_open(ui, pid);
|
||||
ui.data_mut(|d| d.insert_temp(pid.with("open"), !open));
|
||||
}
|
||||
if !widgets::popup_is_open(ui, pid) {
|
||||
return;
|
||||
}
|
||||
let rows = self.hidden.len();
|
||||
let pos = r.left_top() - vec2(0.0, rows as f32 * 22.0 + 18.0);
|
||||
let chosen = widgets::popup_list(ui, pid, pos, r, rows, 0, |ui| {
|
||||
let mut chosen = None;
|
||||
for (id, label, on, tip) in &self.hidden {
|
||||
let item = ui.selectable_label(*on, label.as_str()).on_hover_text(tip.as_str());
|
||||
app.auto.add(&format!("timeline.graph.more.{id}"), item.rect, tip);
|
||||
if item.clicked() {
|
||||
chosen = Some(id.clone());
|
||||
}
|
||||
}
|
||||
chosen
|
||||
});
|
||||
if let Some(id) = chosen {
|
||||
ui.data_mut(|d| d.insert_temp(pid.with("chosen"), id));
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn text_button(
|
||||
app: &mut EffectcraftApp,
|
||||
ui: &mut egui::Ui,
|
||||
p: &egui::Painter,
|
||||
bar: &mut ButtonBar,
|
||||
y: f32,
|
||||
label: &str,
|
||||
on: bool,
|
||||
id: &str,
|
||||
tip: &str,
|
||||
) -> bool {
|
||||
let t = app.tokens;
|
||||
let w = p.layout_no_wrap(label.to_string(), Tokens::ui(11.0), t.text).size().x + 14.0;
|
||||
let r = Rect::from_min_size(pos2(*x, y - 9.0), vec2(w, 18.0));
|
||||
// Once one button overflows, the rest follow it into the menu (they keep their order).
|
||||
if !bar.hidden.is_empty() || bar.x + w > bar.limit {
|
||||
bar.hidden.push((id.to_string(), label.to_string(), on, tip.to_string()));
|
||||
return bar.chosen.as_deref() == Some(id);
|
||||
}
|
||||
let r = Rect::from_min_size(pos2(bar.x, y - 9.0), vec2(w, 18.0));
|
||||
let resp = ui.interact(r, egui::Id::new(("graph-btn", id)), Sense::click()).on_hover_text(tip);
|
||||
p.rect_filled(
|
||||
r,
|
||||
@@ -180,7 +258,7 @@ fn text_button(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, x
|
||||
);
|
||||
p.text(r.center(), Align2::CENTER_CENTER, label, Tokens::ui(11.0), if on { Color32::WHITE } else { t.text });
|
||||
app.auto.add(&format!("timeline.graph.{id}"), r, tip);
|
||||
*x += w + 4.0;
|
||||
bar.x += w + 4.0;
|
||||
resp.clicked()
|
||||
}
|
||||
|
||||
@@ -446,14 +524,14 @@ pub(crate) fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painte
|
||||
p.rect_filled(bar, 0.0, t.panel_bg);
|
||||
p.line_segment([bar.left_top(), bar.right_top()], Stroke::new(1.0, t.separator));
|
||||
let y = bar.center().y;
|
||||
let mut x = bar.min.x + 8.0;
|
||||
let mut buttons = ButtonBar::new(&ctx, bar);
|
||||
let tl = &app.ui.timeline;
|
||||
let (auto_type, show_sel, auto_on) = (tl.graph_mode == "auto", tl.graph_show_selected, tl.graph_auto_zoom);
|
||||
if text_button(
|
||||
app,
|
||||
ui,
|
||||
p,
|
||||
&mut x,
|
||||
&mut buttons,
|
||||
y,
|
||||
"Auto",
|
||||
auto_type,
|
||||
@@ -463,45 +541,45 @@ pub(crate) fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painte
|
||||
app.ui.timeline.graph_mode = if auto_type { if speed { "speed" } else { "value" } } else { "auto" }.into();
|
||||
}
|
||||
// Choosing a graph type turns Auto-Select off, as in After Effects.
|
||||
if text_button(app, ui, p, &mut x, y, "Value", !speed, "valueGraph", "Edit Value Graph") {
|
||||
if text_button(app, ui, p, &mut buttons, y, "Value", !speed, "valueGraph", "Edit Value Graph") {
|
||||
app.ui.timeline.graph_mode = "value".into();
|
||||
}
|
||||
if text_button(app, ui, p, &mut x, y, "Speed", speed, "speedGraph", "Edit Speed Graph") {
|
||||
if text_button(app, ui, p, &mut buttons, y, "Speed", speed, "speedGraph", "Edit Speed Graph") {
|
||||
app.ui.timeline.graph_mode = "speed".into();
|
||||
}
|
||||
x += 6.0;
|
||||
if text_button(app, ui, p, &mut x, y, "Selected", show_sel, "showSelected", "Show Selected Properties (else all animated properties)") {
|
||||
buttons.x += 6.0;
|
||||
if text_button(app, ui, p, &mut buttons, y, "Selected", show_sel, "showSelected", "Show Selected Properties (else all animated properties)") {
|
||||
app.ui.timeline.graph_show_selected = !show_sel;
|
||||
}
|
||||
if text_button(app, ui, p, &mut x, y, "Auto-zoom", auto_on, "autoZoom", "Auto-zoom graph height") {
|
||||
if text_button(app, ui, p, &mut buttons, y, "Auto-zoom", auto_on, "autoZoom", "Auto-zoom graph height") {
|
||||
app.ui.timeline.graph_auto_zoom = !auto_on;
|
||||
}
|
||||
if text_button(app, ui, p, &mut x, y, "Fit", false, "fit", "Fit all graphs to view") {
|
||||
if text_button(app, ui, p, &mut buttons, y, "Fit", false, "fit", "Fit all graphs to view") {
|
||||
app.ui.timeline.graph_auto_zoom = true;
|
||||
app.ui.timeline.pps = None;
|
||||
}
|
||||
if text_button(app, ui, p, &mut x, y, "Fit Selection", false, "fitSelection", "Fit selection to view") {
|
||||
if text_button(app, ui, p, &mut buttons, y, "Fit Selection", false, "fitSelection", "Fit selection to view") {
|
||||
fit_selection(app, &cs, tm, plot);
|
||||
}
|
||||
x += 6.0;
|
||||
buttons.x += 6.0;
|
||||
let (snap, reference, tbox) = (app.ui.timeline.graph_snap, app.ui.timeline.graph_reference, app.ui.timeline.graph_transform_box);
|
||||
if text_button(app, ui, p, &mut x, y, "Snap", snap, "snap", "Snap (key drags snap to the current time and other keys)") {
|
||||
if text_button(app, ui, p, &mut buttons, y, "Snap", snap, "snap", "Snap (key drags snap to the current time and other keys)") {
|
||||
app.ui.timeline.graph_snap = !snap;
|
||||
}
|
||||
if text_button(app, ui, p, &mut x, y, "Reference", reference, "reference", "Show Reference Graph") {
|
||||
if text_button(app, ui, p, &mut buttons, y, "Reference", reference, "reference", "Show Reference Graph") {
|
||||
app.ui.timeline.graph_reference = !reference;
|
||||
}
|
||||
if text_button(app, ui, p, &mut x, y, "Transform Box", tbox, "transformBox", "Show Transform Box when multiple keys are selected") {
|
||||
if text_button(app, ui, p, &mut buttons, y, "Transform Box", tbox, "transformBox", "Show Transform Box when multiple keys are selected") {
|
||||
app.ui.timeline.graph_transform_box = !tbox;
|
||||
}
|
||||
x += 6.0;
|
||||
buttons.x += 6.0;
|
||||
let pos_sel = app.session.state.selected_props.iter().find_map(|(l, u)| super::timeline::is_position(comp.layer(*l)?, *u).then_some(l.0));
|
||||
if text_button(app, ui, p, &mut x, y, "Separate Dimensions", false, "separateDimensions", "Separate Dimensions (Position)")
|
||||
if text_button(app, ui, p, &mut buttons, y, "Separate Dimensions", false, "separateDimensions", "Separate Dimensions (Position)")
|
||||
&& let Some(l) = pos_sel.or(app.session.state.selected_layers.first().map(|l| l.0))
|
||||
{
|
||||
actions.push(("prop.separateDimensions".into(), json!({"layer": l})));
|
||||
}
|
||||
x += 6.0;
|
||||
buttons.x += 6.0;
|
||||
for (label, cmd, params, tip) in [
|
||||
("Hold", "keys.interpolation", json!({"interpolation": "hold"}), "Convert selected keyframes to Hold"),
|
||||
("Linear", "keys.interpolation", json!({"interpolation": "linear"}), "Convert selected keyframes to Linear"),
|
||||
@@ -511,10 +589,11 @@ pub(crate) fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painte
|
||||
("Ease Out", "keys.easyEaseOut", json!({}), "Easy Ease Out (Ctrl+Shift+F9)"),
|
||||
] {
|
||||
let id = cmd.trim_start_matches("keys.").to_string() + label.split_whitespace().next().unwrap_or("");
|
||||
if text_button(app, ui, p, &mut x, y, label, false, &id, tip) {
|
||||
if text_button(app, ui, p, &mut buttons, y, label, false, &id, tip) {
|
||||
actions.push((cmd.into(), params));
|
||||
}
|
||||
}
|
||||
buttons.more(app, ui, p, bar);
|
||||
}
|
||||
|
||||
/// Zoom time and value to the selected keys (and their handles).
|
||||
|
||||
@@ -15,6 +15,7 @@ use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
|
||||
use serde::Serialize;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::i18n::{tr, tr_args};
|
||||
use crate::icons::{self, Icon};
|
||||
use crate::theme::Tokens;
|
||||
use crate::{EffectcraftApp, widgets};
|
||||
@@ -87,13 +88,13 @@ pub fn format_utc(secs: i64) -> String {
|
||||
/// date after a week).
|
||||
pub fn format_ago(now: i64, then: i64) -> String {
|
||||
let d = now.saturating_sub(then);
|
||||
let plural = |n: i64, unit: &str| format!("{n} {unit}{} ago", if n == 1 { "" } else { "s" });
|
||||
let plural = |n: i64, one: &str, many: &str| tr_args(if n == 1 { one } else { many }, &[&n]);
|
||||
match d {
|
||||
i64::MIN..60 => "Just now".to_string(),
|
||||
60..3_600 => plural(d / 60, "minute"),
|
||||
3_600..86_400 => plural(d / 3_600, "hour"),
|
||||
86_400..172_800 => "Yesterday".to_string(),
|
||||
172_800..604_800 => plural(d / 86_400, "day"),
|
||||
i64::MIN..60 => tr("Just now").to_string(),
|
||||
60..3_600 => plural(d / 60, "{} minute ago", "{} minutes ago"),
|
||||
3_600..86_400 => plural(d / 3_600, "{} hour ago", "{} hours ago"),
|
||||
86_400..172_800 => tr("Yesterday").to_string(),
|
||||
172_800..604_800 => plural(d / 86_400, "{} day ago", "{} days ago"),
|
||||
_ => format_utc(then).get(..10).unwrap_or_default().to_string(),
|
||||
}
|
||||
}
|
||||
@@ -112,14 +113,14 @@ pub fn format_size(bytes: u64) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Kind column: what a recent file is, by its extension.
|
||||
/// The Kind column: what a recent file is, by its extension, in the interface language.
|
||||
fn kind_of(path: &str) -> &'static str {
|
||||
match std::path::Path::new(path).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).as_deref() {
|
||||
tr(match std::path::Path::new(path).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).as_deref() {
|
||||
Some("ecproj") => "EffectCraft project",
|
||||
Some("aep" | "aepx") => "After Effects project",
|
||||
Some("json" | "lottie") => "Lottie animation",
|
||||
_ => "Project",
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The config-store name of a project's thumbnail.
|
||||
@@ -237,7 +238,7 @@ fn rail_ui(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, rail:
|
||||
let mut y = rail.min.y + 20.0;
|
||||
for (label, id, primary) in [("New Project", "file.newProject", true), ("Open Project…", "file.open", false)] {
|
||||
let r = Rect::from_min_size(pos2(x0, y), vec2(w, 34.0));
|
||||
if widgets::text_button(ui, r, label, primary, &t, egui::Id::new(("home", id))).clicked() {
|
||||
if widgets::text_button(ui, r, tr(label), primary, &t, egui::Id::new(("home", id))).clicked() {
|
||||
actions.push((id, json!({})));
|
||||
}
|
||||
app.auto.add(&format!("home.{id}"), r, label);
|
||||
@@ -261,7 +262,7 @@ fn rail_ui(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, rail:
|
||||
}
|
||||
let col = if on { t.tab_text_active } else { t.text_dim };
|
||||
icons::paint(p, Rect::from_center_size(pos2(r.min.x + 20.0, r.center().y), vec2(16.0, 16.0)), icon, col);
|
||||
p.text(pos2(r.min.x + 40.0, r.center().y), Align2::LEFT_CENTER, label, Tokens::medium(13.0), col);
|
||||
p.text(pos2(r.min.x + 40.0, r.center().y), Align2::LEFT_CENTER, tr(label), Tokens::medium(13.0), col);
|
||||
app.auto.add(&format!("home.tab.{}", label.to_ascii_lowercase()), r, label);
|
||||
if resp.clicked() {
|
||||
app.ui.home_learn = k == 2;
|
||||
@@ -281,7 +282,7 @@ fn rail_ui(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, rail:
|
||||
let foot_h = 22.0 + links.len() as f32 * 30.0 + 22.0 + sib_rows * 26.0;
|
||||
let mut cy = (rail.max.y - 16.0 - foot_h).max(y + 16.0);
|
||||
p.line_segment([pos2(x0, cy - 10.0), pos2(x0 + w, cy - 10.0)], Stroke::new(1.0, t.separator));
|
||||
p.text(pos2(x0, cy + 6.0), Align2::LEFT_CENTER, crate::i18n::tr("Community"), Tokens::semibold(12.0), t.text_dim);
|
||||
p.text(pos2(x0, cy + 6.0), Align2::LEFT_CENTER, tr("Community"), Tokens::semibold(12.0), t.text_dim);
|
||||
cy += 22.0;
|
||||
for (icon, label, cmd) in links {
|
||||
let r = Rect::from_min_size(pos2(x0, cy), vec2(w, 26.0));
|
||||
@@ -294,14 +295,14 @@ fn rail_ui(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter, rail:
|
||||
}
|
||||
let col = if discord { Color32::WHITE } else { t.text };
|
||||
icons::paint(p, Rect::from_center_size(pos2(r.min.x + 16.0, r.center().y), vec2(13.0, 13.0)), icon, col);
|
||||
p.text(pos2(r.min.x + 30.0, r.center().y), Align2::LEFT_CENTER, label, Tokens::medium(12.0), col);
|
||||
p.text(pos2(r.min.x + 30.0, r.center().y), Align2::LEFT_CENTER, tr(label), Tokens::medium(12.0), col);
|
||||
app.auto.add(&format!("home.{cmd}"), r, label);
|
||||
if resp.clicked() {
|
||||
let _ = app.session.execute(cmd, json!({}));
|
||||
}
|
||||
cy += 30.0;
|
||||
}
|
||||
p.text(pos2(x0, cy + 8.0), Align2::LEFT_CENTER, crate::i18n::tr("More ArtCraft apps"), Tokens::ui(11.0), t.text_faint);
|
||||
p.text(pos2(x0, cy + 8.0), Align2::LEFT_CENTER, tr("More ArtCraft apps"), Tokens::ui(11.0), t.text_faint);
|
||||
cy += 20.0;
|
||||
let sw = (w - 6.0) / 2.0;
|
||||
for (i, (name, slug)) in sib.iter().enumerate() {
|
||||
@@ -328,12 +329,12 @@ fn home_page(
|
||||
let t = app.tokens;
|
||||
let (x0, w) = (area.min.x, area.width());
|
||||
let mut y = area.min.y;
|
||||
p.text(pos2(x0, y + 14.0), Align2::LEFT_CENTER, crate::i18n::tr("Welcome to EffectCraft"), Tokens::semibold(26.0), t.tab_text_active);
|
||||
p.text(pos2(x0, y + 14.0), Align2::LEFT_CENTER, tr("Welcome to EffectCraft"), Tokens::semibold(26.0), t.tab_text_active);
|
||||
y += 40.0;
|
||||
p.text(
|
||||
pos2(x0, y + 8.0),
|
||||
Align2::LEFT_CENTER,
|
||||
format!("Motion graphics and visual effects · version {}", env!("CARGO_PKG_VERSION")),
|
||||
tr_args("Motion graphics and visual effects · version {}", &[&env!("CARGO_PKG_VERSION")]),
|
||||
Tokens::ui(12.5),
|
||||
t.text_dim,
|
||||
);
|
||||
@@ -355,7 +356,7 @@ fn home_page(
|
||||
let ir = Rect::from_center_size(pos2(r.min.x + 30.0, r.center().y), vec2(32.0, 32.0));
|
||||
p.rect_filled(ir, 7.0, t.accent.gamma_multiply(0.18));
|
||||
icons::paint(p, ir.shrink(8.0), icon, t.accent);
|
||||
p.with_clip_rect(r.shrink(2.0)).text(pos2(ir.max.x + 12.0, r.center().y), Align2::LEFT_CENTER, label, Tokens::medium(12.5), t.text);
|
||||
p.with_clip_rect(r.shrink(2.0)).text(pos2(ir.max.x + 12.0, r.center().y), Align2::LEFT_CENTER, tr(label), Tokens::medium(12.5), t.text);
|
||||
app.auto.add(&format!("home.{id}"), r, label);
|
||||
if resp.clicked() {
|
||||
if id == "templates" {
|
||||
@@ -369,18 +370,18 @@ fn home_page(
|
||||
y += 64.0 + 36.0;
|
||||
|
||||
// Recent: heading, filter, clear.
|
||||
p.text(pos2(x0, y + 12.0), Align2::LEFT_CENTER, crate::i18n::tr("Recent"), Tokens::semibold(17.0), t.tab_text_active);
|
||||
p.text(pos2(x0, y + 12.0), Align2::LEFT_CENTER, tr("Recent"), Tokens::semibold(17.0), t.tab_text_active);
|
||||
let entries = recent_entries(&app.session.prefs);
|
||||
let fid = egui::Id::new("home-filter");
|
||||
let mut filter: String = ctx.data(|d| d.get_temp(fid)).unwrap_or_default();
|
||||
let fr = Rect::from_min_size(pos2(x0 + w - 240.0, y), vec2(240.0, 26.0));
|
||||
widgets::search_field(ui, fr, &mut filter, "Filter recent files", &t);
|
||||
widgets::search_field(ui, fr, &mut filter, tr("Filter recent files"), &t);
|
||||
app.auto.add("home.filter", fr, "Filter recent files");
|
||||
ctx.data_mut(|d| d.insert_temp(fid, filter.clone()));
|
||||
if !entries.is_empty() {
|
||||
let cr = Rect::from_min_size(pos2(fr.min.x - 96.0, y + 3.0), vec2(84.0, 20.0));
|
||||
let resp = ui.interact(cr, egui::Id::new("home-clear-recent"), Sense::click());
|
||||
p.text(cr.right_center(), Align2::RIGHT_CENTER, crate::i18n::tr("Clear list"), Tokens::ui(11.5), if resp.hovered() { t.text } else { t.text_faint });
|
||||
p.text(cr.right_center(), Align2::RIGHT_CENTER, tr("Clear list"), Tokens::ui(11.5), if resp.hovered() { t.text } else { t.text_faint });
|
||||
app.auto.add("home.clearRecent", cr, "Clear Recent Projects");
|
||||
if resp.clicked() {
|
||||
actions.push(("file.clearRecent", json!({})));
|
||||
@@ -390,7 +391,7 @@ fn home_page(
|
||||
// Column headings (Name / Opened / Size / Kind, as in After Effects).
|
||||
let (opened_x, size_x, kind_x) = (x0 + w * 0.52, x0 + w * 0.68, x0 + w * 0.80);
|
||||
for (label, x) in [("NAME", x0 + 76.0), ("OPENED", opened_x), ("SIZE", size_x), ("KIND", kind_x)] {
|
||||
p.text(pos2(x, y), Align2::LEFT_CENTER, label, Tokens::medium(10.5), t.text_faint);
|
||||
p.text(pos2(x, y), Align2::LEFT_CENTER, tr(label), Tokens::medium(10.5), t.text_faint);
|
||||
}
|
||||
y += 12.0;
|
||||
p.line_segment([pos2(x0, y), pos2(x0 + w, y)], Stroke::new(1.0, t.separator));
|
||||
@@ -406,8 +407,8 @@ fn home_page(
|
||||
} else {
|
||||
("No recent files match the filter", "Try another name or folder.")
|
||||
};
|
||||
p.text(c + vec2(0.0, 40.0), Align2::CENTER_CENTER, head, Tokens::semibold(14.0), t.text);
|
||||
p.text(c + vec2(0.0, 62.0), Align2::CENTER_CENTER, sub, Tokens::ui(12.0), t.text_faint);
|
||||
p.text(c + vec2(0.0, 40.0), Align2::CENTER_CENTER, tr(head), Tokens::semibold(14.0), t.text);
|
||||
p.text(c + vec2(0.0, 62.0), Align2::CENTER_CENTER, tr(sub), Tokens::ui(12.0), t.text_faint);
|
||||
}
|
||||
let now = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX));
|
||||
let row_h = 48.0;
|
||||
@@ -439,7 +440,7 @@ fn home_page(
|
||||
Tokens::medium(13.0),
|
||||
if e.exists { t.tab_text_active } else { t.text_dim },
|
||||
);
|
||||
let sub = if e.exists { e.folder.clone() } else { format!("{} (missing)", e.folder) };
|
||||
let sub = if e.exists { e.folder.clone() } else { format!("{} {}", e.folder, crate::i18n::tr("(missing)")) };
|
||||
name_clip.text(pos2(tr.max.x + 6.0, r.center().y + 9.0), Align2::LEFT_CENTER, sub, Tokens::ui(11.0), t.text_faint);
|
||||
let cell = |x: f32, x1: f32, text: String| {
|
||||
p.with_clip_rect(Rect::from_min_max(pos2(x, r.min.y), pos2(x1 - 8.0, r.max.y))).text(
|
||||
@@ -534,6 +535,21 @@ mod tests {
|
||||
assert_eq!((kind_of("/a/B.ecproj"), kind_of("c.AEP"), kind_of("x")), ("EffectCraft project", "After Effects project", "Project"));
|
||||
}
|
||||
|
||||
/// The Home screen's own text goes through the interface catalog (#574): the Opened and Kind
|
||||
/// columns read in Chinese, and English stays English.
|
||||
#[test]
|
||||
fn home_text_follows_the_interface_language() {
|
||||
let now = 1_790_000_000;
|
||||
crate::i18n::set_current("zh-hans");
|
||||
let zh = (format_ago(now, now - 5), format_ago(now, now - 3 * 3_600), format_ago(now, now - 90_000), kind_of("/a/B.ecproj"));
|
||||
crate::i18n::set_current("zh-hant");
|
||||
let tw = (format_ago(now, now - 60), kind_of("x"));
|
||||
crate::i18n::set_current("en");
|
||||
assert_eq!(zh, ("刚刚".into(), "3 小时前".into(), "昨天".into(), "EffectCraft 项目"));
|
||||
assert_eq!(tw, ("1 分鐘前".into(), "專案"));
|
||||
assert_eq!(tr("Filter recent files"), "Filter recent files");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn home_screen_registers_its_controls() {
|
||||
let mut s = effectcraft_engine::Session::default();
|
||||
|
||||
@@ -126,7 +126,7 @@ fn buttons(ui: &mut egui::Ui, app: &mut EffectcraftApp, t: &Tokens, prefix: &str
|
||||
}
|
||||
|
||||
fn drag(ui: &mut egui::Ui, app: &mut EffectcraftApp, id: &str, v: &mut f64, speed: f64, range: std::ops::RangeInclusive<f64>, suffix: &str, enabled: bool) {
|
||||
let r = ui.add_enabled(enabled, egui::DragValue::new(v).speed(speed).range(range).max_decimals(2).suffix(suffix));
|
||||
let r = ui.add_enabled(enabled, crate::widgets::drag_value(egui::DragValue::new(v).speed(speed).range(range).max_decimals(2).suffix(suffix)));
|
||||
app.auto.add(id, r.rect, id);
|
||||
}
|
||||
|
||||
|
||||
@@ -103,17 +103,17 @@ fn control(ui: &mut egui::Ui, p: &Property, v: &KV) -> Option<Value> {
|
||||
ParamUi::Slider { slider_min, slider_max, decimals, .. } => {
|
||||
ui.add(egui::Slider::new(&mut y, *slider_min..=*slider_max).clamping(egui::SliderClamping::Never).max_decimals(*decimals as usize))
|
||||
}
|
||||
ParamUi::Percent => ui.add(egui::DragValue::new(&mut y).speed(0.5).suffix("%")),
|
||||
ParamUi::Angle => ui.add(egui::DragValue::new(&mut y).speed(0.5).suffix("°")),
|
||||
ParamUi::Pixels => ui.add(egui::DragValue::new(&mut y).speed(0.25).suffix(" px")),
|
||||
_ => ui.add(egui::DragValue::new(&mut y).speed(0.1)),
|
||||
ParamUi::Percent => ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut y).speed(0.5).suffix("%"))),
|
||||
ParamUi::Angle => ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut y).speed(0.5).suffix("°"))),
|
||||
ParamUi::Pixels => ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut y).speed(0.25).suffix(" px"))),
|
||||
_ => ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut y).speed(0.1))),
|
||||
};
|
||||
(r.changed() && y != *x).then(|| json!(y))
|
||||
}
|
||||
(KV::Color(c), _) => {
|
||||
let mut rgba = egui::Rgba::from_rgba_unmultiplied(c[0] as f32, c[1] as f32, c[2] as f32, c[3] as f32);
|
||||
let changed = egui::color_picker::color_edit_button_rgba(ui, &mut rgba, egui::color_picker::Alpha::Opaque).changed();
|
||||
changed.then(|| json!([rgba.r(), rgba.g(), rgba.b()]))
|
||||
let mut rgb = [c[0] as f32, c[1] as f32, c[2] as f32];
|
||||
let changed = crate::widgets::srgb_color_button(ui, &mut rgb).changed();
|
||||
changed.then(|| json!(rgb))
|
||||
}
|
||||
(KV::Gradient(_), _) => {
|
||||
ui.label(egui::RichText::new(tr("Edit in the Timeline")).weak());
|
||||
|
||||
@@ -128,11 +128,11 @@ pub fn dialog(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
|
||||
super::dialogs::modal(ctx, &title, vec2(520.0, 560.0), t, |ui| {
|
||||
egui::Grid::new("marker-grid").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| {
|
||||
ui.label(tr("Time:"));
|
||||
let r = ui.add(egui::DragValue::new(&mut d.time).speed(0.01).range(0.0..=1e6).suffix(" s").max_decimals(3));
|
||||
let r = ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut d.time).speed(0.01).range(0.0..=1e6).suffix(" s").max_decimals(3)));
|
||||
app.auto.add("dialog.marker.time", r.rect, "Time");
|
||||
ui.end_row();
|
||||
ui.label(tr("Duration:"));
|
||||
let r = ui.add(egui::DragValue::new(&mut d.duration).speed(0.01).range(0.0..=1e6).suffix(" s").max_decimals(3));
|
||||
let r = ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut d.duration).speed(0.01).range(0.0..=1e6).suffix(" s").max_decimals(3)));
|
||||
app.auto.add("dialog.marker.duration", r.rect, "Duration");
|
||||
ui.end_row();
|
||||
ui.label(tr("Comment:"));
|
||||
|
||||
@@ -78,6 +78,32 @@ pub enum DragPayload {
|
||||
Files(Vec<String>),
|
||||
}
|
||||
|
||||
/// Layers carried by a Project item drag. Dragging a selected item uses the
|
||||
/// complete selection, while dragging an unselected item uses only that item.
|
||||
/// Folders and data files are not composition layers.
|
||||
pub(crate) fn project_drop_items(app: &EffectcraftApp, dragged: u64) -> Vec<u64> {
|
||||
use effectcraft_engine::project::{FootageKind, ItemId, ItemKind};
|
||||
|
||||
let selected = &app.session.state.project_selection;
|
||||
let candidates: Vec<u64> = if selected.iter().any(|id| id.0 == dragged) {
|
||||
selected.iter().map(|id| id.0).collect()
|
||||
} else {
|
||||
// One unselected item goes through as is, so a folder or data file still gets the
|
||||
// engine's error instead of a silent no-op.
|
||||
return vec![dragged];
|
||||
};
|
||||
candidates
|
||||
.into_iter()
|
||||
.filter(|id| {
|
||||
app.session.project.item(ItemId(*id)).is_some_and(|item| match &item.kind {
|
||||
ItemKind::Comp(_) | ItemKind::Solid(_) => true,
|
||||
ItemKind::Footage(f) => f.kind != FootageKind::Data,
|
||||
ItemKind::Folder => false,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The current time formatted per project settings (timecode with `;` for drop-frame, frames
|
||||
/// or Feet + Frames).
|
||||
pub fn timecode(session: &Session, comp: &Comp, t: Tick) -> String {
|
||||
|
||||
@@ -102,11 +102,11 @@ pub fn paint(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
app.auto.add("paint.color", fg, "Foreground color");
|
||||
app.auto.add("paint.background", bg, "Background color");
|
||||
let mut fc = rgb(o.color);
|
||||
if crate::header::color_popup(ui, egui::Id::new("paint-fg-pop"), fg.left_bottom(), &mut fc) {
|
||||
if crate::widgets::color_popup(ui, egui::Id::new("paint-fg-pop"), fg.left_bottom(), &mut fc) {
|
||||
set(app, json!({"color": [fc[0], fc[1], fc[2], 1.0]}));
|
||||
}
|
||||
let mut bc = rgb(o.background);
|
||||
if crate::header::color_popup(ui, egui::Id::new("paint-bg-pop"), bg.left_bottom(), &mut bc) {
|
||||
if crate::widgets::color_popup(ui, egui::Id::new("paint-bg-pop"), bg.left_bottom(), &mut bc) {
|
||||
set(app, json!({"background": [bc[0], bc[1], bc[2], 1.0]}));
|
||||
}
|
||||
let swap = Rect::from_min_size(pos2(x0 + 46.0, y), vec2(18.0, 14.0));
|
||||
|
||||
@@ -599,12 +599,10 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
actions.push(("layer.addItem".into(), json!({"item": id.0})));
|
||||
ui.close();
|
||||
}
|
||||
// File ▸ New Comp from Selection on the selection (the right-clicked row joins it
|
||||
// above): several items ask how in its dialog, as in After Effects (#360).
|
||||
if ui.button(crate::i18n::tr("New Comp from Selection")).clicked() {
|
||||
if let Some((w, h)) = it.dimensions() {
|
||||
let d = it.duration().map(|d| d.seconds()).unwrap_or(10.0);
|
||||
actions.push(("comp.new".into(), json!({"name": format!("{} Comp", it.name), "width": w, "height": h, "duration": d})));
|
||||
actions.push(("layer.addItem".into(), json!({"item": id.0})));
|
||||
}
|
||||
actions.push(("file.newCompFromSelection".into(), json!({})));
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
|
||||
@@ -72,6 +72,17 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let mut y = top;
|
||||
let mut actions: Actions = vec![];
|
||||
|
||||
// Several layers selected: "(3) Selected Objects", as in After Effects. The rows show the
|
||||
// first layer; the stopwatch, keyframe button and value edits apply to all of them (#355).
|
||||
let selected = app.session.state.selected_layers.iter().filter(|id| comp.layer(**id).is_some()).count();
|
||||
if selected > 1 {
|
||||
let n = selected.to_string();
|
||||
let label = crate::i18n::tr_args("({}) Selected Objects", &[&n]);
|
||||
p.text(pos2(x0, y + ROW_H / 2.0), Align2::LEFT_CENTER, &label, Tokens::semibold(12.0), t.text);
|
||||
app.auto.add("properties.selectedObjects", Rect::from_min_size(pos2(x0, y), vec2(w, ROW_H)), &label);
|
||||
y += ROW_H + 4.0;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Layer Transform
|
||||
if let Some(tr) = layer.transform().cloned() {
|
||||
section_header(app, ui, &p, x0, w, y, "Layer Transform", "properties.transform");
|
||||
@@ -218,7 +229,7 @@ fn transform_row(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter,
|
||||
match what {
|
||||
"prev" => actions.push(("time.go".into(), json!({"to": "prevKey", "prop": uid}))),
|
||||
"next" => actions.push(("time.go".into(), json!({"to": "nextKey", "prop": uid}))),
|
||||
_ => actions.push(("prop.toggleKey".into(), json!({"layer": lid, "prop": uid}))),
|
||||
_ => actions.push(("prop.toggleKey".into(), json!({"layer": lid, "prop": uid, "selected": true}))),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -228,13 +239,18 @@ fn transform_row(app: &mut EffectcraftApp, ui: &mut egui::Ui, p: &egui::Painter,
|
||||
icons::paint(p, swr, Icon::Stopwatch, if resp.hovered() { t.text } else { t.text_dim });
|
||||
app.auto.add(&format!("{base}.stopwatch"), swr, &pr.name);
|
||||
if resp.clicked() {
|
||||
actions.push(("prop.toggleAnimation".into(), json!({"layer": lid, "prop": uid})));
|
||||
actions.push(("prop.toggleAnimation".into(), json!({"layer": lid, "prop": uid, "selected": true})));
|
||||
}
|
||||
}
|
||||
p.text(pos2(r.min.x + 42.0, cy), Align2::LEFT_CENTER, &pr.name, Tokens::ui(12.0), t.text);
|
||||
let vx = r.min.x + (r.width() * 0.5).max(130.0);
|
||||
let merge = format!("props-{uid}");
|
||||
let set = |actions: &mut Actions, v: serde_json::Value| actions.push(("prop.set".into(), json!({"layer": lid, "prop": uid, "value": v, "merge": merge})));
|
||||
// With several layers selected the edit applies to all: a scrub by the same change, a typed
|
||||
// value as it is.
|
||||
let scrub = ui.ctx().dragged_id().is_some() && ui.input(|i| i.pointer.is_decidedly_dragging());
|
||||
let set = |actions: &mut Actions, v: serde_json::Value| {
|
||||
actions.push(("prop.set".into(), json!({"layer": lid, "prop": uid, "value": v, "merge": merge, "selected": true, "offset": scrub})))
|
||||
};
|
||||
let value = ectx.value(layer, pr);
|
||||
let is_scale = pr.name == "Scale";
|
||||
let pct = is_scale || pr.name == "Opacity";
|
||||
@@ -320,13 +336,7 @@ fn text_section(
|
||||
// Font family and style.
|
||||
let fr = Rect::from_min_size(pos2(x0, y), vec2(w, 22.0));
|
||||
let pop = egui::Id::new("props-font-pop");
|
||||
if widgets::dropdown(ui, fr, &doc.font, &t, egui::Id::new("props-font")).clicked() {
|
||||
widgets::open_popup(ui, pop);
|
||||
}
|
||||
app.auto.add("properties.text.font", fr, "Font family");
|
||||
// Every installed family (built only while the menu is open: it can be long).
|
||||
let fams: Vec<String> = if widgets::popup_is_open(ui, pop) { effectcraft_engine::text_families() } else { vec![] };
|
||||
if let Some(f) = widgets::popup_menu(ui, pop, fr.left_bottom(), &fams, fams.iter().position(|f| *f == doc.font)).and_then(|i| fams.get(i)) {
|
||||
if let Some(f) = super::text_panels::font_picker(app, ui, pop, fr, &doc.font, "properties.text.font", true) {
|
||||
set(actions, json!({"font": f}));
|
||||
}
|
||||
y += 28.0;
|
||||
@@ -401,7 +411,7 @@ fn text_section(
|
||||
}
|
||||
app.auto.add(&format!("properties.text.{key}"), sw, label);
|
||||
let mut rgb = [c[0], c[1], c[2]];
|
||||
if crate::header::color_popup(ui, pop, sw.left_bottom(), &mut rgb) {
|
||||
if crate::widgets::color_popup(ui, pop, sw.left_bottom(), &mut rgb) {
|
||||
set(actions, json!({key: [rgb[0], rgb[1], rgb[2]], "merge": format!("props-text-{key}")}));
|
||||
}
|
||||
p.text(pos2(sw.max.x + 8.0, sw.center().y), Align2::LEFT_CENTER, label, Tokens::ui(12.0), t.text);
|
||||
|
||||
@@ -168,6 +168,32 @@ pub fn interact(
|
||||
let sign = if kind == "bg" || kind == "refineErase" { "−" } else { "+" };
|
||||
painter.text(hp, Align2::CENTER_CENTER, sign, Tokens::semibold(12.0), col);
|
||||
}
|
||||
// ⌘/Ctrl-drag resizes the brush (After Effects): the circle stays at the press point and its
|
||||
// edge follows the pointer. No stroke is painted.
|
||||
let rid = egui::Id::new("layer-panel-roto-resize");
|
||||
if resp.drag_started()
|
||||
&& mods.command
|
||||
&& let Some(pos) = ui.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos())
|
||||
{
|
||||
ctx.data_mut(|d| d.insert_temp(rid, pos));
|
||||
}
|
||||
if let Some(origin) = ctx.data(|d| d.get_temp::<Pos2>(rid)) {
|
||||
if let Some(pos) = resp.interact_pointer_pos()
|
||||
&& zoom > 0.0
|
||||
{
|
||||
let dia = (2.0 * f64::from(origin.distance(pos)) / zoom).clamp(1.0, 5000.0).round();
|
||||
let key = if refine { "refineDiameter" } else { "diameter" };
|
||||
if let Err(e) = app.session.execute("roto.options", json!({key: dia})) {
|
||||
app.ui.status = e.to_string();
|
||||
}
|
||||
painter.circle_stroke(origin, (dia * 0.5 * zoom) as f32, Stroke::new(1.5, col));
|
||||
painter.text(origin + vec2(0.0, -14.0), Align2::CENTER_BOTTOM, format!("{dia:.0} px"), Tokens::ui(11.0), col);
|
||||
}
|
||||
if resp.drag_stopped() || !resp.dragged() {
|
||||
ctx.data_mut(|d| d.remove::<Pos2>(rid));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
let did = egui::Id::new("layer-panel-roto-drag");
|
||||
if resp.drag_started()
|
||||
&& let Some(pos) = ui.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos())
|
||||
|
||||
@@ -38,6 +38,12 @@ fn hex(c: [u8; 3]) -> String {
|
||||
format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2])
|
||||
}
|
||||
|
||||
/// sRGB components (0–1) as bytes.
|
||||
fn srgb_bytes(c: [f32; 3]) -> [u8; 3] {
|
||||
let col = crate::widgets::srgb32(c);
|
||||
[col.r(), col.g(), col.b()]
|
||||
}
|
||||
|
||||
fn reg(app: &mut EffectcraftApp, id: &str, r: &egui::Response, label: &str) {
|
||||
app.auto.add(id, r.rect, label);
|
||||
}
|
||||
@@ -112,7 +118,7 @@ fn page_ui(app: &mut EffectcraftApp, ui: &mut egui::Ui, page: &Page, cur: &Value
|
||||
let r = match kind {
|
||||
Kind::Int(lo, hi, unit) => {
|
||||
let mut x = v.as_i64().unwrap_or(0);
|
||||
let r = ui.add(egui::DragValue::new(&mut x).range(lo..=hi).speed(0.25));
|
||||
let r = ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut x).range(lo..=hi).speed(0.25)));
|
||||
if !unit.is_empty() {
|
||||
ui.label(RichText::new(unit).color(t.text_dim));
|
||||
}
|
||||
@@ -123,7 +129,7 @@ fn page_ui(app: &mut EffectcraftApp, ui: &mut egui::Ui, page: &Page, cur: &Value
|
||||
}
|
||||
Kind::Float(lo, hi, unit) => {
|
||||
let mut x = v.as_f64().unwrap_or(0.0);
|
||||
let r = ui.add(egui::DragValue::new(&mut x).range(lo..=hi).speed(0.1).max_decimals(3));
|
||||
let r = ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut x).range(lo..=hi).speed(0.1).max_decimals(3)));
|
||||
if !unit.is_empty() {
|
||||
ui.label(RichText::new(unit).color(t.text_dim));
|
||||
}
|
||||
@@ -178,8 +184,9 @@ fn page_ui(app: &mut EffectcraftApp, ui: &mut egui::Ui, page: &Page, cur: &Value
|
||||
}
|
||||
Kind::Color => {
|
||||
let c = crate::panels::viewer::hex_rgb(v.as_str().unwrap_or("")).unwrap_or([128, 128, 128]);
|
||||
let mut rgb = c;
|
||||
let r = ui.color_edit_button_srgb(&mut rgb);
|
||||
let mut f = c.map(|v| v as f32 / 255.0);
|
||||
let r = crate::widgets::srgb_color_button(ui, &mut f);
|
||||
let rgb = if r.changed() { srgb_bytes(f) } else { c };
|
||||
ui.label(RichText::new(hex(rgb)).monospace().color(t.text_dim));
|
||||
if rgb != c {
|
||||
acts.push(Act::Set(key.into(), json!(hex(rgb))));
|
||||
@@ -559,8 +566,9 @@ fn labels_ui(app: &mut EffectcraftApp, ui: &mut egui::Ui, cur: &Value, acts: &mu
|
||||
egui::Grid::new("settings-labels").num_columns(4).spacing([10.0, 4.0]).show(ui, |ui| {
|
||||
for (i, l) in labels.iter().enumerate() {
|
||||
let c = crate::panels::viewer::hex_rgb(l["color"].as_str().unwrap_or("")).unwrap_or([128, 128, 128]);
|
||||
let mut rgb = c;
|
||||
let r = ui.color_edit_button_srgb(&mut rgb);
|
||||
let mut f = c.map(|v| v as f32 / 255.0);
|
||||
let r = crate::widgets::srgb_color_button(ui, &mut f);
|
||||
let rgb = if r.changed() { srgb_bytes(f) } else { c };
|
||||
app.auto.add(&format!("settings.labels.{i}.color"), r.rect, "label colour");
|
||||
if rgb != c {
|
||||
acts.push(Act::Set(format!("labels.{i}.color"), json!(hex(rgb))));
|
||||
|
||||
@@ -204,6 +204,8 @@ pub fn show(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
|
||||
_ => None,
|
||||
})
|
||||
});
|
||||
// The shortcut field must not also type the key it just recorded (Alt+R came out as `rAlt+R`).
|
||||
ctx.input_mut(|i| i.events.retain(|e| !matches!(e, egui::Event::Text(_) | egui::Event::Key { .. })));
|
||||
if let Some((k, m)) = got {
|
||||
st.recording = false;
|
||||
if k != egui::Key::Escape
|
||||
@@ -586,6 +588,41 @@ mod tests {
|
||||
}
|
||||
assert_eq!(split("Cmd+Shift+K"), ([false, true, false, true], "K".into()));
|
||||
assert_eq!(split("Cmd++"), ([false, true, false, false], "+".into()));
|
||||
// The plus key, with and without modifiers, parses back (typed by hand or recorded).
|
||||
for txt in ["+", "Cmd++", "Alt++"] {
|
||||
assert_eq!(crate::menus::parse_shortcut(txt).map(|(_, k)| k), Some(egui::Key::Plus), "{txt}");
|
||||
}
|
||||
assert_eq!(crate::menus::parse_shortcut("Alt+R").map(|(m, k)| (m.alt, k)), Some((true, egui::Key::R)));
|
||||
assert_eq!(split("F9"), ([false; 4], "F9".into()));
|
||||
}
|
||||
|
||||
fn frame(app: &mut EffectcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) {
|
||||
app.auto.begin_frame();
|
||||
let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| crate::panels::dialogs::show(app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recording_a_shortcut_does_not_also_type_the_key_into_the_field() {
|
||||
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install(&ctx, &app.tokens, crate::i18n::language(&app));
|
||||
open(&mut app);
|
||||
app.dialog_state.shortcuts.selected = app.session.shortcuts().bindables.first().map(|b| b.key.clone());
|
||||
for _ in 0..3 {
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
}
|
||||
let [x, y, w, h] = app.auto.find("shortcuts.record").expect("shortcut field").rect;
|
||||
let at = pos2(x + w / 2.0, y + h / 2.0);
|
||||
let click = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), click(true)]);
|
||||
frame(&mut app, &ctx, vec![click(false)]);
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
assert!(app.dialog_state.shortcuts.recording);
|
||||
// Alt+R arrives as the key and as the typed text `r`.
|
||||
let key = egui::Event::Key { key: egui::Key::R, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::ALT };
|
||||
frame(&mut app, &ctx, vec![key, egui::Event::Text("r".into())]);
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(app.dialog_state.shortcuts.pending, "Alt+R");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,11 +96,7 @@ pub fn character(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
// Font family + style.
|
||||
let fr = Rect::from_min_size(pos2(x0, y), vec2(w, 22.0));
|
||||
let pop = egui::Id::new("char-font-pop");
|
||||
if widgets::dropdown(ui, fr, &doc.font, &t, egui::Id::new("char-font")).clicked() && enabled {
|
||||
widgets::open_popup(ui, pop);
|
||||
}
|
||||
app.auto.add("character.font", fr, "Font family");
|
||||
if let Some(f) = font_popup(app, ui, pop, fr.left_bottom(), &doc.font) {
|
||||
if let Some(f) = font_picker(app, ui, pop, fr, &doc.font, "character.font", enabled) {
|
||||
actions.push(json!({"font": f}));
|
||||
}
|
||||
y += 28.0;
|
||||
@@ -202,7 +198,7 @@ pub fn character(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
}
|
||||
app.auto.add(&format!("character.{key}"), fs, label);
|
||||
let mut rgb = [c[0], c[1], c[2]];
|
||||
if crate::header::color_popup(ui, pop, fs.left_bottom(), &mut rgb) {
|
||||
if crate::widgets::color_popup(ui, pop, fs.left_bottom(), &mut rgb) {
|
||||
actions.push(json!({key: [rgb[0], rgb[1], rgb[2]], "merge": format!("char-{key}")}));
|
||||
}
|
||||
p.text(pos2(fs.max.x + 6.0, y + 10.0), Align2::LEFT_CENTER, label, Tokens::ui(11.5), t.text_dim);
|
||||
@@ -551,47 +547,171 @@ 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 !widgets::popup_is_open(ui, id) {
|
||||
#[derive(Clone, Default)]
|
||||
struct FontSearch {
|
||||
query: String,
|
||||
selected: usize,
|
||||
}
|
||||
|
||||
/// Shared font menu for Character and Properties: search, recent fonts and previews.
|
||||
pub(super) fn font_picker(app: &mut EffectcraftApp, ui: &mut egui::Ui, id: egui::Id, rect: Rect, current: &str, auto: &str, enabled: bool) -> Option<String> {
|
||||
let state_id = id.with("search-state");
|
||||
app.auto.add(auto, rect, "Font family");
|
||||
if !widgets::popup_is_open(ui, id) || !enabled {
|
||||
ui.data_mut(|d| d.remove::<FontSearch>(state_id));
|
||||
if widgets::dropdown(ui, rect, current, &app.tokens, id.with("field")).clicked() && enabled {
|
||||
widgets::open_popup(ui, id);
|
||||
}
|
||||
return None;
|
||||
}
|
||||
let rows = effectcraft_engine::font_menu(&app.session.prefs);
|
||||
let saved = ui.data(|d| d.get_temp::<FontSearch>(state_id));
|
||||
let fresh = saved.is_none();
|
||||
let mut state = saved.unwrap_or_default();
|
||||
let search_id = id.with("search");
|
||||
let (up, down, enter, escape) = ui.input_mut(|i| {
|
||||
(
|
||||
i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowUp),
|
||||
i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowDown),
|
||||
i.consume_key(egui::Modifiers::NONE, egui::Key::Enter),
|
||||
i.consume_key(egui::Modifiers::NONE, egui::Key::Escape),
|
||||
)
|
||||
});
|
||||
let preview = app.session.prefs.type_.font_preview;
|
||||
let t = app.tokens;
|
||||
let seps = rows.iter().filter(|r| r.family.is_empty()).count();
|
||||
widgets::popup_list(ui, id, pos, Rect::NOTHING, rows.len().saturating_sub(seps), seps, |ui| {
|
||||
ui.set_min_width(if preview { 300.0 } else { 180.0 });
|
||||
let mut chosen = None;
|
||||
for r in &rows {
|
||||
if r.family.is_empty() {
|
||||
ui.separator();
|
||||
continue;
|
||||
// The font field itself becomes editable. The popup contains only results.
|
||||
let arrow = Rect::from_min_max(pos2(rect.max.x - 22.0, rect.min.y), rect.max);
|
||||
let edit_rect = Rect::from_min_max(rect.min, pos2(arrow.min.x, rect.max.y));
|
||||
let search = ui.put(edit_rect, egui::TextEdit::singleline(&mut state.query).id(search_id).hint_text(current).font(Tokens::ui(12.0)));
|
||||
app.auto.add(&format!("{auto}.search"), search.rect, "Search fonts");
|
||||
if fresh {
|
||||
search.request_focus();
|
||||
}
|
||||
ui.memory_mut(|m| m.set_focus_lock_filter(search_id, egui::EventFilter { vertical_arrows: true, escape: true, ..Default::default() }));
|
||||
if widgets::icon_button(ui, arrow, crate::icons::Icon::ChevronDown, false, &t, id.with("arrow")).clicked() {
|
||||
ui.data_mut(|d| {
|
||||
d.insert_temp(id.with("open"), false);
|
||||
d.remove::<FontSearch>(state_id);
|
||||
});
|
||||
ui.memory_mut(|m| m.surrender_focus(search_id));
|
||||
return None;
|
||||
}
|
||||
app.auto.add(&format!("{auto}.toggle"), arrow, "Close font list");
|
||||
let mut chosen = None;
|
||||
let screen = ui.ctx().content_rect();
|
||||
let below = screen.bottom() - rect.bottom() - 16.0;
|
||||
let above = below < 100.0 && rect.top() - screen.top() > below;
|
||||
let max_height = (if above { rect.top() - screen.top() - 16.0 } else { below }).clamp(28.0, 380.0);
|
||||
let anchor = if above { rect.left_top() } else { rect.left_bottom() };
|
||||
let pivot = if above { Align2::LEFT_BOTTOM } else { Align2::LEFT_TOP };
|
||||
widgets::note_open_popup_list(ui.ctx());
|
||||
let area = egui::Area::new(id.with("area")).order(egui::Order::Foreground).pivot(pivot).fixed_pos(anchor).show(ui.ctx(), |ui| {
|
||||
egui::Frame::popup(ui.style()).show(ui, |ui| {
|
||||
ui.set_width(rect.width().max(180.0));
|
||||
let query = state.query.trim().to_lowercase();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let filtered: Vec<_> = rows
|
||||
.iter()
|
||||
.filter(|r| {
|
||||
!r.family.is_empty()
|
||||
&& (query.is_empty()
|
||||
|| ((r.family.to_lowercase().contains(&query) || r.display.to_lowercase().contains(&query)) && seen.insert(&r.family)))
|
||||
})
|
||||
.collect();
|
||||
if fresh {
|
||||
state.selected = filtered.iter().position(|r| r.family == current).unwrap_or(0);
|
||||
}
|
||||
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 search.changed() {
|
||||
state.selected = 0;
|
||||
}
|
||||
let last = filtered.len().saturating_sub(1);
|
||||
state.selected = state.selected.min(last);
|
||||
if down {
|
||||
state.selected = state.selected.saturating_add(1).min(last);
|
||||
}
|
||||
if up {
|
||||
state.selected = state.selected.saturating_sub(1);
|
||||
}
|
||||
if enter {
|
||||
chosen = filtered.get(state.selected).map(|r| r.family.clone());
|
||||
}
|
||||
// Give the result list its actual height even when the previous query had
|
||||
// only one row. A cached tiny Area must not collapse a reopened long list.
|
||||
let height = (filtered.len() as f32 * (24.0 + ui.spacing().item_spacing.y) + 16.0).clamp(28.0, max_height);
|
||||
ui.set_height(height);
|
||||
let mut scroll = egui::ScrollArea::vertical().id_salt(id.with("results")).max_height(height).min_scrolled_height(height);
|
||||
if search.changed() {
|
||||
scroll = scroll.vertical_scroll_offset(0.0);
|
||||
}
|
||||
scroll.show(ui, |ui| {
|
||||
if filtered.is_empty() {
|
||||
let r = ui.label(tr("No matching fonts"));
|
||||
app.auto.add(&format!("{auto}.empty"), r.rect, "No matching fonts");
|
||||
}
|
||||
}
|
||||
if resp.clicked() {
|
||||
chosen = Some(r.family.clone());
|
||||
}
|
||||
}
|
||||
chosen
|
||||
})
|
||||
let mut was_recent = false;
|
||||
for (index, r) in filtered.iter().enumerate() {
|
||||
if query.is_empty() && was_recent && !r.recent {
|
||||
ui.separator();
|
||||
}
|
||||
was_recent = r.recent;
|
||||
let row_width = ui.available_width();
|
||||
let label_width = if preview { (row_width - 100.0).max(40.0) } else { row_width };
|
||||
let resp = ui.add_sized([row_width, 24.0], egui::Button::selectable(index == state.selected, ""));
|
||||
resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, ui.is_enabled(), index == state.selected, &r.display));
|
||||
let label_rect = Rect::from_min_size(resp.rect.min + vec2(5.0, 0.0), vec2(label_width - 5.0, resp.rect.height()));
|
||||
ui.painter().with_clip_rect(label_rect.intersect(ui.clip_rect())).text(
|
||||
label_rect.left_center(),
|
||||
Align2::LEFT_CENTER,
|
||||
&r.display,
|
||||
Tokens::ui(12.0),
|
||||
t.text,
|
||||
);
|
||||
if ui.is_rect_visible(resp.rect) {
|
||||
app.auto.add(&format!("{auto}.option.{}", r.family), resp.rect, &r.display);
|
||||
}
|
||||
if index == state.selected && (fresh || up || down) {
|
||||
resp.scroll_to_me(None);
|
||||
}
|
||||
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
|
||||
}
|
||||
};
|
||||
// Scaled and placed to fit the row's preview column, and clipped to the row (#577).
|
||||
let room = Rect::from_min_max(pos2(resp.rect.max.x - 95.0, resp.rect.min.y + 1.0), pos2(resp.rect.max.x - 6.0, resp.rect.max.y - 1.0));
|
||||
if let Some((k, o)) = fit_preview(&lines, room, resp.rect.center().y + 5.0) {
|
||||
let painter = ui.painter().with_clip_rect(resp.rect.intersect(ui.clip_rect()));
|
||||
for poly in lines.iter() {
|
||||
let pts: Vec<egui::Pos2> =
|
||||
poly.iter().filter(|p| p[0].is_finite() && p[1].is_finite()).map(|p| (o + vec2(p[0], p[1]) * k).to_pos2()).collect();
|
||||
painter.add(egui::Shape::line(pts, egui::Stroke::new(1.0, t.text_dim)));
|
||||
}
|
||||
}
|
||||
}
|
||||
if resp.clicked() {
|
||||
chosen = Some(r.family.clone());
|
||||
}
|
||||
resp.on_hover_text(&r.display);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
let outside = widgets::pressed_outside(ui.ctx(), &area.response) && !ui.input(|i| i.pointer.interact_pos().is_some_and(|p| rect.contains(p)));
|
||||
if chosen.is_some() || outside || escape {
|
||||
ui.data_mut(|d| {
|
||||
d.insert_temp(id.with("open"), false);
|
||||
d.remove::<FontSearch>(state_id);
|
||||
});
|
||||
ui.memory_mut(|m| m.surrender_focus(search_id));
|
||||
} else {
|
||||
ui.data_mut(|d| d.insert_temp(state_id, state));
|
||||
}
|
||||
chosen
|
||||
}
|
||||
|
||||
/// Align panel: Align Layers to Selection / Composition, the six align buttons and the six
|
||||
@@ -722,3 +842,63 @@ fn align_glyph(p: &egui::Painter, r: Rect, op: &str, distribute: bool, t: &Token
|
||||
p.rect_filled(Rect::from_min_size(pos2(c.x + 3.0, off(9.0)), vec2(5.0, 9.0)), 1.0, t.text_dim);
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a font's "Sample" outlines (`lines`, baseline at y = 0) go in `room`: `(scale, origin)`,
|
||||
/// a point `p` landing at `origin + p * scale`. At their natural size on `baseline` when they fit;
|
||||
/// fonts with large or odd metrics are scaled down (never up) and moved inside, so no preview
|
||||
/// spills out of its row (#577). `None`: nothing to draw.
|
||||
fn fit_preview(lines: &[Vec<[f32; 2]>], room: Rect, baseline: f32) -> Option<(f32, egui::Vec2)> {
|
||||
let b = lines
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|p| p[0].is_finite() && p[1].is_finite())
|
||||
.fold(Rect::NOTHING, |b, p| b.union(Rect::from_min_max(pos2(p[0], p[1]), pos2(p[0], p[1]))));
|
||||
if !(b.min.x <= b.max.x && b.min.y <= b.max.y && room.is_positive()) {
|
||||
return None;
|
||||
}
|
||||
let k = (room.width() / b.width().max(1e-3)).min(room.height() / b.height().max(1e-3)).min(1.0);
|
||||
let mut o = vec2(room.min.x - b.min.x * k, baseline);
|
||||
let (top, bottom) = (o.y + b.min.y * k, o.y + b.max.y * k);
|
||||
if top < room.min.y {
|
||||
o.y += room.min.y - top;
|
||||
} else if bottom > room.max.y {
|
||||
o.y -= bottom - room.max.y;
|
||||
}
|
||||
Some((k, o))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// #577: every font's "Sample" preview lands inside its row's preview box: at its natural size
|
||||
/// when it fits, else scaled down; nothing for no outlines.
|
||||
#[test]
|
||||
fn font_previews_fit_their_row() {
|
||||
let room = Rect::from_min_max(pos2(180.0, 101.0), pos2(294.0, 119.0));
|
||||
let baseline = 115.0;
|
||||
let inside = |lines: &[Vec<[f32; 2]>]| {
|
||||
let (k, o) = fit_preview(lines, room, baseline).expect("a preview");
|
||||
for p in lines.iter().flatten() {
|
||||
let q = o + vec2(p[0], p[1]) * k;
|
||||
assert!(room.expand(0.01).contains(pos2(q.x, q.y)), "{p:?} → {q:?} outside {room:?}");
|
||||
}
|
||||
k
|
||||
};
|
||||
// A plain 14 px sample fits as it is, on the baseline.
|
||||
let plain = vec![vec![[0.0, -10.0], [60.0, -10.0], [60.0, 3.0], [0.0, 3.0]]];
|
||||
assert_eq!(inside(&plain), 1.0);
|
||||
assert_eq!(fit_preview(&plain, room, baseline).map(|(_, o)| o.y), Some(baseline));
|
||||
// Huge, wide, tall, offset and negative-bearing outlines are scaled into the box.
|
||||
for lines in [
|
||||
vec![vec![[0.0, -80.0], [400.0, 30.0]]],
|
||||
vec![vec![[-50.0, -5.0], [500.0, 2.0]]],
|
||||
vec![vec![[10.0, -200.0], [12.0, 0.0]]],
|
||||
vec![vec![[0.0, 20.0], [30.0, 40.0]]],
|
||||
] {
|
||||
assert!(inside(&lines) <= 1.0);
|
||||
}
|
||||
assert!(fit_preview(&[], room, baseline).is_none());
|
||||
assert!(fit_preview(&[vec![[f32::NAN, 1.0]]], room, baseline).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,11 +58,6 @@ fn classic_geometry_row(comp: &Comp, l: &Layer) -> bool {
|
||||
comp.renderer == effectcraft_engine::project::Renderer::Classic3D && l.is_3d() && matches!(l.source, LayerSource::Text | LayerSource::Shape)
|
||||
}
|
||||
|
||||
/// Time navigator's visible-span bar and the work area bar.
|
||||
const NAV_BAR: Color32 = Color32::from_rgb(0x55, 0x55, 0x55);
|
||||
const WORK_AREA_BAR: Color32 = Color32::from_rgb(0x5c, 0x5c, 0x5c);
|
||||
/// Fill of the timeline's switch / A/V boxes (dark wells, as in After Effects).
|
||||
const SWITCH_BOX: Color32 = Color32::from_rgb(0x19, 0x19, 0x19);
|
||||
/// Background of the selected layer's name cell.
|
||||
const SELECTED_NAME_BG: Color32 = Color32::from_rgb(0xa6, 0xa6, 0xa6);
|
||||
|
||||
@@ -212,6 +207,29 @@ fn edge_scroll_speed(rows: Rect, y: f32, zone: f32) -> f32 {
|
||||
(depth / zone).clamp(-3.0, 3.0) * 400.0
|
||||
}
|
||||
|
||||
/// Autoscroll speed (points per second, left negative) of a ruler scrub held at `x`, past the
|
||||
/// left (`x0`) or right (`x1`) end of the visible time span: faster the further past.
|
||||
fn edge_scroll_speed_x(x0: f32, x1: f32, x: f32) -> f32 {
|
||||
let depth = if x < x0 {
|
||||
x - x0
|
||||
} else if x > x1 {
|
||||
x - x1
|
||||
} else {
|
||||
return 0.0;
|
||||
};
|
||||
(depth / 40.0).clamp(-3.0, 3.0) * 400.0 + depth.signum() * 100.0
|
||||
}
|
||||
|
||||
/// The timeline's first visible time (`start`, showing `span` seconds of a `duration` comp)
|
||||
/// paged so the CTI at `cti` is in view: unchanged while it is, else the page that starts at
|
||||
/// the CTI (as After Effects pages the Timeline during a preview).
|
||||
fn page_to_cti(start: f64, span: f64, duration: f64, cti: f64) -> f64 {
|
||||
if !(start.is_finite() && span.is_finite() && cti.is_finite()) || (cti >= start && cti <= start + span) {
|
||||
return start;
|
||||
}
|
||||
cti.min(duration - span).max(0.0)
|
||||
}
|
||||
|
||||
/// The text of an expression being edited when its pick whip was pressed, and the selection in
|
||||
/// it (characters): the pick whip's reference goes in there.
|
||||
type WhipInto = (String, [usize; 2]);
|
||||
@@ -1189,6 +1207,34 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let ctx = ui.ctx().clone();
|
||||
let Some(cid) = app.session.active_comp_id() else {
|
||||
ui.painter().text(rect.center(), Align2::CENTER_CENTER, "(no composition)", Tokens::ui(12.0), t.text_faint);
|
||||
// Dropping footage into an empty Timeline should create its first composition,
|
||||
// just like dropping onto the Project panel's New Composition button (#649).
|
||||
if let Some(crate::panels::DragPayload::Item(dragged)) = egui::DragAndDrop::payload::<crate::panels::DragPayload>(&ctx).as_deref()
|
||||
&& ui.rect_contains_pointer(rect)
|
||||
{
|
||||
let items: Vec<ItemId> = crate::panels::project_drop_items(app, *dragged)
|
||||
.into_iter()
|
||||
.map(ItemId)
|
||||
.filter(|id| {
|
||||
app.session.project.item(*id).is_some_and(|item| match &item.kind {
|
||||
effectcraft_engine::project::ItemKind::Footage(footage) => footage.kind != effectcraft_engine::project::FootageKind::Data,
|
||||
effectcraft_engine::project::ItemKind::Solid(_) | effectcraft_engine::project::ItemKind::Comp(_) => true,
|
||||
_ => false,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
if !items.is_empty() {
|
||||
ui.painter().rect_stroke(rect.shrink(2.0), 0.0, Stroke::new(2.0, t.accent), StrokeKind::Inside);
|
||||
app.auto.add("timeline.newCompDrop", rect, "Drop footage to create a composition");
|
||||
if ctx.input(|i| i.pointer.any_released()) {
|
||||
app.session.state.project_selection = items;
|
||||
if let Err(e) = crate::menus::invoke(app, &ctx, "file.newCompFromSelection", json!({})) {
|
||||
app.ui.status = e;
|
||||
}
|
||||
egui::DragAndDrop::clear_payload(&ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
};
|
||||
let Some(comp) = app.session.project.comp_arc(cid) else { return };
|
||||
@@ -1217,6 +1263,10 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let pps = app.ui.timeline.pps.unwrap_or(fit_pps);
|
||||
if app.ui.timeline.pps.is_none() {
|
||||
app.ui.timeline.start = 0.0;
|
||||
} else if app.playback.playing {
|
||||
// During playback the view pages to keep the CTI in sight (After Effects).
|
||||
let span = ((graph_x1 - graph_x0 - 6.0) as f64 / pps).max(0.0);
|
||||
app.ui.timeline.start = page_to_cti(app.ui.timeline.start, span, comp.duration.seconds(), app.session.time().seconds());
|
||||
}
|
||||
let tm = TMap { x0: graph_x0 + 6.0, start: app.ui.timeline.start, pps };
|
||||
ctx.data_mut(|d| d.insert_temp(tl_map_id(), (tm.x0, tm.start, tm.pps)));
|
||||
@@ -1308,7 +1358,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let vis1 = (tm.t(graph_x1) / comp.duration.seconds()) as f32;
|
||||
let nav_vis =
|
||||
Rect::from_min_max(pos2(nav.min.x + nav.width() * vis0.clamp(0.0, 1.0), nav.min.y), pos2(nav.min.x + nav.width() * vis1.clamp(0.0, 1.0), nav.max.y));
|
||||
p.rect_filled(nav_vis, 0.0, NAV_BAR);
|
||||
p.rect_filled(nav_vis, 0.0, t.tl_nav_bar);
|
||||
for x in [nav_vis.min.x, nav_vis.max.x] {
|
||||
p.rect_filled(Rect::from_min_max(pos2(x - 3.0, nav.min.y - 1.0), pos2(x + 3.0, nav.max.y + 1.0)), 3.0, t.accent);
|
||||
}
|
||||
@@ -1348,7 +1398,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let wa_row = Rect::from_min_max(pos2(graph_x0, top + header_h), pos2(rect.max.x, top + header_h + colhdr_h));
|
||||
let (wa0, wa1) = (comp.work_area.0.seconds(), comp.work_area.1.seconds());
|
||||
let wa = Rect::from_min_max(pos2(tm.x(wa0), wa_row.min.y + 3.0), pos2(tm.x(wa1), wa_row.max.y - 6.0));
|
||||
p.with_clip_rect(wa_row).rect_filled(wa, 0.0, WORK_AREA_BAR);
|
||||
p.with_clip_rect(wa_row).rect_filled(wa, 0.0, t.tl_work_area_bar);
|
||||
let shift = ui.input(|i| i.modifiers.shift);
|
||||
let bar = wa.intersect(wa_row);
|
||||
let bresp = ui.interact(bar, egui::Id::new("wa-bar"), Sense::click_and_drag());
|
||||
@@ -1482,7 +1532,24 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
if ((rresp.is_pointer_button_down_on() && ui.input(|i| i.pointer.primary_down())) || rresp.clicked())
|
||||
&& let Some(pt) = rresp.interact_pointer_pos()
|
||||
{
|
||||
let mut secs = tm.t(pt.x).max(0.0);
|
||||
let mut x = pt.x;
|
||||
// Zoomed in, a scrub held past either end of the ruler scrolls the timeline that way
|
||||
// (faster the further), with the CTI at the edge (After Effects).
|
||||
let mut tm = tm;
|
||||
if rresp.dragged() && app.ui.timeline.pps.is_some() {
|
||||
let speed = edge_scroll_speed_x(tm.x0, graph_x1, x);
|
||||
if speed != 0.0 {
|
||||
let dt = f64::from(ui.input(|i| i.stable_dt).clamp(0.0, 0.1));
|
||||
let span = f64::from(graph_x1 - tm.x0) / pps;
|
||||
let cur = app.ui.timeline.start;
|
||||
let hi = (comp.duration.seconds() - span).max(0.0).max(cur);
|
||||
app.ui.timeline.start = (cur + f64::from(speed) * dt / pps).clamp(0.0, hi);
|
||||
tm.start = app.ui.timeline.start;
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
x = x.clamp(tm.x0, graph_x1);
|
||||
}
|
||||
let mut secs = tm.t(x).max(0.0);
|
||||
// Shift-drag: snap to keyframes, in/out points, markers and the work area (8 px).
|
||||
if ui.input(|i| i.modifiers.shift) {
|
||||
let cands = snap_candidates(&comp, &build_rows(app, &comp));
|
||||
@@ -1614,9 +1681,14 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let max_scroll = (total_h - rows_rect.height() + rh).max(0.0);
|
||||
if ui.rect_contains_pointer(rows_rect) {
|
||||
let (dy, dx, zoom) = ui.input(|i| (i.smooth_scroll_delta.y, i.smooth_scroll_delta.x, i.modifiers.alt));
|
||||
if zoom && dy.abs() > 0.0 {
|
||||
// Ctrl/Cmd+wheel and a trackpad pinch reach egui as a zoom factor rather than a scroll
|
||||
// (#428); like Alt+wheel they zoom time.
|
||||
let pinch = ui.input(|i| i.zoom_delta()) as f64;
|
||||
let at_x = ui.input(|i| i.pointer.hover_pos()).map(|p| p.x).unwrap_or(graph_x0);
|
||||
if (pinch - 1.0).abs() > 1e-4 {
|
||||
set_zoom(&mut app.ui.timeline, &comp, tm.pps * pinch, fit_pps, tm.t(at_x), (at_x - tm.x0) as f64);
|
||||
} else if zoom && dy.abs() > 0.0 {
|
||||
// Alt+wheel zooms around the pointer, out until the whole comp shows.
|
||||
let at_x = ui.input(|i| i.pointer.hover_pos()).map(|p| p.x).unwrap_or(graph_x0);
|
||||
set_zoom(&mut app.ui.timeline, &comp, tm.pps * (dy as f64 / 200.0).exp(), fit_pps, tm.t(at_x), (at_x - tm.x0) as f64);
|
||||
} else {
|
||||
let over_outline = ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| p.x < graph_x0);
|
||||
@@ -1687,7 +1759,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
// (outline and time graph alike), not as alternating stripes.
|
||||
let _ = ri;
|
||||
lp.rect_filled(left, 0.0, if is_sel { t.row_selected } else { t.row_alt });
|
||||
gp.rect_filled(Rect::from_min_max(pos2(graph_x0, r.min.y), r.max), 0.0, if is_sel { Color32::from_rgb(0x2a, 0x2a, 0x2a) } else { t.tl_bg });
|
||||
gp.rect_filled(Rect::from_min_max(pos2(graph_x0, r.min.y), r.max), 0.0, if is_sel { t.tl_graph_selected } else { t.tl_bg });
|
||||
lp.line_segment([pos2(rect.min.x, r.max.y - 0.5), pos2(graph_x0, r.max.y - 0.5)], Stroke::new(1.0, t.app_bg));
|
||||
gp.line_segment([pos2(graph_x0, r.max.y - 0.5), pos2(r.max.x, r.max.y - 0.5)], Stroke::new(1.0, t.app_bg));
|
||||
// A/V features.
|
||||
@@ -1703,7 +1775,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
if !applicable || !vis.av {
|
||||
continue;
|
||||
}
|
||||
lp.rect_filled(br.shrink(0.5), 1.0, SWITCH_BOX);
|
||||
lp.rect_filled(br.shrink(0.5), 1.0, t.switch_well);
|
||||
layer_switch(ui, &t, r, br, icon, on, egui::Id::new(("av", layer.id.0, i)), layer.id.0, name, &mut actions);
|
||||
app.auto.add(&format!("timeline.layer.{}.{name}", layer.id.0), br, name);
|
||||
}
|
||||
@@ -1829,7 +1901,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
continue;
|
||||
}
|
||||
let br = Rect::from_center_size(pos2(cw.switches + SW * i as f32 + SW / 2.0, cy), vec2(16.0, 16.0));
|
||||
lp.rect_filled(br.shrink(1.0), 1.0, SWITCH_BOX);
|
||||
lp.rect_filled(br.shrink(1.0), 1.0, t.switch_well);
|
||||
layer_switch(ui, &t, r, br, icon, on, egui::Id::new(("sw", layer.id.0, i)), layer.id.0, name, &mut actions);
|
||||
app.auto.add(&format!("timeline.layer.{}.switch.{name}", layer.id.0), br, name);
|
||||
}
|
||||
@@ -2184,7 +2256,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let en_r = Rect::from_center_size(pos2(cw.switches + 10.0, cy), vec2(16.0, 16.0));
|
||||
let en = ui.interact(en_r, egui::Id::new(("expr-en", uid)), Sense::click()).on_hover_text(crate::i18n::tr("Enable Expression"));
|
||||
lp.rect_stroke(en_r.shrink(1.0), 2.0, Stroke::new(1.0, t.separator), StrokeKind::Inside);
|
||||
let expr_col = Color32::from_rgb(0xe8, 0x7c, 0x5c);
|
||||
let expr_col = t.expr_text;
|
||||
lp.text(
|
||||
en_r.center(),
|
||||
Align2::CENTER_CENTER,
|
||||
@@ -2269,7 +2341,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
}
|
||||
// The editor in the time-graph area.
|
||||
ui.set_clip_rect(right_clip);
|
||||
gp.rect_filled(Rect::from_min_max(pos2(graph_x0, r.min.y), r.max), 0.0, Color32::from_rgb(0x1a, 0x1a, 0x1a));
|
||||
gp.rect_filled(Rect::from_min_max(pos2(graph_x0, r.min.y), r.max), 0.0, t.expr_bg);
|
||||
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 mut buf: String = ctx.data(|d| d.get_temp(buf_id)).unwrap_or_else(|| ex.text.clone());
|
||||
if let Some(after) = ctx.data_mut(|d| d.remove_temp::<usize>(expr_refocus_id(*uid))) {
|
||||
@@ -2388,13 +2460,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let is_tr_rot = layer.transform().and_then(|t| t.get("rotation")).is_some_and(|r| r.uid == prop.uid);
|
||||
let base = if is_tr_rot && prop.name == "Rotation" && layer.is_3d() { "Z Rotation".to_string() } else { prop.name.clone() };
|
||||
let pname = if prop.has_expression() { format!("{base} =") } else { base };
|
||||
lp.text(
|
||||
pos2(name_x, cy),
|
||||
Align2::LEFT_CENTER,
|
||||
&pname,
|
||||
Tokens::ui(12.0),
|
||||
if prop.has_expression() { Color32::from_rgb(0xe8, 0x7c, 0x5c) } else { t.text },
|
||||
);
|
||||
lp.text(pos2(name_x, cy), Align2::LEFT_CENTER, &pname, Tokens::ui(12.0), if prop.has_expression() { t.expr_text } else { t.text });
|
||||
let name_rect = Rect::from_min_max(pos2(name_x, r.min.y), pos2(cw.switches - 2.0, r.max.y));
|
||||
let name_resp = ui.interact(name_rect, egui::Id::new(("pname", uid)), Sense::click_and_drag());
|
||||
app.auto.add(&format!("timeline.prop.{uid}.name"), name_rect, &prop.name);
|
||||
@@ -2439,7 +2505,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
Align2::LEFT_CENTER,
|
||||
format!("= {}", e.text.lines().next().unwrap_or("")),
|
||||
Tokens::mono(11.0),
|
||||
Color32::from_rgb(0xe8, 0x7c, 0x5c),
|
||||
t.expr_text,
|
||||
);
|
||||
}
|
||||
// Keyframes.
|
||||
@@ -2959,9 +3025,14 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
rp.galley(tag.min, g, Color32::WHITE);
|
||||
}
|
||||
if released {
|
||||
let (index, time) = (json!(index), json!(start.map(Tick::seconds)));
|
||||
let time = json!(start.map(Tick::seconds));
|
||||
match payload.as_ref() {
|
||||
crate::panels::DragPayload::Item(id) => actions.push(("layer.addItem".into(), json!({"item": id, "index": index, "time": time}))),
|
||||
crate::panels::DragPayload::Item(id) => {
|
||||
// Insert each selected item at the drop point, in selection order.
|
||||
for (offset, item) in crate::panels::project_drop_items(app, *id).into_iter().enumerate() {
|
||||
actions.push(("layer.addItem".into(), json!({"item": item, "index": index.saturating_add(offset), "time": time.clone()})));
|
||||
}
|
||||
}
|
||||
crate::panels::DragPayload::Files(paths) => {
|
||||
actions.push(("mediaBrowser.import".into(), json!({"paths": paths, "addToComp": true, "index": index, "time": time})))
|
||||
}
|
||||
@@ -3440,26 +3511,6 @@ fn fmt_num(v: f64, d: usize) -> String {
|
||||
format!("{v:.d$}")
|
||||
}
|
||||
|
||||
/// Linked values after component `d` of `c` became `v`: the others scale by the same ratio
|
||||
/// (Constrain Proportions); from 0 the others that are 0 too follow the value.
|
||||
fn constrained(c: &[f64], d: usize, v: f64) -> Vec<f64> {
|
||||
let Some(&old) = c.get(d) else { return c.to_vec() };
|
||||
c.iter()
|
||||
.enumerate()
|
||||
.map(|(e, &x)| {
|
||||
if e == d {
|
||||
v
|
||||
} else if old.abs() > 1e-9 {
|
||||
x * v / old
|
||||
} else if x.abs() <= 1e-9 {
|
||||
v
|
||||
} else {
|
||||
x
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Inline value editor for a property row; pushes `prop.set` actions. Returns the rects of a
|
||||
/// multi-dimension value's fields, one per dimension (none for other values).
|
||||
fn value_editor(
|
||||
@@ -3476,8 +3527,11 @@ fn value_editor(
|
||||
let uid = prop.uid;
|
||||
let mut dims = vec![];
|
||||
let merge = format!("scrub-{uid}");
|
||||
// With several layers selected the edit applies to all of them (#491): a scrub by the same
|
||||
// change, a typed value as it is.
|
||||
let scrub = ui.ctx().dragged_id().is_some() && ui.input(|i| i.pointer.is_decidedly_dragging());
|
||||
let set = |actions: &mut Vec<(String, serde_json::Value)>, v: serde_json::Value| {
|
||||
actions.push(("prop.set".into(), json!({"layer": layer.id.0, "prop": uid, "value": v, "merge": merge})))
|
||||
actions.push(("prop.set".into(), json!({"layer": layer.id.0, "prop": uid, "value": v, "merge": merge, "selected": true, "offset": scrub})))
|
||||
};
|
||||
let is_3d = layer.is_3d();
|
||||
let mut x = at.x;
|
||||
@@ -3535,7 +3589,7 @@ fn value_editor(
|
||||
// Alt edits one value of a linked pair.
|
||||
let shown = if linked && !ui.input(|i| i.modifiers.alt) { n.min(c.len()) } else { 1 };
|
||||
let from = if shown == 1 { d } else { 0 };
|
||||
for (e, v) in constrained(c.get(from..from + shown).unwrap_or_default(), d - from, nv).into_iter().enumerate() {
|
||||
for (e, v) in widgets::constrained(c.get(from..from + shown).unwrap_or_default(), d - from, nv).into_iter().enumerate() {
|
||||
if let Some(slot) = nc.get_mut(from + e) {
|
||||
*slot = v;
|
||||
}
|
||||
@@ -3557,8 +3611,19 @@ fn value_editor(
|
||||
if resp.clicked() {
|
||||
widgets::open_popup(ui, pop);
|
||||
}
|
||||
// The eyedropper after the swatch samples the Composition panel (shape Fill and
|
||||
// Stroke colours, text and effect colours), as in After Effects' Timeline (#633).
|
||||
let er = Rect::from_center_size(pos2(r.max.x + 12.0, at.y), vec2(16.0, 16.0));
|
||||
let active = app.ui.fx_pick.as_ref().is_some_and(|k| k.prop == uid && k.kind == "color");
|
||||
if super::fx_widgets::eyedropper_button(ui, er, active, egui::Id::new(("tl-eye", uid)), &t)
|
||||
.on_hover_text(crate::i18n::tr("Eyedropper: click, then click in the Composition panel"))
|
||||
.clicked()
|
||||
{
|
||||
super::effect_controls::toggle_pick(app, "color", layer, prop);
|
||||
}
|
||||
app.auto.add(&format!("timeline.prop.{uid}.eyedropper"), er, &prop.name);
|
||||
let mut rgb = [c[0] as f32, c[1] as f32, c[2] as f32];
|
||||
if crate::header::color_popup(ui, pop, r.left_bottom(), &mut rgb) {
|
||||
if crate::widgets::color_popup(ui, pop, r.left_bottom(), &mut rgb) {
|
||||
set(actions, json!([rgb[0], rgb[1], rgb[2], 1.0]));
|
||||
}
|
||||
}
|
||||
@@ -3619,6 +3684,20 @@ fn value_editor(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// #468: playback pages the view to the CTI; a scrub past either end scrolls that way.
|
||||
#[test]
|
||||
fn the_view_pages_to_the_cti() {
|
||||
assert_eq!(page_to_cti(10.0, 5.0, 60.0, 12.0), 10.0, "in view: unchanged");
|
||||
assert_eq!(page_to_cti(10.0, 5.0, 60.0, 16.0), 16.0, "past the right end: the page from the CTI");
|
||||
assert_eq!(page_to_cti(10.0, 5.0, 60.0, 3.0), 3.0, "before the start");
|
||||
assert_eq!(page_to_cti(10.0, 5.0, 60.0, 58.0), 55.0, "not past the comp's end");
|
||||
assert_eq!(page_to_cti(10.0, 80.0, 60.0, 95.0), 0.0);
|
||||
assert_eq!(page_to_cti(10.0, f64::NAN, 60.0, 95.0), 10.0);
|
||||
assert_eq!(edge_scroll_speed_x(100.0, 500.0, 300.0), 0.0);
|
||||
assert!(edge_scroll_speed_x(100.0, 500.0, 501.0) > 0.0 && edge_scroll_speed_x(100.0, 500.0, 99.0) < 0.0);
|
||||
assert!(edge_scroll_speed_x(100.0, 500.0, 600.0) > edge_scroll_speed_x(100.0, 500.0, 520.0));
|
||||
}
|
||||
|
||||
/// A comp with two solids; "Box" has an animated Position and a Gaussian Blur.
|
||||
fn app() -> EffectcraftApp {
|
||||
let mut s = effectcraft_engine::Session::default();
|
||||
|
||||
@@ -508,7 +508,8 @@ pub fn options_dialog(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens)
|
||||
ui.horizontal(|ui| {
|
||||
let r = ui.checkbox(&mut d.blur_on, crate::i18n::tr("Blur"));
|
||||
app.auto.add("dialog.trackOptions.blurOn", r.rect, "Blur");
|
||||
let r = ui.add_enabled(d.blur_on, egui::DragValue::new(&mut d.opts.blur).speed(0.1).range(0.5..=50.0).suffix(" pixels"));
|
||||
let r =
|
||||
ui.add_enabled(d.blur_on, crate::widgets::drag_value(egui::DragValue::new(&mut d.opts.blur).speed(0.1).range(0.5..=50.0).suffix(" pixels")));
|
||||
app.auto.add("dialog.trackOptions.blur", r.rect, "Blur pixels");
|
||||
let r = ui.checkbox(&mut d.opts.enhance, crate::i18n::tr("Enhance"));
|
||||
app.auto.add("dialog.trackOptions.enhance", r.rect, "Enhance");
|
||||
@@ -539,7 +540,7 @@ pub fn options_dialog(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens)
|
||||
.response;
|
||||
app.auto.add("dialog.trackOptions.action", r.rect, "If Confidence is Below action");
|
||||
ui.label(crate::i18n::tr("If Confidence is Below"));
|
||||
let r = ui.add(egui::DragValue::new(&mut d.opts.threshold).speed(0.5).range(0.0..=100.0).suffix(" %"));
|
||||
let r = ui.add(crate::widgets::drag_value(egui::DragValue::new(&mut d.opts.threshold).speed(0.5).range(0.0..=100.0).suffix(" %")));
|
||||
app.auto.add("dialog.trackOptions.threshold", r.rect, "Confidence threshold");
|
||||
});
|
||||
(ok, cancel) = ok_cancel(ui, app, t, "dialog.trackOptions");
|
||||
|
||||
@@ -84,12 +84,17 @@ enum Gesture {
|
||||
/// Layer pixels → comp as the drag began, and its inverse.
|
||||
l2c: Mat3,
|
||||
inv: Mat3,
|
||||
/// The other selected layers and their scales as the drag began: they scale by the same
|
||||
/// ratio about their own anchor points, as in After Effects (#491).
|
||||
others: Vec<(LayerId, [f64; 3])>,
|
||||
},
|
||||
Rotate {
|
||||
layer: LayerId,
|
||||
center: Pos2,
|
||||
start_angle: f64,
|
||||
start_rot: f64,
|
||||
/// The other selected layers and their rotations: they turn by the same angle.
|
||||
others: Vec<(LayerId, f64)>,
|
||||
},
|
||||
Anchor {
|
||||
layer: LayerId,
|
||||
@@ -258,17 +263,97 @@ pub(crate) fn fx2c(ctx: &EvalCtx, layer: &Layer) -> Mat3 {
|
||||
from_effect_space(ctx, layer, l2c(ctx, layer).0)
|
||||
}
|
||||
|
||||
/// Layer → comp matrix and its bounds quad (in comp pixels).
|
||||
/// The selected, unlocked layers of `comp` other than `layer` (when `layer` is one of them): a
|
||||
/// handle or Rotation tool drag on one changes them all.
|
||||
fn selected_others<'a>(app: &EffectcraftApp, comp: &'a Comp, layer: LayerId) -> Vec<&'a Layer> {
|
||||
let sel = &app.session.state.selected_layers;
|
||||
if !sel.contains(&layer) {
|
||||
return vec![];
|
||||
}
|
||||
sel.iter().filter(|id| **id != layer).filter_map(|id| comp.layer(*id)).filter(|l| !l.switches.locked && l.transform().is_some()).collect()
|
||||
}
|
||||
|
||||
/// The least homogeneous depth (`w`: the distance in front of a perspective camera in pixels, 1
|
||||
/// for 2D layers and orthographic views) a viewer outline is drawn at: points at or behind the
|
||||
/// camera would flip through infinity and draw long lines across the viewer (#572).
|
||||
const NEAR_W: f64 = 0.5;
|
||||
|
||||
/// `p` through the homography `m` before the perspective divide: (x, y, w).
|
||||
fn homogeneous(m: &Mat3, p: [f64; 2]) -> [f64; 3] {
|
||||
let r = |i: usize| m.0.get(i).map_or(0.0, |row| row[0] * p[0] + row[1] * p[1] + row[2]);
|
||||
[r(0), r(1), r(2)]
|
||||
}
|
||||
|
||||
/// The closed polygon `poly` (layer pixels) through `m`, clipped to the part in front of the
|
||||
/// camera's near plane (comp pixels; empty when none of it is).
|
||||
fn project_clipped(m: &Mat3, poly: &[[f64; 2]]) -> Vec<[f64; 2]> {
|
||||
let h: Vec<[f64; 3]> = poly.iter().map(|p| homogeneous(m, *p)).collect();
|
||||
let mut out = vec![];
|
||||
for (i, a) in h.iter().enumerate() {
|
||||
let Some(b) = h.get((i + 1) % h.len()) else { continue };
|
||||
let (ina, inb) = (a[2] >= NEAR_W, b[2] >= NEAR_W);
|
||||
if ina {
|
||||
out.push(*a);
|
||||
}
|
||||
if ina != inb {
|
||||
let t = (NEAR_W - a[2]) / (b[2] - a[2]);
|
||||
out.push([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, NEAR_W]);
|
||||
}
|
||||
}
|
||||
out.iter().map(|q| [q[0] / q[2], q[1] / q[2]]).filter(|q| q[0].is_finite() && q[1].is_finite()).collect()
|
||||
}
|
||||
|
||||
/// The segment a → b (world space) through the projection `pc`, clipped at the near plane.
|
||||
fn project_segment(pc: &effectcraft_engine::geom::Mat4, a: effectcraft_engine::geom::Vec3, b: effectcraft_engine::geom::Vec3) -> Option<[[f64; 2]; 2]> {
|
||||
let h = |p: effectcraft_engine::geom::Vec3| {
|
||||
let r = |i: usize| pc.0.get(i).map_or(0.0, |row| row[0] * p.x + row[1] * p.y + row[2] * p.z + row[3]);
|
||||
[r(0), r(1), r(3)]
|
||||
};
|
||||
let (mut ha, mut hb) = (h(a), h(b));
|
||||
if ha[2] < NEAR_W && hb[2] < NEAR_W {
|
||||
return None;
|
||||
}
|
||||
let cut = |p: [f64; 3], q: [f64; 3]| {
|
||||
let t = (NEAR_W - p[2]) / (q[2] - p[2]);
|
||||
[p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t, NEAR_W]
|
||||
};
|
||||
if ha[2] < NEAR_W {
|
||||
ha = cut(ha, hb);
|
||||
} else if hb[2] < NEAR_W {
|
||||
hb = cut(hb, ha);
|
||||
}
|
||||
let d = |q: [f64; 3]| [q[0] / q[2], q[1] / q[2]];
|
||||
let s = [d(ha), d(hb)];
|
||||
s.iter().flatten().all(|v| v.is_finite()).then_some(s)
|
||||
}
|
||||
|
||||
/// The content box corners (layer pixels) of `layer`.
|
||||
fn box_corners(b: [f64; 4]) -> [[f64; 2]; 4] {
|
||||
[[b[0], b[1]], [b[2], b[1]], [b[2], b[3]], [b[0], b[3]]]
|
||||
}
|
||||
|
||||
/// Layer → comp matrix and its bounds quad (in comp pixels). None for a 3D layer reaching to or
|
||||
/// behind the camera (its quad would flip; [`layer_outline`] draws the part in front).
|
||||
pub(crate) fn layer_quad(ctx: &EvalCtx, layer: &Layer) -> Option<(Mat3, [[f64; 2]; 4], [f64; 4])> {
|
||||
let b = effectcraft_engine::render::content_bounds(ctx, layer)?;
|
||||
let (m, _) = l2c(ctx, layer);
|
||||
let pts = [[b[0], b[1]], [b[2], b[1]], [b[2], b[3]], [b[0], b[3]]].map(|p| {
|
||||
let corners = box_corners(b);
|
||||
if corners.iter().any(|p| homogeneous(&m, *p)[2] < NEAR_W) {
|
||||
return None;
|
||||
}
|
||||
let pts = corners.map(|p| {
|
||||
let q = m.apply(gv2(p[0], p[1]));
|
||||
[q.x, q.y]
|
||||
});
|
||||
Some((m, pts, b))
|
||||
}
|
||||
|
||||
/// The outline of a layer's content box in comp pixels, clipped at the camera's near plane.
|
||||
pub(crate) fn layer_outline(ctx: &EvalCtx, layer: &Layer) -> Vec<[f64; 2]> {
|
||||
let Some(b) = effectcraft_engine::render::content_bounds(ctx, layer) else { return vec![] };
|
||||
project_clipped(&l2c(ctx, layer).0, &box_corners(b))
|
||||
}
|
||||
|
||||
/// Which axes a bounding-box handle scales: corners (0–3) both; the top and bottom edges (4, 6)
|
||||
/// y; the right and left edges (5, 7) x.
|
||||
fn handle_axes(handle: usize) -> [bool; 2] {
|
||||
@@ -522,10 +607,12 @@ fn locked_pane(app: &mut EffectcraftApp, ui: &mut egui::Ui, full: Rect, bg: Colo
|
||||
let cam = (lv.view != View3D::ActiveCamera && comp.has_3d())
|
||||
.then(|| app.session.state.views3d.get(&lv.comp).cloned().unwrap_or_default().cam(lv.view, comp.width as f64, comp.height as f64).state());
|
||||
let dc = effectcraft_engine::viewer::DisplayColor::of(&app.session);
|
||||
// The display conversion's inputs, keyed as in the main viewer's texture caches.
|
||||
let dc_key = format!("{cam:?}{}", super::viewer_tools::display_key(app, dc.is_some()));
|
||||
let key = {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
(app.session.revision, lv.comp.0, t.0, scale.to_bits(), format!("{cam:?}{}", dc.is_some())).hash(&mut h);
|
||||
(app.session.revision, lv.comp.0, t.0, scale.to_bits(), dc_key).hash(&mut h);
|
||||
h.finish()
|
||||
};
|
||||
let id = egui::Id::new("viewer-locked");
|
||||
@@ -785,6 +872,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let mut handle_hits: Vec<(LayerId, usize, Pos2, egui::CursorIcon)> = Vec::new();
|
||||
let mut vertex_hits: Vec<VertexHit> = Vec::new();
|
||||
let mut key_hits: Vec<ov::KeyHit> = Vec::new();
|
||||
let mut motion_frames: Vec<ov::PathFrame> = Vec::new();
|
||||
let mut paths: Vec<ov::PathInfo> = Vec::new();
|
||||
let sel_vertices = app.session.state.selected_vertices.clone();
|
||||
// Pen path in progress ends when the tool changes or its mask is gone; Esc / Enter also end
|
||||
@@ -804,7 +892,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
for l in comp.layers.iter().filter(|l| selected.contains(&l.id) && l.is_active_at(time)) {
|
||||
let col = if label_handles { t.label(l.label) } else { t.accent };
|
||||
// Motion path of animated position (keyframes and spatial tangents are draggable).
|
||||
ov::motion_path(app, &painter, &map, &ectx, l, col, &mut key_hits);
|
||||
ov::motion_path(app, &painter, &map, &ectx, l, col, &mut key_hits, &mut motion_frames);
|
||||
// Masks and shape paths.
|
||||
if app.ui.viewer.show_masks {
|
||||
let pen = ui.data(|d| d.get_temp::<(LayerId, u64)>(pen_id()));
|
||||
@@ -834,6 +922,12 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
}
|
||||
}
|
||||
let Some((m, q, _)) = layer_quad(&ectx, l) else {
|
||||
// A 3D layer reaching past the camera: the part of its box in front of it.
|
||||
let outline = layer_outline(&ectx, l);
|
||||
if outline.len() > 2 {
|
||||
painter.add(egui::Shape::closed_line(outline.iter().map(|p| map.to_screen(*p)).collect(), Stroke::new(1.0, col)));
|
||||
continue;
|
||||
}
|
||||
// Cameras, lights, empty layers: just the anchor.
|
||||
if let Some(tr) = l.transform() {
|
||||
let pos = ectx.v3(l, tr, "position", [0.0; 3]);
|
||||
@@ -866,15 +960,16 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let w = ectx.world_matrix(l);
|
||||
let pc = cam_state(&ectx).projection(cw as f64, ch as f64) * w;
|
||||
let a3 = effectcraft_engine::geom::vec3(a[0], a[1], a[2]);
|
||||
let o = pc.apply(a3);
|
||||
let len = 60.0 / zoom as f64;
|
||||
for (axis, col) in [
|
||||
(effectcraft_engine::geom::vec3(len, 0.0, 0.0), Color32::from_rgb(0xe0, 0x50, 0x50)),
|
||||
(effectcraft_engine::geom::vec3(0.0, len, 0.0), Color32::from_rgb(0x60, 0xd0, 0x60)),
|
||||
(effectcraft_engine::geom::vec3(0.0, 0.0, len), Color32::from_rgb(0x50, 0x8c, 0xf0)),
|
||||
] {
|
||||
let e = pc.apply(a3 + axis);
|
||||
painter.arrow(map.to_screen([o.x, o.y]), map.to_screen([e.x, e.y]) - map.to_screen([o.x, o.y]), Stroke::new(2.0, col));
|
||||
// (clipped at the camera's near plane, #572)
|
||||
if let Some([o, e]) = project_segment(&pc, a3, a3 + axis) {
|
||||
painter.arrow(map.to_screen(o), map.to_screen(e) - map.to_screen(o), Stroke::new(2.0, col));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -886,7 +981,8 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
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 q = layer_outline(&ectx, l);
|
||||
if q.len() > 2 {
|
||||
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 {
|
||||
@@ -1044,7 +1140,9 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
}
|
||||
}
|
||||
let gid = egui::Id::new("viewer-gesture");
|
||||
if let Some(hp) = resp.hover_pos() {
|
||||
// An overlay on top of the viewer (e.g. the camera tracker points) takes the hover, but the pointer is still over the viewer: keep wheel zoom working.
|
||||
let hover_pos = resp.hover_pos().or_else(|| if resp.contains_pointer() { ui.input(|i| i.pointer.hover_pos()) } else { None });
|
||||
if let Some(hp) = hover_pos {
|
||||
app.pointer_comp = Some({
|
||||
let c = map.to_comp(hp);
|
||||
[c[0] as f32, c[1] as f32]
|
||||
@@ -1056,7 +1154,15 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
Tool::Orbit => egui::CursorIcon::Alias,
|
||||
Tool::PanCamera => egui::CursorIcon::Move,
|
||||
Tool::Dolly => egui::CursorIcon::ResizeVertical,
|
||||
t if t.is_shape() || t.is_pen() => egui::CursorIcon::Crosshair,
|
||||
t if t.is_pen() => {
|
||||
pen_cursor(
|
||||
&ctx,
|
||||
hp,
|
||||
pen_cursor_icon(t, ov::segment_at(&paths, &map, hp, 5.0).is_some() || ov::motion_frame_at(&motion_frames, &key_hits, hp).is_some()),
|
||||
);
|
||||
egui::CursorIcon::None
|
||||
}
|
||||
t if t.is_shape() => egui::CursorIcon::Crosshair,
|
||||
_ if app.ui.viewer.roi_draw => egui::CursorIcon::Crosshair,
|
||||
t if t.puppet_kind().is_some() => match super::puppet_tool::hit(&pin_hits, hp) {
|
||||
Some((_, super::puppet_tool::PinPart::Ring)) => egui::CursorIcon::Alias,
|
||||
@@ -1104,7 +1210,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
&& ui.input(|i| i.pointer.primary_pressed())
|
||||
&& let Some(pos) = ui.input(|i| i.pointer.press_origin())
|
||||
{
|
||||
pen_press(app, ui, &ectx, &map, &paths, pos, mods);
|
||||
pen_press(app, ui, &ectx, &map, &paths, ov::motion_frame_at(&motion_frames, &key_hits, pos), pos, mods);
|
||||
}
|
||||
// A pen click (press + release without a drag) ends its tangent gesture on release.
|
||||
if ui.input(|i| i.pointer.primary_released())
|
||||
@@ -1150,6 +1256,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
}
|
||||
Tool::MaskFeather => ov::begin_feather(app, &ectx, &paths, &map, press).map(Gesture::Overlay),
|
||||
Tool::Rotate => pick(app, &ectx, cpt, mods.shift).map(|l| {
|
||||
let others = selected_others(app, &comp, l).into_iter().filter_map(|o| Some((o.id, ectx.f(o, o.transform()?, "rotation", 0.0)))).collect();
|
||||
let layer = comp.layer(l).cloned();
|
||||
let center = layer
|
||||
.as_ref()
|
||||
@@ -1157,7 +1264,13 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
.map(|p| map.to_screen([p[0], p[1]]))
|
||||
.unwrap_or(pos);
|
||||
let rot = layer.as_ref().and_then(|l| l.transform().map(|tr| ectx.f(l, tr, "rotation", 0.0))).unwrap_or(0.0);
|
||||
Gesture::Rotate { layer: l, center, start_angle: ((pos.y - center.y) as f64).atan2((pos.x - center.x) as f64).to_degrees(), start_rot: rot }
|
||||
Gesture::Rotate {
|
||||
layer: l,
|
||||
center,
|
||||
start_angle: ((pos.y - center.y) as f64).atan2((pos.x - center.x) as f64).to_degrees(),
|
||||
start_rot: rot,
|
||||
others,
|
||||
}
|
||||
}),
|
||||
Tool::PanBehind => pick(app, &ectx, cpt, false).and_then(|l| {
|
||||
let layer = comp.layer(l)?;
|
||||
@@ -1267,6 +1380,10 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
axes: handle_axes(hi),
|
||||
l2c,
|
||||
inv,
|
||||
others: selected_others(app, &comp, lid)
|
||||
.into_iter()
|
||||
.filter_map(|o| Some((o.id, ectx.v3(o, o.transform()?, "scale", [100.0; 3]))))
|
||||
.collect(),
|
||||
})
|
||||
})
|
||||
} else if let Some(l) = pick(app, &ectx, cpt, mods.shift) {
|
||||
@@ -1335,23 +1452,29 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
let _ = app.session.execute("prop.set", json!({"layer": lid.0, "path": "transform/position", "value": v, "merge": merge}));
|
||||
}
|
||||
}
|
||||
Gesture::Scale { layer, start_scale, start_local, handle, anchor, axes, l2c, inv } => {
|
||||
Gesture::Scale { layer, start_scale, start_local, handle, anchor, axes, l2c, inv, others } => {
|
||||
let lp = inv.apply(gv2(cpt[0], cpt[1]));
|
||||
let uniform = mods.shift && axes == [true, true];
|
||||
let f = drag_ratio(start_local, [lp.x - anchor[0], lp.y - anchor[1]], axes, uniform);
|
||||
// The handle snaps (to the comp's and other layers' edges, corners and centres),
|
||||
// so a layer scales exactly to them, e.g. to the comp's size.
|
||||
let f = snap_handle(f, handle, anchor, &l2c, axes, uniform, |p| vt::snap(app, &ctx, &ectx, &map, &[layer], &[p], mods));
|
||||
let v = [start_scale[0] * f[0], start_scale[1] * f[1], start_scale[2]];
|
||||
let _ = app.session.execute("prop.set", json!({"layer": layer.0, "path": "transform/scale", "value": v, "merge": merge}));
|
||||
for (lid, s0) in std::iter::once((layer, start_scale)).chain(others) {
|
||||
let v = [s0[0] * f[0], s0[1] * f[1], s0[2]];
|
||||
let _ = app.session.execute("prop.set", json!({"layer": lid.0, "path": "transform/scale", "value": v, "merge": merge}));
|
||||
}
|
||||
}
|
||||
Gesture::Rotate { layer, center, start_angle, start_rot } => {
|
||||
Gesture::Rotate { layer, center, start_angle, start_rot, others } => {
|
||||
let ang = ((pos.y - center.y) as f64).atan2((pos.x - center.x) as f64).to_degrees();
|
||||
let mut r = start_rot + (ang - start_angle);
|
||||
if mods.shift {
|
||||
r = (r / 45.0).round() * 45.0;
|
||||
}
|
||||
let _ = app.session.execute("prop.set", json!({"layer": layer.0, "path": "transform/rotation", "value": r, "merge": merge}));
|
||||
for (lid, r0) in others {
|
||||
let _ =
|
||||
app.session.execute("prop.set", json!({"layer": lid.0, "path": "transform/rotation", "value": r0 + (r - start_rot), "merge": merge}));
|
||||
}
|
||||
}
|
||||
Gesture::Anchor { layer, start_anchor, start_pos, start, inv, l2p, own, anchor_only } => {
|
||||
// Pan Behind snaps the anchor point (to its own layer's box, other layers' features,
|
||||
@@ -1589,19 +1712,35 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
}
|
||||
Tool::Type | Tool::TypeVertical => {}
|
||||
Tool::Pen | Tool::MaskFeather => {}
|
||||
// On a motion path (After Effects): Add Vertex adds a keyframe where it is clicked,
|
||||
// Delete Vertex removes the keyframe, Convert Vertex switches it between Linear and
|
||||
// Auto Bezier spatial interpolation.
|
||||
Tool::PenAdd => {
|
||||
if let Some((l, m, seg, tt)) = ov::segment_at(&paths, &map, pos, 6.0) {
|
||||
let _ = app.session.execute("mask.insertVertex", json!({"layer": l.0, "mask": m, "segment": seg, "t": tt}));
|
||||
} else if let Some(f) = ov::motion_frame_at(&motion_frames, &key_hits, pos) {
|
||||
add_motion_key(app, f);
|
||||
}
|
||||
}
|
||||
Tool::PenDelete => {
|
||||
if let Some(h) = vertex_at(pos, false) {
|
||||
let _ = app.session.execute("mask.deleteVertices", json!({"vertices": [{"layer": h.layer.0, "mask": h.mask, "index": h.index}]}));
|
||||
} else if let Some(k) = ov::motion_key_at(&key_hits, pos)
|
||||
&& select_motion_key(app, &k)
|
||||
{
|
||||
let _ = app.session.execute("keys.delete", json!({}));
|
||||
}
|
||||
}
|
||||
Tool::PenConvert => {
|
||||
if let Some(h) = vertex_at(pos, false) {
|
||||
let _ = app.session.execute("mask.convertVertex", json!({"layer": h.layer.0, "mask": h.mask, "index": h.index}));
|
||||
} else if let Some(k) = ov::motion_key_at(&key_hits, pos) {
|
||||
// A key showing direction handles becomes Linear; one without, Auto Bezier.
|
||||
let curved = key_hits.iter().any(|h| h.tangent.is_some() && h.layer == k.layer && h.prop == k.prop && h.time == k.time);
|
||||
if select_motion_key(app, &k) {
|
||||
let spatial = if curved { "linear" } else { "autoBezier" };
|
||||
let _ = app.session.execute("keys.interpolation", json!({"spatial": spatial}));
|
||||
}
|
||||
}
|
||||
}
|
||||
Tool::Selection if mods.alt && vertex_at(pos, false).is_some() => {
|
||||
@@ -1640,6 +1779,10 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) {
|
||||
_ => {
|
||||
if pick(app, &ectx, cpt, mods.shift).is_none() {
|
||||
let _ = app.session.execute("edit.deselectAll", json!({}));
|
||||
} else if !mods.shift && !app.session.state.selected_vertices.is_empty() && ov::segment_at(&paths, &map, pos, 6.0).is_none() {
|
||||
// A click away from the paths, even on their layer, deselects the mask
|
||||
// points (the layer stays selected), as in After Effects (#513).
|
||||
let _ = app.session.execute("mask.selectVertices", json!({"vertices": []}));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1789,7 +1932,60 @@ fn draw_rigs(app: &mut EffectcraftApp, painter: &egui::Painter, map: &ViewerMap,
|
||||
/// footage/solid layer (or shape layer, with Tool Creates Mask), a shape path (Shape n group with
|
||||
/// the Tools bar's Fill and Stroke) on the selected shape layer, or a new shape layer when
|
||||
/// nothing is selected. The placed point snaps.
|
||||
fn pen_press(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, map: &ViewerMap, paths: &[ov::PathInfo], pos: Pos2, mods: egui::Modifiers) {
|
||||
/// Add a Position keyframe at a motion path's frame, keeping the path where it is.
|
||||
fn add_motion_key(app: &mut EffectcraftApp, f: ov::PathFrame) {
|
||||
if let Err(e) = app.session.execute("prop.addKey", json!({"layer": f.layer.0, "prop": f.prop, "time": f.time.seconds()})) {
|
||||
app.ui.status = e.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
/// Select only the motion path's keyframe `k` (what the vertex tools act on).
|
||||
fn select_motion_key(app: &mut EffectcraftApp, k: &ov::KeyHit) -> bool {
|
||||
app.session.execute("keys.select", json!({"keys": [{"layer": k.layer.0, "prop": k.prop, "time": k.time.seconds()}]})).is_ok()
|
||||
}
|
||||
|
||||
/// The pointer for a Pen slot tool: the tool's own pen, the Pen showing Add Vertex's over a path
|
||||
/// it would add a point to (After Effects).
|
||||
fn pen_cursor_icon(tool: Tool, over_path: bool) -> crate::icons::Icon {
|
||||
use crate::icons::Icon;
|
||||
match tool {
|
||||
Tool::Pen if over_path => Icon::PenAdd,
|
||||
Tool::PenAdd => Icon::PenAdd,
|
||||
Tool::PenDelete => Icon::PenDelete,
|
||||
Tool::PenConvert => Icon::PenConvert,
|
||||
Tool::MaskFeather => Icon::MaskFeather,
|
||||
_ => Icon::Pen,
|
||||
}
|
||||
}
|
||||
|
||||
/// Paint pen pointer `icon` with its tip at `at`, outlined for any background.
|
||||
fn pen_cursor(ctx: &egui::Context, at: Pos2, icon: crate::icons::Icon) {
|
||||
use crate::icons::Icon;
|
||||
// Where each glyph's tip sits in its 16 × 16 box.
|
||||
let tip = match icon {
|
||||
Icon::PenAdd | Icon::PenDelete | Icon::MaskFeather => vec2(6.0, 2.5),
|
||||
Icon::PenConvert => vec2(8.0, 3.5),
|
||||
_ => vec2(8.0, 1.8),
|
||||
};
|
||||
let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("viewer-pen-cursor")));
|
||||
let rect = Rect::from_min_size(at - tip, vec2(16.0, 16.0));
|
||||
for d in [vec2(-1.0, 0.0), vec2(1.0, 0.0), vec2(0.0, -1.0), vec2(0.0, 1.0)] {
|
||||
crate::icons::paint(&painter, rect.translate(d), icon, Color32::BLACK);
|
||||
}
|
||||
crate::icons::paint(&painter, rect, icon, Color32::WHITE);
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn pen_press(
|
||||
app: &mut EffectcraftApp,
|
||||
ui: &mut egui::Ui,
|
||||
ectx: &EvalCtx,
|
||||
map: &ViewerMap,
|
||||
paths: &[ov::PathInfo],
|
||||
motion_frame: Option<ov::PathFrame>,
|
||||
pos: Pos2,
|
||||
mods: egui::Modifiers,
|
||||
) {
|
||||
use effectcraft_engine::project::LayerSource;
|
||||
let gid = egui::Id::new("viewer-gesture");
|
||||
let current: Option<(LayerId, u64)> = ui.data(|d| d.get_temp(pen_id()));
|
||||
@@ -1821,7 +2017,11 @@ fn pen_press(app: &mut EffectcraftApp, ui: &mut egui::Ui, ectx: &EvalCtx, map: &
|
||||
}
|
||||
return;
|
||||
}
|
||||
// On a visible path's segment the Pen adds a vertex there.
|
||||
// On a visible path's segment the Pen adds a vertex there; on a motion path, a keyframe.
|
||||
if let Some(f) = motion_frame {
|
||||
add_motion_key(app, f);
|
||||
return;
|
||||
}
|
||||
if let Some((l, m, seg, t)) = ov::segment_at(paths, map, pos, 5.0) {
|
||||
let _ = app.session.execute("mask.insertVertex", json!({"layer": l.0, "mask": m, "segment": seg, "t": t}));
|
||||
return;
|
||||
@@ -2147,14 +2347,7 @@ pub(crate) fn minify_factor(smooth: bool, pixels: f64, screen: f64) -> usize {
|
||||
if smooth && k >= 1.0 { k.min(256.0) as usize } else { 1 }
|
||||
}
|
||||
|
||||
pub(crate) fn hex_rgb(s: &str) -> Option<[u8; 3]> {
|
||||
let h = s.trim().trim_start_matches('#');
|
||||
if h.len() != 6 || !h.is_ascii() {
|
||||
return None;
|
||||
}
|
||||
let p = |i: usize| u8::from_str_radix(&h[i..i + 2], 16).ok();
|
||||
Some([p(0)?, p(2)?, p(4)?])
|
||||
}
|
||||
pub(crate) use crate::widgets::hex_rgb;
|
||||
|
||||
/// The Extended Viewer's render region for this frame (see [`ViewerState::extended`]):
|
||||
/// Settings ▸ 3D ▸ Extended Viewer on, the comp has 3D layers and the view is a custom 3D view
|
||||
@@ -2227,3 +2420,40 @@ fn show_frame(app: &mut EffectcraftApp, ctx: &egui::Context, key: crate::frames:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use effectcraft_engine::geom::{Mat4, vec3};
|
||||
|
||||
/// A perspective-like homography: w = 100 + y (the plane crosses the camera at y = −100).
|
||||
fn tilted() -> Mat3 {
|
||||
Mat3([[100.0, 0.0, 0.0], [0.0, 100.0, 0.0], [0.0, 1.0, 100.0]])
|
||||
}
|
||||
|
||||
/// #572: a box reaching behind the camera is clipped at the near plane instead of flipping
|
||||
/// through infinity into long lines.
|
||||
#[test]
|
||||
fn outlines_clip_at_the_near_plane() {
|
||||
let m = tilted();
|
||||
let front = project_clipped(&m, &box_corners([-50.0, -50.0, 50.0, 50.0]));
|
||||
assert_eq!(front.len(), 4);
|
||||
let crossing = project_clipped(&m, &box_corners([-50.0, -150.0, 50.0, 50.0]));
|
||||
assert_eq!(crossing.len(), 4, "{crossing:?}");
|
||||
// Nothing flipped through infinity: a corner behind the camera (y = −150, w = −50) would
|
||||
// land at y = +300 if it were projected as is; clipped at the near plane it runs off far
|
||||
// above (negative y) instead, and the front corners stay where they were.
|
||||
assert!(crossing.iter().all(|p| p[0].is_finite() && p[1].is_finite() && p[1] < 34.0), "{crossing:?}");
|
||||
assert!(project_clipped(&m, &box_corners([-50.0, -400.0, 50.0, -200.0])).is_empty(), "wholly behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gizmo_segments_clip_at_the_near_plane() {
|
||||
// w = 100 + z.
|
||||
let pc = Mat4([[100.0, 0.0, 0.0, 0.0], [0.0, 100.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 1.0, 100.0]]);
|
||||
let s = project_segment(&pc, vec3(10.0, 0.0, 0.0), vec3(10.0, 0.0, -300.0)).unwrap();
|
||||
assert_eq!(s[0], [10.0, 0.0]);
|
||||
assert!(s[1][0] > 10.0 && s[1][0].is_finite(), "toward the camera it grows, never flips: {s:?}");
|
||||
assert!(project_segment(&pc, vec3(0.0, 0.0, -200.0), vec3(0.0, 0.0, -300.0)).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,32 +23,37 @@ pub(crate) fn show(app: &mut EffectcraftApp, ui: &egui::Ui, painter: &egui::Pain
|
||||
let Some(ptr) = ctx.input(|i| i.pointer.hover_pos()).filter(|_| ui.rect_contains_pointer(map.area)) else { return };
|
||||
let stroke = Stroke::new(2.0, app.tokens.accent);
|
||||
let at = map.to_comp(ptr);
|
||||
let action: Option<(&str, Value)> = match payload.as_ref() {
|
||||
DragPayload::Effect(effect) => layer_at(ectx, at).map(|l| {
|
||||
if let Some((_, q, _)) = layer_quad(ectx, l) {
|
||||
painter.add(egui::Shape::closed_line(q.iter().map(|c| map.to_screen(*c)).collect(), stroke));
|
||||
}
|
||||
("effect.apply", json!({"effect": effect, "layers": [l.id.0]}))
|
||||
}),
|
||||
let actions: Vec<(&str, Value)> = match payload.as_ref() {
|
||||
DragPayload::Effect(effect) => layer_at(ectx, at)
|
||||
.map(|l| {
|
||||
if let Some((_, q, _)) = layer_quad(ectx, l) {
|
||||
painter.add(egui::Shape::closed_line(q.iter().map(|c| map.to_screen(*c)).collect(), stroke));
|
||||
}
|
||||
("effect.apply", json!({"effect": effect, "layers": [l.id.0]}))
|
||||
})
|
||||
.into_iter()
|
||||
.collect(),
|
||||
DragPayload::Item(item) => {
|
||||
// The layer's frame, centred on the pointer.
|
||||
if let Some([w, h]) = app.session.project.item(ItemId(*item)).and_then(|it| frame_size(&it.kind, ectx.comp.pixel_aspect)) {
|
||||
painter.rect_stroke(Rect::from_center_size(ptr, vec2(w, h) * map.zoom), 0.0, Stroke::new(1.0, app.tokens.accent), StrokeKind::Middle);
|
||||
}
|
||||
Some(("layer.addItem", json!({"item": item, "position": at})))
|
||||
// New layers go above the current selection, so insert in reverse
|
||||
// to preserve the order of the dragged Project items.
|
||||
crate::panels::project_drop_items(app, *item).into_iter().rev().map(|item| ("layer.addItem", json!({"item": item, "position": at}))).collect()
|
||||
}
|
||||
DragPayload::Files(paths) => Some(("mediaBrowser.import", json!({"paths": paths, "addToComp": true, "position": at}))),
|
||||
DragPayload::Property { .. } => None,
|
||||
DragPayload::Files(paths) => vec![("mediaBrowser.import", json!({"paths": paths, "addToComp": true, "position": at}))],
|
||||
DragPayload::Property { .. } => vec![],
|
||||
};
|
||||
if action.as_ref().is_some_and(|(id, _)| *id != "effect.apply") {
|
||||
if actions.first().is_some_and(|(id, _)| *id != "effect.apply") {
|
||||
painter.rect_stroke(map.area, 0.0, stroke, StrokeKind::Inside);
|
||||
}
|
||||
if ctx.input(|i| i.pointer.any_released()) {
|
||||
egui::DragAndDrop::clear_payload(&ctx);
|
||||
if let Some((id, params)) = action
|
||||
&& let Err(e) = crate::menus::invoke(app, &ctx, id, params)
|
||||
{
|
||||
app.ui.status = e;
|
||||
for (id, params) in actions {
|
||||
if let Err(e) = crate::menus::invoke(app, &ctx, id, params) {
|
||||
app.ui.status = e;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -248,6 +248,32 @@ pub(crate) struct KeyHit {
|
||||
pub p2c: Mat3,
|
||||
}
|
||||
|
||||
/// A frame on a motion path (one of its dots): where the Pen and Add Vertex tools add a
|
||||
/// keyframe.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct PathFrame {
|
||||
pub layer: LayerId,
|
||||
pub prop: u64,
|
||||
/// Layer time of the frame.
|
||||
pub time: Tick,
|
||||
pub pos: Pos2,
|
||||
}
|
||||
|
||||
/// The keyframe dot on a motion path under `pos`.
|
||||
pub(crate) fn motion_key_at(hits: &[KeyHit], pos: Pos2) -> Option<KeyHit> {
|
||||
hits.iter().rev().find(|h| h.tangent.is_none() && h.pos.distance(pos) < 6.0).copied()
|
||||
}
|
||||
|
||||
/// The motion-path frame nearest `pos` (within a few points) where a keyframe can be added: not
|
||||
/// on a keyframe dot already there.
|
||||
pub(crate) fn motion_frame_at(frames: &[PathFrame], hits: &[KeyHit], pos: Pos2) -> Option<PathFrame> {
|
||||
if motion_key_at(hits, pos).is_some() {
|
||||
return None;
|
||||
}
|
||||
let near = frames.iter().filter(|f| f.pos.distance(pos) < 5.0).min_by(|a, b| a.pos.distance(pos).total_cmp(&b.pos.distance(pos)))?;
|
||||
(!hits.iter().any(|h| h.tangent.is_none() && h.layer == near.layer && h.prop == near.prop && h.time == near.time)).then_some(*near)
|
||||
}
|
||||
|
||||
/// Parent space → comp matrix of a 2D layer at the context time.
|
||||
pub(crate) fn parent_to_comp(ectx: &EvalCtx, l: &Layer) -> Mat3 {
|
||||
match l.parent.and_then(|p| ectx.comp.layer(p)) {
|
||||
@@ -261,7 +287,17 @@ pub(crate) fn parent_to_comp(ectx: &EvalCtx, l: &Layer) -> Mat3 {
|
||||
|
||||
/// Draw the position motion path of a selected 2D layer: frame dots along the path, keyframe
|
||||
/// squares (filled when selected) and spatial Bezier tangent handles. Works through parents.
|
||||
pub(crate) fn motion_path(app: &mut EffectcraftApp, painter: &egui::Painter, map: &ViewerMap, ectx: &EvalCtx, l: &Layer, col: Color32, hits: &mut Vec<KeyHit>) {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn motion_path(
|
||||
app: &mut EffectcraftApp,
|
||||
painter: &egui::Painter,
|
||||
map: &ViewerMap,
|
||||
ectx: &EvalCtx,
|
||||
l: &Layer,
|
||||
col: Color32,
|
||||
hits: &mut Vec<KeyHit>,
|
||||
frames: &mut Vec<PathFrame>,
|
||||
) {
|
||||
let Some(pos) = l.transform().and_then(|tr| tr.get("position")) else { return };
|
||||
if pos.keys.len() < 2 || l.is_3d() {
|
||||
return;
|
||||
@@ -278,7 +314,9 @@ pub(crate) fn motion_path(app: &mut EffectcraftApp, painter: &egui::Painter, map
|
||||
let mut pts = vec![];
|
||||
let mut lt = lt0;
|
||||
while lt <= lt1 && pts.len() < 20_000 {
|
||||
pts.push(to_scr(pos.value_at(lt).as_vec3()));
|
||||
let q = to_scr(pos.value_at(lt).as_vec3());
|
||||
frames.push(PathFrame { layer: l.id, prop: pos.uid, time: lt, pos: q });
|
||||
pts.push(q);
|
||||
lt += fd;
|
||||
}
|
||||
pts.push(to_scr(pos.value_at(lt1).as_vec3()));
|
||||
|
||||
@@ -349,6 +349,14 @@ fn transformed(img: &egui::ColorImage, ch: Channel, colorized: bool, stops: f32,
|
||||
egui::ColorImage::new(img.size, px.into_iter().map(|a| Color32::from_rgba_premultiplied(a[0], a[1], a[2], a[3])).collect())
|
||||
}
|
||||
|
||||
/// The display conversion's inputs, for the texture caches.
|
||||
pub(crate) fn display_key(app: &EffectcraftApp, has_conversion: bool) -> String {
|
||||
let opts = &app.session.state.viewer;
|
||||
let custom = if opts.simulation.profile == vw::SimProfile::MyCustom { format!("{:?}", app.session.prefs.custom_rgb) } else { String::new() };
|
||||
format!("{:?}{:?}{}{custom}", has_conversion, opts.simulation, app.session.prefs.previews.display_profile)
|
||||
+ &format!("{:?}{:?}{}", app.session.project.settings.working_space, app.session.project.settings.output_space, opts.display_color_management)
|
||||
}
|
||||
|
||||
/// Draw the frame into `comp_rect`: the rendered frame (covering the region of interest when one
|
||||
/// is set), or the snapshot while Show Snapshot is on / F5 is held, through Show Channel and the
|
||||
/// exposure. Fast Previews ▸ Wireframe draws layer outlines instead.
|
||||
@@ -378,10 +386,7 @@ pub(crate) fn draw_frame(app: &mut EffectcraftApp, ctx: &egui::Context, painter:
|
||||
return;
|
||||
}
|
||||
let dc = vw::DisplayColor::of(&app.session);
|
||||
// The display conversion's inputs, for the texture caches.
|
||||
let custom = if opts.simulation.profile == vw::SimProfile::MyCustom { format!("{:?}", app.session.prefs.custom_rgb) } else { String::new() };
|
||||
let dc_key = format!("{:?}{:?}{}{custom}", dc.is_some(), opts.simulation, app.session.prefs.previews.display_profile)
|
||||
+ &format!("{:?}{:?}{}", app.session.project.settings.working_space, app.session.project.settings.output_space, opts.display_color_management);
|
||||
let dc_key = display_key(app, dc.is_some());
|
||||
let plain = opts.channel == Channel::Rgb && opts.exposure == 0.0 && dc.is_none();
|
||||
let uv = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0));
|
||||
if snap {
|
||||
@@ -704,11 +709,13 @@ fn bottom_bar_contents(app: &mut EffectcraftApp, ui: &mut egui::Ui, bar: Rect, z
|
||||
let mut ev = vo.exposure as f64;
|
||||
let resp = ui.put(
|
||||
er,
|
||||
egui::DragValue::new(&mut ev)
|
||||
.speed(0.05)
|
||||
.range(-40.0..=40.0)
|
||||
.fixed_decimals(1)
|
||||
.custom_formatter(|v, _| if v == 0.0 { "0.0".into() } else { format!("{v:+.1}") }),
|
||||
crate::widgets::drag_value(
|
||||
egui::DragValue::new(&mut ev)
|
||||
.speed(0.05)
|
||||
.range(-40.0..=40.0)
|
||||
.fixed_decimals(1)
|
||||
.custom_formatter(|v, _| if v == 0.0 { "0.0".into() } else { format!("{v:+.1}") }),
|
||||
),
|
||||
);
|
||||
let resp = resp.on_hover_text(crate::i18n::tr("Adjust Exposure (stops)"));
|
||||
app.auto.add_response("viewer.exposure", &resp, "Adjust Exposure");
|
||||
@@ -744,9 +751,23 @@ fn bottom_bar_contents(app: &mut EffectcraftApp, ui: &mut egui::Ui, bar: Rect, z
|
||||
x += 4.0;
|
||||
// 3D renderer + view.
|
||||
if comp.has_3d() {
|
||||
// The comp's 3D renderer, as After Effects' Composition panel shows it: the menu switches
|
||||
// it through Composition Settings (undoable), and the automation label is the renderer.
|
||||
use effectcraft_engine::project::Renderer;
|
||||
let renderers = [(Renderer::Classic3D, "Classic 3D", "classic3D"), (Renderer::Advanced3D, "Advanced 3D", "advanced3D")];
|
||||
let current = renderers.iter().find(|(r, ..)| *r == comp.renderer).map_or("Classic 3D", |(_, label, _)| *label);
|
||||
let r = Rect::from_min_size(pos2(x, cy - 10.0), vec2(96.0, 20.0));
|
||||
let response = widgets::dropdown(ui, r, "Classic 3D", &t, egui::Id::new("vw-3d"));
|
||||
app.auto.add_response("viewer.renderer3d", &response, "3D Renderer");
|
||||
if widgets::dropdown(ui, r, crate::i18n::tr(current), &t, egui::Id::new("vw-3d")).clicked() {
|
||||
toggle_popup(ui, "vw-3d-pop");
|
||||
}
|
||||
app.auto.add("viewer.renderer3d", r, current);
|
||||
let items: Vec<(String, bool)> = renderers.iter().map(|(r, label, _)| (label.to_string(), *r == comp.renderer)).collect();
|
||||
if let Some((renderer, _, id)) = popup(app, ui, "vw-3d-pop", r, &items, "renderer3dItem").and_then(|i| renderers.get(i))
|
||||
&& *renderer != comp.renderer
|
||||
&& let Err(e) = app.session.execute("comp.settings", json!({"renderer": id}))
|
||||
{
|
||||
app.ui.status = e.to_string();
|
||||
}
|
||||
x = r.max.x + 4.0;
|
||||
let cid = app.session.active_comp_id();
|
||||
let cur = cid.and_then(|c| app.session.state.views3d.get(&c)).map(|v| v.current).unwrap_or_default();
|
||||
|
||||
@@ -102,7 +102,9 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, id: u32, rect: Rect) {
|
||||
app.request_frame(cid, frame, scale);
|
||||
let key = app.frame_key(cid, frame, scale);
|
||||
if let Some((key, img)) = app.frames.get_for_viewer(&key, app.passive_tex.get(&id).map(|(k, _)| k)) {
|
||||
set_texture(app, &ctx, id, key, img);
|
||||
let dc = effectcraft_engine::viewer::DisplayColor::of(&app.session);
|
||||
let dkey = display_hash(&super::viewer_tools::display_key(app, dc.is_some()));
|
||||
set_texture(app, &ctx, id, key, img, dc, dkey);
|
||||
}
|
||||
match app.passive_tex.get(&id).filter(|(k, _)| k.comp == cid.0) {
|
||||
Some((_, tex)) => {
|
||||
@@ -126,16 +128,38 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, id: u32, rect: Rect) {
|
||||
}
|
||||
|
||||
/// Keep the frame viewer `id` shows in its texture.
|
||||
fn set_texture(app: &mut EffectcraftApp, ctx: &egui::Context, id: u32, key: FrameKey, img: FrameImage) {
|
||||
fn set_texture(
|
||||
app: &mut EffectcraftApp,
|
||||
ctx: &egui::Context,
|
||||
id: u32,
|
||||
key: FrameKey,
|
||||
img: FrameImage,
|
||||
dc: Option<effectcraft_engine::viewer::DisplayColor>,
|
||||
dkey: u64,
|
||||
) {
|
||||
let dc_id = egui::Id::new(("passive-viewer-display", id));
|
||||
let same_display = ctx.data(|d| d.get_temp::<u64>(dc_id)) == Some(dkey);
|
||||
if let Some((k, _)) = app.passive_tex.get_mut(&id)
|
||||
&& *k == key
|
||||
&& same_display
|
||||
{
|
||||
// An undo or an edit elsewhere can reuse this content at a newer revision. Keep that
|
||||
// revision as the lower bound for subsequent intermediate edit frames.
|
||||
k.revision = key.revision;
|
||||
return;
|
||||
}
|
||||
ctx.data_mut(|d| d.insert_temp(dc_id, dkey));
|
||||
let opts = super::viewer::zoom_texture_options(app.session.prefs.viewer_zoom_smooth());
|
||||
// The monitor conversion the active viewer applies (Use Display Color Management).
|
||||
let img = match (img, &dc) {
|
||||
(FrameImage::Cpu(img), Some(dc)) => {
|
||||
let mut px: Vec<[u8; 4]> = img.pixels.iter().map(|c| c.to_array()).collect();
|
||||
dc.apply(&mut px);
|
||||
let pixels = px.into_iter().map(|a| Color32::from_rgba_premultiplied(a[0], a[1], a[2], a[3])).collect();
|
||||
FrameImage::Cpu(Arc::new(egui::ColorImage::new(img.size, pixels)))
|
||||
}
|
||||
(img, _) => img,
|
||||
};
|
||||
let tex = match (img, app.passive_tex.remove(&id)) {
|
||||
(FrameImage::Cpu(img), Some((_, PassiveTexture::Cpu(mut h))))
|
||||
if h.size() == crate::frames::fitted_size(img.size, crate::frames::max_texture_side(ctx)) =>
|
||||
@@ -165,6 +189,14 @@ fn set_texture(app: &mut EffectcraftApp, ctx: &egui::Context, id: u32, key: Fram
|
||||
app.passive_tex.insert(id, (key, tex));
|
||||
}
|
||||
|
||||
/// A hash of the display conversion's inputs (see `viewer_tools::display_key`).
|
||||
fn display_hash(key: &str) -> u64 {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
key.hash(&mut h);
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// Give a passive viewer's texture back (GPU textures are registered with the renderer).
|
||||
fn free(app: &EffectcraftApp, tex: Option<PassiveTexture>) {
|
||||
if let (Some(PassiveTexture::Gpu(id, _)), Some(rs)) = (tex, &app.wgpu) {
|
||||
|
||||
@@ -0,0 +1,531 @@
|
||||
//! Continuous numeric scrubbing across native monitor edges.
|
||||
|
||||
use egui::{Context, Event, Id, PointerButton, Pos2, RawInput, Response, Vec2};
|
||||
#[cfg(any(not(target_arch = "wasm32"), test))]
|
||||
use egui::{Rect, pos2, vec2};
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct State {
|
||||
numeric: Option<(Id, u64)>,
|
||||
offset: Vec2,
|
||||
pending: Option<(Pos2, Pos2)>,
|
||||
disabled: bool,
|
||||
}
|
||||
|
||||
fn state_id() -> Id {
|
||||
Id::new("numeric-pointer-wrap")
|
||||
}
|
||||
|
||||
/// Opt in only number scrubs, never object, keyframe, panel or scrollbar drags.
|
||||
pub(crate) fn track(response: &Response) {
|
||||
if response.dragged_by(PointerButton::Primary) {
|
||||
let pass = response.ctx.cumulative_pass_nr();
|
||||
response.ctx.data_mut(|d| {
|
||||
let state = d.get_temp_mut_or_default::<State>(state_id());
|
||||
state.numeric = Some((response.id, pass));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep egui's drag coordinates continuous while the visible native pointer wraps.
|
||||
/// Rebase only when the OS acknowledges a successful warp: queued events from before
|
||||
/// it must not be interpreted as another monitor-width movement. A coalesced event
|
||||
/// may include a little real movement beyond the requested destination.
|
||||
/// Returns whether a numeric gesture ended, so the app can close its Undo group. `injected`:
|
||||
/// this frame carries pointer events from the control channel (an agent's `ui.drag`), whose
|
||||
/// gesture must never move the user's real cursor.
|
||||
pub(crate) fn prepare_input(ctx: &Context, raw: &mut RawInput, injected: bool) -> bool {
|
||||
let lost_focus = !raw.focused || raw.events.iter().any(|e| matches!(e, Event::WindowFocused(false)));
|
||||
let (down, last_pos, modifiers) = ctx.input(|i| (i.pointer.primary_down(), i.pointer.latest_pos(), i.modifiers));
|
||||
ctx.data_mut(|d| {
|
||||
let state = d.get_temp_mut_or_default::<State>(state_id());
|
||||
if lost_focus
|
||||
&& down
|
||||
&& state.numeric.is_some()
|
||||
&& let Some(pos) = last_pos
|
||||
{
|
||||
// The OS may deliver the eventual button-up to another app. Explicitly
|
||||
// finish this scrub so focus returning cannot restart it or leave Undo merged.
|
||||
raw.events.push(Event::PointerButton { pos: pos - state.offset, button: PointerButton::Primary, pressed: false, modifiers });
|
||||
}
|
||||
let touch = injected || raw.events.iter().any(|e| matches!(e, Event::Touch { .. }));
|
||||
if lost_focus
|
||||
|| touch
|
||||
|| raw.events.iter().any(|e| matches!(e, Event::WindowFocused(false) | Event::PointerButton { button: PointerButton::Primary, .. }))
|
||||
{
|
||||
let ended = state.numeric.is_some();
|
||||
*state = State { disabled: touch, ..Default::default() };
|
||||
return ended;
|
||||
}
|
||||
if state.numeric.is_none() {
|
||||
return false;
|
||||
}
|
||||
// Mouse capture can report leaving the client area mid-scrub. Keep the
|
||||
// drag's previous coordinate until its next captured movement arrives.
|
||||
raw.events.retain(|e| !matches!(e, Event::PointerGone));
|
||||
for event in &mut raw.events {
|
||||
let p = match event {
|
||||
Event::PointerMoved(p) | Event::PointerButton { pos: p, .. } => p,
|
||||
_ => continue,
|
||||
};
|
||||
if let Some((from, to)) = state.pending
|
||||
&& p.distance_sq(to) < p.distance_sq(from)
|
||||
{
|
||||
state.offset += from - to;
|
||||
state.pending = None;
|
||||
}
|
||||
*p += state.offset;
|
||||
}
|
||||
false
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(any(not(target_arch = "wasm32"), test))]
|
||||
fn wrap_target(p: Pos2, bounds: Rect) -> Option<Pos2> {
|
||||
if !p.is_finite() || !bounds.is_finite() || bounds.width() < 32.0 || bounds.height() < 32.0 {
|
||||
return None;
|
||||
}
|
||||
let axis = |v: f32, lo: f32, hi: f32| {
|
||||
if v <= lo + 2.0 {
|
||||
hi - 8.0
|
||||
} else if v >= hi - 2.0 {
|
||||
lo + 8.0
|
||||
} else {
|
||||
v
|
||||
}
|
||||
};
|
||||
let to = pos2(axis(p.x, bounds.min.x, bounds.max.x), axis(p.y, bounds.min.y, bounds.max.y));
|
||||
(to != p).then_some(to)
|
||||
}
|
||||
|
||||
#[cfg(any(not(target_arch = "wasm32"), test))]
|
||||
fn finish_frame(ctx: &Context, bounds: Rect, warp: impl FnOnce(Pos2) -> Option<Pos2>) {
|
||||
let state = ctx.data(|d| d.get_temp::<State>(state_id())).unwrap_or_default();
|
||||
let active = state.numeric.is_some_and(|(id, pass)| pass == ctx.cumulative_pass_nr() && ctx.is_being_dragged(id));
|
||||
let (down, focused, virtual_pos) = ctx.input(|i| (i.pointer.primary_down(), i.focused, i.pointer.latest_pos()));
|
||||
if !active || !down || !focused {
|
||||
ctx.data_mut(|d| d.remove::<State>(state_id()));
|
||||
return;
|
||||
}
|
||||
if state.disabled || state.pending.is_some() {
|
||||
return;
|
||||
}
|
||||
let Some(from) = virtual_pos.map(|p| p - state.offset) else { return };
|
||||
let Some(to) = wrap_target(from, bounds) else { return };
|
||||
let destination = warp(to);
|
||||
ctx.data_mut(|d| {
|
||||
let state = d.get_temp_mut_or_default::<State>(state_id());
|
||||
if let Some(to) = destination {
|
||||
state.pending = Some((from, to));
|
||||
} else {
|
||||
// Unsupported backends keep ordinary dragging; do not retry/log every frame.
|
||||
state.disabled = true;
|
||||
}
|
||||
});
|
||||
if destination.is_some() {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
/// Native monitor coordinates are physical pixels; egui input uses UI points.
|
||||
/// Use the monitor containing the original press, including negative desktop origins.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn finish_native(ctx: &Context, frame: &eframe::Frame) {
|
||||
let pass = ctx.cumulative_pass_nr();
|
||||
if !ctx.data(|d| d.get_temp::<State>(state_id()).is_some_and(|s| s.numeric.is_some_and(|(_, p)| p == pass))) {
|
||||
ctx.data_mut(|d| d.remove::<State>(state_id()));
|
||||
return;
|
||||
}
|
||||
let Some(window) = frame.winit_window() else { return };
|
||||
let Ok(origin) = window.inner_position() else { return };
|
||||
let ppp = ctx.pixels_per_point();
|
||||
if !ppp.is_finite() || ppp <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let Some(press) = ctx.input(|i| i.pointer.press_origin()) else { return };
|
||||
let screen_press = press * ppp + vec2(origin.x as f32, origin.y as f32);
|
||||
let monitor = window
|
||||
.available_monitors()
|
||||
.find(|m| {
|
||||
let p = m.position();
|
||||
let s = m.size();
|
||||
Rect::from_min_size(pos2(p.x as f32, p.y as f32), vec2(s.width as f32, s.height as f32)).contains(screen_press)
|
||||
})
|
||||
.or_else(|| window.current_monitor());
|
||||
let Some(monitor) = monitor else { return };
|
||||
let p = monitor.position();
|
||||
let s = monitor.size();
|
||||
let bounds = Rect::from_min_size(
|
||||
pos2((p.x as f64 - origin.x as f64) as f32, (p.y as f64 - origin.y as f64) as f32) / ppp,
|
||||
vec2(s.width as f32, s.height as f32) / ppp,
|
||||
);
|
||||
finish_frame(ctx, bounds, |to| {
|
||||
// Reuse winit's physical position type obtained above, now client-relative.
|
||||
let mut target = origin;
|
||||
target.x = (to.x * ppp).round() as i32;
|
||||
target.y = (to.y * ppp).round() as i32;
|
||||
match window.set_cursor_position(target) {
|
||||
// Remember the actual device pixel to avoid fractional-DPI drift on every wrap.
|
||||
Ok(()) => Some(pos2(target.x as f32 / ppp, target.y as f32 / ppp)),
|
||||
Err(e) => {
|
||||
log::warn!("numeric cursor wrap is unavailable: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use egui::{Event, Id, Modifiers, PointerButton, pos2, vec2};
|
||||
|
||||
struct Scrub {
|
||||
ctx: Context,
|
||||
value: f64,
|
||||
bounds: Rect,
|
||||
time: f64,
|
||||
accept_warp: bool,
|
||||
warps: Vec<Pos2>,
|
||||
standard: bool,
|
||||
ordinary: bool,
|
||||
angle: bool,
|
||||
angle_rects: Option<(Rect, Rect)>,
|
||||
modifiers: Modifiers,
|
||||
injected: bool,
|
||||
}
|
||||
|
||||
impl Scrub {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
ctx: Context::default(),
|
||||
value: 0.0,
|
||||
bounds: Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)),
|
||||
time: 0.0,
|
||||
accept_warp: true,
|
||||
warps: Vec::new(),
|
||||
standard: false,
|
||||
ordinary: false,
|
||||
angle: false,
|
||||
angle_rects: None,
|
||||
modifiers: Modifiers::NONE,
|
||||
injected: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn frame(&mut self, events: Vec<Event>, focused: bool) {
|
||||
self.time += 0.02;
|
||||
let mut raw = RawInput {
|
||||
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))),
|
||||
time: Some(self.time),
|
||||
events,
|
||||
focused,
|
||||
..Default::default()
|
||||
};
|
||||
raw.events.push(Event::ModifiersChanged(self.modifiers));
|
||||
prepare_input(&self.ctx, &mut raw, self.injected);
|
||||
let mut out = self.ctx.run_ui(raw, |ui| {
|
||||
if self.standard {
|
||||
ui.put(
|
||||
Rect::from_min_size(pos2(100.0, 100.0), vec2(60.0, 20.0)),
|
||||
crate::widgets::drag_value(egui::DragValue::new(&mut self.value).speed(1.0).max_decimals(3)),
|
||||
);
|
||||
} else if self.ordinary {
|
||||
ui.interact(Rect::from_min_size(pos2(100.0, 100.0), vec2(60.0, 20.0)), Id::new("ordinary"), egui::Sense::drag());
|
||||
} else if self.angle {
|
||||
let (rr, dr, value) = crate::panels::fx_widgets::angle_field(
|
||||
ui,
|
||||
pos2(100.0, 100.0),
|
||||
Id::new("scrub"),
|
||||
self.value,
|
||||
1,
|
||||
&crate::theme::Tokens::for_kind(crate::theme::ThemeKind::Dark),
|
||||
);
|
||||
self.angle_rects = Some((rr, dr));
|
||||
if let Some(v) = value {
|
||||
self.value = v;
|
||||
}
|
||||
} else {
|
||||
let (_, value, _) = crate::widgets::hot_number_at(
|
||||
ui,
|
||||
pos2(100.0, 100.0),
|
||||
Id::new("scrub"),
|
||||
self.value,
|
||||
1.0,
|
||||
(-1e9, 1e9),
|
||||
1,
|
||||
"",
|
||||
&crate::theme::Tokens::for_kind(crate::theme::ThemeKind::Dark),
|
||||
);
|
||||
if let Some(v) = value {
|
||||
self.value = v;
|
||||
}
|
||||
}
|
||||
finish_frame(ui.ctx(), self.bounds, |p| {
|
||||
self.warps.push(p);
|
||||
self.accept_warp.then_some(p)
|
||||
});
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
|
||||
fn move_to(&mut self, p: Pos2) {
|
||||
self.frame(vec![Event::PointerMoved(p)], true);
|
||||
}
|
||||
|
||||
fn begin(&mut self) {
|
||||
self.frame(vec![], true);
|
||||
let p = pos2(105.0, 108.0);
|
||||
self.frame(
|
||||
vec![Event::PointerMoved(p), Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }],
|
||||
true,
|
||||
);
|
||||
self.move_to(p + vec2(10.0, 0.0));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn angle_degrees_continue_across_zero_and_repeated_monitor_wraps() {
|
||||
for initial in [0.0, 359.5, -359.5, 720.0, -720.0] {
|
||||
for direction in [-1.0, 1.0] {
|
||||
let mut s = Scrub::new();
|
||||
s.angle = true;
|
||||
s.value = initial;
|
||||
s.frame(vec![], true);
|
||||
let p = s.angle_rects.unwrap().1.center();
|
||||
s.frame(
|
||||
vec![Event::PointerMoved(p), Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }],
|
||||
true,
|
||||
);
|
||||
let mut last = p;
|
||||
let mut expected = initial;
|
||||
// Feed small real movements, including zero/whole-turn crossings, then
|
||||
// the synthetic OS warp. Every real pixel contributes exactly once.
|
||||
for step in 0..800 {
|
||||
let direction = if step < 400 { direction } else { -direction };
|
||||
let next = pos2((last.x + direction * 13.0).clamp(1.0, 799.0), last.y);
|
||||
expected += f64::from(next.x - last.x) * 0.5;
|
||||
let count = s.warps.len();
|
||||
s.move_to(next);
|
||||
assert!((s.value - expected).abs() < 1e-6, "initial={initial}, direction={direction}, actual={}, expected={expected}", s.value);
|
||||
last = next;
|
||||
if s.warps.len() > count {
|
||||
last = *s.warps.last().unwrap();
|
||||
s.move_to(last);
|
||||
assert!((s.value - expected).abs() < 1e-6, "the teleport must not reset the angle");
|
||||
}
|
||||
}
|
||||
assert!(s.warps.len() >= 5);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numeric_drag_wraps_repeatedly_without_counting_the_teleport() {
|
||||
let mut s = Scrub::new();
|
||||
s.begin();
|
||||
for _ in 0..5 {
|
||||
s.move_to(pos2(799.0, 108.0));
|
||||
let target = *s.warps.last().expect("numeric drag must wrap at the monitor edge");
|
||||
assert!(target.x < 16.0);
|
||||
let before = s.value;
|
||||
s.move_to(target);
|
||||
assert_eq!(s.value, before, "the warp itself must not change the value");
|
||||
s.move_to(target + vec2(20.0, 0.0));
|
||||
assert_eq!(s.value, before + 20.0);
|
||||
}
|
||||
assert_eq!(s.warps.len(), 5);
|
||||
s.move_to(pos2(0.0, 108.0));
|
||||
let target = *s.warps.last().unwrap();
|
||||
assert!(target.x > 780.0);
|
||||
let before = s.value;
|
||||
s.move_to(target - vec2(3.0, 0.0));
|
||||
assert_eq!(s.value, before - 3.0, "coalesced movement after a left-edge warp is preserved");
|
||||
}
|
||||
|
||||
/// An agent's `ui.drag` over the control channel scrubs the value but never moves the user's
|
||||
/// real cursor, even at the window's (monitor's) edge.
|
||||
#[test]
|
||||
fn injected_drags_never_warp_the_real_cursor() {
|
||||
let mut s = Scrub::new();
|
||||
s.injected = true;
|
||||
s.begin();
|
||||
s.move_to(pos2(799.0, 108.0));
|
||||
assert!(s.warps.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normal_pointer_movement_does_not_warp() {
|
||||
let mut s = Scrub::new();
|
||||
s.move_to(pos2(799.0, 108.0));
|
||||
assert!(s.warps.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn standard_editor_wraps_at_top_bottom_and_corner_without_a_value_jump() {
|
||||
let mut s = Scrub::new();
|
||||
s.standard = true;
|
||||
s.begin();
|
||||
for edge in [pos2(200.0, 0.0), pos2(200.0, 599.0), pos2(799.0, 599.0)] {
|
||||
s.move_to(edge);
|
||||
let target = *s.warps.last().unwrap();
|
||||
assert_ne!(target, edge);
|
||||
let before = s.value;
|
||||
s.move_to(target);
|
||||
assert_eq!(s.value, before);
|
||||
s.move_to(target + vec2(5.0, -5.0));
|
||||
assert_eq!(s.value, before + 10.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn release_and_focus_loss_end_wrapping_and_restore_normal_hit_testing() {
|
||||
for lose_focus in [false, true] {
|
||||
let mut s = Scrub::new();
|
||||
s.begin();
|
||||
s.move_to(pos2(799.0, 108.0));
|
||||
let target = *s.warps.last().unwrap();
|
||||
s.move_to(target);
|
||||
let value = s.value;
|
||||
let events = if lose_focus {
|
||||
vec![Event::WindowFocused(false)]
|
||||
} else {
|
||||
vec![Event::PointerButton { pos: target, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }]
|
||||
};
|
||||
s.frame(events, !lose_focus);
|
||||
s.move_to(pos2(799.0, 108.0));
|
||||
assert_eq!(s.warps.len(), 1);
|
||||
assert_eq!(s.value, value);
|
||||
assert_eq!(s.ctx.input(|i| i.pointer.latest_pos()), Some(pos2(799.0, 108.0)));
|
||||
s.begin();
|
||||
s.move_to(pos2(799.0, 108.0));
|
||||
assert_eq!(s.warps.len(), 2, "the next independent drag still wraps");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_drag_does_not_wrap_and_failed_warp_is_not_retried() {
|
||||
let mut s = Scrub::new();
|
||||
s.ordinary = true;
|
||||
s.begin();
|
||||
s.move_to(pos2(799.0, 108.0));
|
||||
assert!(s.warps.is_empty());
|
||||
|
||||
let mut s = Scrub::new();
|
||||
s.accept_warp = false;
|
||||
s.begin();
|
||||
s.move_to(pos2(799.0, 108.0));
|
||||
for _ in 0..3 {
|
||||
s.move_to(pos2(799.0, 108.0));
|
||||
}
|
||||
assert_eq!(s.warps.len(), 1);
|
||||
let value = s.value;
|
||||
s.move_to(pos2(779.0, 108.0));
|
||||
assert_eq!(s.value, value - 20.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modifiers_keep_their_sensitivity_after_wrapping() {
|
||||
for (modifiers, multiplier) in [(Modifiers::SHIFT, 10.0), (Modifiers::COMMAND, 0.1)] {
|
||||
let mut s = Scrub::new();
|
||||
s.modifiers = modifiers;
|
||||
s.begin();
|
||||
s.move_to(pos2(799.0, 108.0));
|
||||
let target = *s.warps.last().unwrap();
|
||||
let value = s.value;
|
||||
s.move_to(target + vec2(10.0, 0.0));
|
||||
assert!((s.value - value - 10.0 * multiplier).abs() < 1e-8);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn monitor_rect_can_extend_beyond_the_app_and_have_a_negative_origin() {
|
||||
let mut s = Scrub::new();
|
||||
s.bounds = Rect::from_min_size(pos2(-200.0, -100.0), vec2(1200.0, 800.0));
|
||||
s.begin();
|
||||
s.move_to(pos2(999.0, 108.0));
|
||||
let target = *s.warps.last().unwrap();
|
||||
assert_eq!(target, pos2(-192.0, 108.0));
|
||||
let value = s.value;
|
||||
s.frame(vec![Event::PointerGone, Event::PointerMoved(target)], true);
|
||||
assert_eq!(s.value, value);
|
||||
s.move_to(target + vec2(10.0, 0.0));
|
||||
assert_eq!(s.value, value + 10.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_properties_and_angle_drags_keep_each_gesture_in_one_undo_step() {
|
||||
use crate::{EffectcraftApp, dock::PanelKind};
|
||||
use effectcraft_engine::project::LayerId;
|
||||
use eframe::App;
|
||||
use serde_json::json;
|
||||
|
||||
for angle in [false, true] {
|
||||
let mut session = effectcraft_host::session();
|
||||
session.execute("comp.new", json!({"width": 32, "height": 16})).unwrap();
|
||||
let lid = session.execute("layer.newSolid", json!({"width": 8, "height": 8})).unwrap()["layer"].as_u64().unwrap();
|
||||
let path = if angle { "transform/rotation" } else { "transform/position" };
|
||||
let prop = session.active_comp().unwrap().layer(LayerId(lid)).unwrap().props.prop(path).unwrap();
|
||||
let uid = prop.uid;
|
||||
let original = prop.value.clone();
|
||||
let undo = session.history.undo.len();
|
||||
let panel = PanelKind::Properties;
|
||||
let id = if angle { format!("properties.prop.{uid}.value") } else { format!("properties.prop.{uid}.value.0") };
|
||||
let mut app = EffectcraftApp::new(session);
|
||||
app.show_panel(panel);
|
||||
app.toggle_maximize(panel);
|
||||
let ctx = Context::default();
|
||||
let bounds = Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 1000.0));
|
||||
let mut frame = eframe::Frame::_new_kittest();
|
||||
let mut time = 0.0;
|
||||
let mut step = |app: &mut EffectcraftApp, events| {
|
||||
time += 1.0 / 60.0;
|
||||
let mut raw = RawInput { screen_rect: Some(bounds), time: Some(time), events, ..Default::default() };
|
||||
app.raw_input_hook(&ctx, &mut raw);
|
||||
let mut warp = None;
|
||||
let mut out = ctx.run_ui(raw, |ui| {
|
||||
app.logic(ui.ctx(), &mut frame);
|
||||
app.ui(ui, &mut frame);
|
||||
finish_frame(ui.ctx(), bounds, |p| {
|
||||
warp = Some(p);
|
||||
Some(p)
|
||||
});
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
warp
|
||||
};
|
||||
for _ in 0..4 {
|
||||
step(&mut app, vec![]);
|
||||
}
|
||||
for gesture in 1..=2 {
|
||||
let direction = if gesture == 1 { -1.0 } else { 1.0 };
|
||||
let r = app.auto.find(&id).unwrap().rect;
|
||||
let p = pos2(r[0] + r[2] / 2.0, r[1] + r[3] / 2.0);
|
||||
step(
|
||||
&mut app,
|
||||
vec![Event::PointerMoved(p), Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }],
|
||||
);
|
||||
step(&mut app, vec![Event::PointerMoved(p + vec2(direction * 10.0, 0.0))]);
|
||||
let mut last = p;
|
||||
for _ in 0..3 {
|
||||
let edge = if direction < 0.0 { 1.0 } else { 1599.0 };
|
||||
let target = step(&mut app, vec![Event::PointerMoved(pos2(edge, p.y))]).expect("real property scrubs wrap");
|
||||
let before = app.session.active_comp().unwrap().layer(LayerId(lid)).unwrap().props.find(uid).unwrap().value.clone();
|
||||
step(&mut app, vec![Event::PointerMoved(target)]);
|
||||
assert_eq!(app.session.active_comp().unwrap().layer(LayerId(lid)).unwrap().props.find(uid).unwrap().value, before);
|
||||
last = target + vec2(direction * 10.0, 0.0);
|
||||
step(&mut app, vec![Event::PointerMoved(last)]);
|
||||
if angle {
|
||||
let value = app.session.active_comp().unwrap().layer(LayerId(lid)).unwrap().props.find(uid).unwrap().value.as_f64();
|
||||
assert!((value - before.as_f64() - f64::from(direction) * 5.0).abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
step(&mut app, vec![Event::PointerButton { pos: last, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }]);
|
||||
assert_eq!(app.session.history.undo.len(), undo + gesture, "each drag is one undo step: {panel:?}");
|
||||
}
|
||||
app.session.execute("edit.undo", json!({})).unwrap();
|
||||
app.session.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(app.session.active_comp().unwrap().layer(LayerId(lid)).unwrap().props.find(uid).unwrap().value, original);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -88,7 +88,10 @@ pub fn dropped_files(app: &mut EffectcraftApp, ui: &egui::Ui, bounds: Rect) {
|
||||
None
|
||||
};
|
||||
|
||||
let params = json!({
|
||||
// Dropped files import as stills and folders' numbered stills as sequences; Alt-drag
|
||||
// imports a folder's files one by one (After Effects).
|
||||
let alt = ctx.input(|i| i.modifiers.alt);
|
||||
let mut params = json!({
|
||||
"paths": rest,
|
||||
"drag": true,
|
||||
"importAs": app.session.prefs.drag_import_as(),
|
||||
@@ -96,6 +99,9 @@ pub fn dropped_files(app: &mut EffectcraftApp, ui: &egui::Ui, bounds: Rect) {
|
||||
"position": at,
|
||||
"background": true
|
||||
});
|
||||
if alt {
|
||||
params["sequence"] = json!(false);
|
||||
}
|
||||
|
||||
if let Err(e) = crate::menus::invoke(app, &ctx, "file.import", params) {
|
||||
errors.push(crate::i18n::tr_args("Cannot import dropped files: {}", &[&e]));
|
||||
|
||||
@@ -81,6 +81,20 @@ pub struct Tokens {
|
||||
pub timecode: Color32,
|
||||
pub danger: Color32,
|
||||
pub warning: Color32,
|
||||
/// Effect Controls effect headers, and the header of the effect being worked on (it or one
|
||||
/// of its properties selected).
|
||||
pub fx_header: Color32,
|
||||
pub fx_header_active: Color32,
|
||||
/// Timeline: a selected layer's row in the time graph, the boxes behind the A/V and layer
|
||||
/// switches, the time navigator and the work area bar.
|
||||
pub tl_graph_selected: Color32,
|
||||
pub switch_well: Color32,
|
||||
pub tl_nav_bar: Color32,
|
||||
pub tl_work_area_bar: Color32,
|
||||
/// The Timeline's expression field and the colour of enabled expressions (their text and
|
||||
/// the names of properties that have one).
|
||||
pub expr_bg: Color32,
|
||||
pub expr_text: Color32,
|
||||
/// Label colours (`Label::ALL` order), from Settings ▸ Labels.
|
||||
pub labels: [Color32; 17],
|
||||
pub radius: f32,
|
||||
@@ -153,6 +167,14 @@ impl Tokens {
|
||||
timecode: Color32::from_rgb(0x3d, 0x8f, 0xf5),
|
||||
danger: Color32::from_rgb(0xe0, 0x4a, 0x3c),
|
||||
warning: Color32::from_rgb(0xe8, 0x9a, 0x2c),
|
||||
fx_header: Color32::from_rgb(0x2a, 0x2a, 0x2a),
|
||||
fx_header_active: Color32::from_rgb(0x2f, 0x3a, 0x52),
|
||||
tl_graph_selected: Color32::from_rgb(0x2a, 0x2a, 0x2a),
|
||||
switch_well: Color32::from_rgb(0x19, 0x19, 0x19),
|
||||
tl_nav_bar: Color32::from_rgb(0x55, 0x55, 0x55),
|
||||
tl_work_area_bar: Color32::from_rgb(0x5c, 0x5c, 0x5c),
|
||||
expr_bg: Color32::from_rgb(0x1a, 0x1a, 0x1a),
|
||||
expr_text: Color32::from_rgb(0xe8, 0x7c, 0x5c),
|
||||
labels: default_labels(),
|
||||
radius: 6.0,
|
||||
radius_sm: 3.0,
|
||||
@@ -202,6 +224,16 @@ impl Tokens {
|
||||
pasteboard: Color32::from_rgb(0xa8, 0xa8, 0xa8),
|
||||
// Keyframes have no outline: dark enough to stand out on the light time graph.
|
||||
keyframe: Color32::from_rgb(0x6c, 0x6c, 0x6c),
|
||||
// Custom-painted surfaces in the Light palette, so dark text stays readable on
|
||||
// them (#644).
|
||||
fx_header: Color32::from_rgb(0xd8, 0xd8, 0xd8),
|
||||
fx_header_active: Color32::from_rgb(0xb0, 0xcf, 0xec),
|
||||
tl_graph_selected: Color32::from_rgb(0xc2, 0xc2, 0xc2),
|
||||
switch_well: Color32::from_rgb(0xf2, 0xf2, 0xf2),
|
||||
tl_nav_bar: Color32::from_rgb(0x9a, 0x9a, 0x9a),
|
||||
tl_work_area_bar: Color32::from_rgb(0x94, 0x94, 0x94),
|
||||
expr_bg: Color32::from_rgb(0xf2, 0xf2, 0xf2),
|
||||
expr_text: Color32::from_rgb(0xa3, 0x34, 0x17),
|
||||
..dark
|
||||
},
|
||||
}
|
||||
@@ -268,6 +300,10 @@ impl Tokens {
|
||||
&mut self.tl_ruler_bg,
|
||||
&mut self.pasteboard,
|
||||
&mut self.work_area,
|
||||
&mut self.fx_header,
|
||||
&mut self.tl_graph_selected,
|
||||
&mut self.switch_well,
|
||||
&mut self.expr_bg,
|
||||
] {
|
||||
adj(c);
|
||||
}
|
||||
@@ -339,8 +375,9 @@ const SCRIPT_PROBES: &[(char, &str)] = &[
|
||||
/// Japanese-locale machine would be drawn with the Japanese face. The interface language is the
|
||||
/// better signal, so the probe for its script comes first — kana for Japanese, a Han character for
|
||||
/// the Chinese catalogs. Both scripts are registered, so file, layer and template names in the
|
||||
/// other one still render; then [`SCRIPT_PROBES`]. The web build has no system fonts and installs
|
||||
/// nothing.
|
||||
/// other one still render; then [`SCRIPT_PROBES`], then Hangul, since the Japanese and Chinese faces
|
||||
/// may lack it (Hiragino Sans on macOS has none). The web build has no system fonts
|
||||
/// and installs nothing.
|
||||
fn install_script_fallbacks(family_fonts: &mut FontDefinitions, language: &str) -> Vec<String> {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
@@ -354,13 +391,17 @@ fn install_script_fallbacks(family_fonts: &mut FontDefinitions, language: &str)
|
||||
// language's face draws them.
|
||||
const KANA: (char, &str) = ('あ', "japanese-system");
|
||||
const HAN: (char, &str) = ('文', "chinese-system");
|
||||
// Hangul is probed last: with no Korean font installed the lookup can land on a catch-all
|
||||
// face (Unifont) that also covers Arabic or Indic text but can't shape it, so the
|
||||
// script-specific faces must be registered ahead of it. A face already seen is skipped.
|
||||
const HANGUL: (char, &str) = ('한', "korean-system");
|
||||
// Han text follows the interface language, not the operating system's locale.
|
||||
fonts::set_cjk_locale(cjk_locale(language));
|
||||
let base = fonts::resolve("Inter", "Regular").face;
|
||||
let cjk = if is_chinese(language) { [HAN, KANA] } else { [KANA, HAN] };
|
||||
let mut names = Vec::new();
|
||||
let mut seen = Vec::new();
|
||||
for &(probe, name) in cjk.iter().chain(SCRIPT_PROBES) {
|
||||
for &(probe, name) in cjk.iter().chain(SCRIPT_PROBES).chain(std::iter::once(&HANGUL)) {
|
||||
let id = fonts::fallback_for(probe, base);
|
||||
if seen.contains(&id) {
|
||||
continue;
|
||||
@@ -400,11 +441,20 @@ fn is_chinese(language: &str) -> bool {
|
||||
matches!(language, "zh-hans" | "zh-hant")
|
||||
}
|
||||
|
||||
/// egui's theme preference for an appearance mode showing a `light` (or dark) theme. Sync with
|
||||
/// System leaves it at System: a concrete preference makes egui set the native window's
|
||||
/// appearance, and on macOS a window with its own appearance no longer hears when the system's
|
||||
/// changes (#642). A fixed Light or Dark mode pins the window to match.
|
||||
pub fn theme_preference(appearance_mode: &str, light: bool) -> egui::ThemePreference {
|
||||
match appearance_mode {
|
||||
"auto" => egui::ThemePreference::System,
|
||||
_ if light => egui::ThemePreference::Light,
|
||||
_ => egui::ThemePreference::Dark,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply_visuals(ctx: &egui::Context, t: &Tokens) {
|
||||
let light = t.kind.is_light();
|
||||
// egui keeps one style per light/dark theme and by default picks it by the system appearance;
|
||||
// pin it to ours so a fixed Dark or Light mode isn't swapped for egui's defaults.
|
||||
ctx.set_theme(if light { egui::ThemePreference::Light } else { egui::ThemePreference::Dark });
|
||||
let mut v = if light { Visuals::light() } else { Visuals::dark() };
|
||||
v.panel_fill = t.panel_bg;
|
||||
v.window_fill = t.panel_bg;
|
||||
@@ -439,8 +489,10 @@ pub fn apply_visuals(ctx: &egui::Context, t: &Tokens) {
|
||||
v.widgets.active.fg_stroke = Stroke::new(1.0, t.tab_text_active);
|
||||
v.widgets.open.bg_fill = t.hover;
|
||||
v.widgets.open.weak_bg_fill = t.hover;
|
||||
ctx.set_visuals(v);
|
||||
ctx.global_style_mut(|s| {
|
||||
// egui keeps one style per light/dark theme and picks it by its theme preference (see
|
||||
// [`theme_preference`]); both get ours, so whichever it picks, egui's defaults never show.
|
||||
ctx.all_styles_mut(|s| {
|
||||
s.visuals = v.clone();
|
||||
s.spacing.item_spacing = egui::vec2(6.0, 4.0);
|
||||
s.spacing.button_padding = egui::vec2(8.0, 3.0);
|
||||
s.spacing.interact_size.y = 22.0;
|
||||
@@ -597,6 +649,24 @@ mod tests {
|
||||
install_script_fallbacks(&mut english, "en");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hangul_gets_a_face_when_one_is_installed() {
|
||||
use effectcraft_text::fonts;
|
||||
let mut fonts_def = FontDefinitions::default();
|
||||
install_script_fallbacks(&mut fonts_def, "en");
|
||||
let base = fonts::resolve("Inter", "Regular").face;
|
||||
let id = fonts::fallback_for('한', base);
|
||||
let face = fonts::face(id);
|
||||
if !face.has_char('한') {
|
||||
eprintln!("no Hangul font is installed: nothing to check here");
|
||||
return;
|
||||
}
|
||||
let Some(font) = face.font() else { return };
|
||||
let bytes = font.data().as_bytes();
|
||||
let covered = fonts_def.font_data.values().any(|d| d.font.as_ref() == bytes && d.index == face.info.index);
|
||||
assert!(covered, "a face covering Hangul must be registered with egui");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fallback_face_is_registered_at_most_once() {
|
||||
let mut fonts = FontDefinitions::default();
|
||||
|
||||
+122
-17
@@ -104,6 +104,7 @@ pub fn hot_number_at(
|
||||
return (er, out, out.is_some());
|
||||
}
|
||||
let resp = ui.interact(rect, id, Sense::click_and_drag());
|
||||
crate::pointer_wrap::track(&resp);
|
||||
let col = if resp.hovered() || resp.dragged() { t.accent_hover } else { t.hot_text };
|
||||
ui.painter().galley_with_override_text_color(rect.min + vec2(2.0, 2.0), galley, col);
|
||||
if resp.hovered() || resp.dragged() {
|
||||
@@ -154,13 +155,34 @@ pub fn hot_int_at(ui: &mut Ui, rect_min: egui::Pos2, id: egui::Id, value: i64, s
|
||||
(rect, (step != 0.0).then(|| value.saturating_add(step as i64)), done)
|
||||
}
|
||||
|
||||
/// Standard numeric editors use the same continuous native scrubbing as hot text.
|
||||
pub fn drag_value(value: egui::DragValue<'_>) -> impl egui::Widget {
|
||||
move |ui: &mut Ui| {
|
||||
let response = ui.add(value);
|
||||
crate::pointer_wrap::track(&response);
|
||||
response
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep the keyboard on an inline editor that is open until it loses the focus. The frame it
|
||||
/// opens (it has no focus yet) its whole `text` is selected, so typing replaces the value.
|
||||
/// (Only then is the focus requested: a request resets what keys the field keeps for itself,
|
||||
/// such as Tab with [`egui::TextEdit::lock_focus`].)
|
||||
/// opens its whole `text` is selected, so typing replaces the value; after that the caret is the
|
||||
/// user's (arrow keys move it), even if the field is without the focus for a frame (#488).
|
||||
/// (The focus is only requested while the field doesn't have it: a request resets what keys the
|
||||
/// field keeps for itself, such as Tab with [`egui::TextEdit::lock_focus`].)
|
||||
pub fn keep_focus(ctx: &egui::Context, field: &Response, text: &str) {
|
||||
// The editor is open in consecutive passes; a gap means it was closed and opened again.
|
||||
let shown = field.id.with("keep-focus-pass");
|
||||
let pass = ctx.cumulative_pass_nr();
|
||||
let previous = ctx.data_mut(|d| {
|
||||
let previous = d.get_temp::<u64>(shown);
|
||||
d.insert_temp(shown, pass);
|
||||
previous
|
||||
});
|
||||
let opening = previous.is_none_or(|p| p.saturating_add(1) < pass);
|
||||
if !ctx.memory(|m| m.has_focus(field.id)) {
|
||||
select_all(ctx, field.id, text);
|
||||
if opening {
|
||||
select_all(ctx, field.id, text);
|
||||
}
|
||||
field.request_focus();
|
||||
}
|
||||
}
|
||||
@@ -182,17 +204,8 @@ pub fn swatch(ui: &mut Ui, rect: Rect, c: [f32; 4], id: egui::Id, t: &Tokens) ->
|
||||
resp
|
||||
}
|
||||
|
||||
/// A colour button with egui's picker for a colour stored as sRGB components (0–1), as the
|
||||
/// project stores colours (`color_edit_button_rgb` reads linear values and shows them lighter).
|
||||
/// The value is only rewritten when the user picks a colour.
|
||||
pub fn srgb_color_button(ui: &mut Ui, c: &mut [f32; 3]) -> Response {
|
||||
let mut u = c.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);
|
||||
let r = ui.color_edit_button_srgb(&mut u);
|
||||
if r.changed() {
|
||||
*c = u.map(|v| v as f32 / 255.0);
|
||||
}
|
||||
r
|
||||
}
|
||||
// The colour picker and its helpers (every colour input uses them).
|
||||
pub use crate::color_picker::{color_popup, hex_rgb, hsv_to_rgb, rgb_to_hsv, srgb_color_button, srgb_hex, srgb32};
|
||||
|
||||
/// A twirl-down triangle; returns clicked.
|
||||
pub fn twirl(ui: &mut Ui, rect: Rect, open: bool, id: egui::Id, t: &Tokens) -> Response {
|
||||
@@ -285,6 +298,8 @@ fn field(ui: &mut Ui, rect: Rect, text: &mut String, hint: &str, t: &Tokens, sea
|
||||
.hint_text(hint)
|
||||
.frame(egui::Frame::NONE)
|
||||
.desired_width(inner.width())
|
||||
// As tall as the field, so the text and the hint sit on its middle (they sat high, #581).
|
||||
.min_size(inner.size())
|
||||
.font(Tokens::ui(12.0))
|
||||
.vertical_align(egui::Align::Center),
|
||||
)
|
||||
@@ -528,8 +543,7 @@ pub fn popup_list<R>(ui: &mut Ui, id: egui::Id, pos: egui::Pos2, anchor: Rect, r
|
||||
egui::ScrollArea::vertical().max_height(max_h).min_scrolled_height((est - 16.0).min(max_h)).show(ui, |ui| chosen = body(ui));
|
||||
});
|
||||
});
|
||||
let pass = ui.ctx().cumulative_pass_nr();
|
||||
ui.ctx().data_mut(|d| d.insert_temp(popup_list_pass_id(), pass));
|
||||
note_open_popup_list(ui.ctx());
|
||||
let outside = pressed_outside(ui.ctx(), &area.response) && !ui.input(|i| i.pointer.interact_pos()).is_some_and(|p| anchor.contains(p));
|
||||
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));
|
||||
@@ -537,6 +551,12 @@ pub fn popup_list<R>(ui: &mut Ui, id: egui::Id, pos: egui::Pos2, anchor: Rect, r
|
||||
chosen
|
||||
}
|
||||
|
||||
/// Custom popup lists also hold the app's keyboard shortcuts while open.
|
||||
pub(crate) fn note_open_popup_list(ctx: &egui::Context) {
|
||||
let pass = ctx.cumulative_pass_nr();
|
||||
ctx.data_mut(|d| d.insert_temp(popup_list_pass_id(), pass));
|
||||
}
|
||||
|
||||
/// The pass a [`popup_list`] was last drawn in.
|
||||
fn popup_list_pass_id() -> egui::Id {
|
||||
egui::Id::new("popup-list-pass")
|
||||
@@ -567,3 +587,88 @@ pub fn popup_is_open(ui: &Ui, id: egui::Id) -> bool {
|
||||
pub fn open_popup(ui: &Ui, id: egui::Id) {
|
||||
ui.data_mut(|d| d.insert_temp(id.with("open"), true));
|
||||
}
|
||||
|
||||
/// Linked values after component `d` of `c` became `v`: the others scale by the same ratio
|
||||
/// (Constrain Proportions); from 0 the others that are 0 too follow the value.
|
||||
pub(crate) fn constrained(c: &[f64], d: usize, v: f64) -> Vec<f64> {
|
||||
let Some(&old) = c.get(d) else { return c.to_vec() };
|
||||
c.iter()
|
||||
.enumerate()
|
||||
.map(|(e, &x)| {
|
||||
if e == d {
|
||||
v
|
||||
} else if old.abs() > 1e-9 {
|
||||
x * v / old
|
||||
} else if x.abs() <= 1e-9 {
|
||||
v
|
||||
} else {
|
||||
x
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// #488: an inline editor selects its whole text only as it opens. Should it be without the
|
||||
/// keyboard for a frame later (an input method, another handler), it takes the keyboard back
|
||||
/// with the caret where the user put it instead of selecting everything again, which made
|
||||
/// the arrows seem dead and Backspace erase the whole name.
|
||||
#[test]
|
||||
fn inline_editors_select_all_only_as_they_open() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut text = String::from("Comp 1");
|
||||
let mut id = egui::Id::NULL;
|
||||
let frame = |ctx: &egui::Context, text: &mut String, id: &mut egui::Id| {
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
|
||||
let r = ui.add(egui::TextEdit::singleline(text));
|
||||
keep_focus(ui.ctx(), &r, text);
|
||||
*id = r.id;
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
};
|
||||
let range = |ctx: &egui::Context, id: egui::Id| egui::TextEdit::load_state(ctx, id).and_then(|s| s.cursor.char_range());
|
||||
let ix = |n: usize| egui::text::CCursor::new(n).index;
|
||||
frame(&ctx, &mut text, &mut id);
|
||||
frame(&ctx, &mut text, &mut id);
|
||||
let all = range(&ctx, id).unwrap();
|
||||
assert_eq!((all.primary.index.min(all.secondary.index), all.primary.index.max(all.secondary.index)), (ix(0), ix(6)), "opened with all selected");
|
||||
// The caret after "Co", then a frame without the keyboard.
|
||||
let mut state = egui::TextEdit::load_state(&ctx, id).unwrap();
|
||||
state.cursor.set_char_range(Some(egui::text::CCursorRange::one(egui::text::CCursor::new(2))));
|
||||
state.store(&ctx, id);
|
||||
ctx.memory_mut(|m| m.surrender_focus(id));
|
||||
frame(&ctx, &mut text, &mut id);
|
||||
frame(&ctx, &mut text, &mut id);
|
||||
assert!(ctx.memory(|m| m.has_focus(id)), "the editor keeps the keyboard");
|
||||
let r = range(&ctx, id).unwrap();
|
||||
assert_eq!((r.primary.index, r.secondary.index), (ix(2), ix(2)), "the caret stays where it was");
|
||||
// Closed for a frame and opened again: all selected again.
|
||||
ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear();
|
||||
frame(&ctx, &mut text, &mut id);
|
||||
frame(&ctx, &mut text, &mut id);
|
||||
let r = range(&ctx, id).unwrap();
|
||||
assert_eq!((r.primary.index.min(r.secondary.index), r.primary.index.max(r.secondary.index)), (ix(0), ix(6)));
|
||||
}
|
||||
|
||||
/// #581: a field's text edit fills it, so its text and hint sit on the field's middle line
|
||||
/// (it was a row at the top of the field, its text high).
|
||||
#[test]
|
||||
fn field_text_is_vertically_centred() {
|
||||
let ctx = egui::Context::default();
|
||||
let t = Tokens::for_kind(Default::default());
|
||||
for h in [22.0, 26.0, 30.0] {
|
||||
let field = Rect::from_min_size(pos2(20.0, 40.0), vec2(220.0, h));
|
||||
let mut text = String::new();
|
||||
let mut got = None;
|
||||
let mut out = ctx.run_ui(Default::default(), |ui| {
|
||||
got = Some(search_field(ui, field, &mut text, "Filter recent files", &t).rect);
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
let r = got.expect("the field was drawn");
|
||||
assert!((r.center().y - field.center().y).abs() < 0.5 && r.height() >= h - 2.5, "{h}: {r:?} in {field:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,7 +120,13 @@ impl Snapshot {
|
||||
}
|
||||
DockNode::Stack { entries } => {
|
||||
if entries.len() > MAX_PANELS
|
||||
|| entries.iter().any(|e| !panel_ok(e.panel) || e.height.is_some_and(|v| !v.is_finite() || !(0.0..=MAX_COORD).contains(&v)))
|
||||
|| entries.iter().any(|e| {
|
||||
e.panels.is_empty()
|
||||
|| e.panels.len() > MAX_PANELS
|
||||
|| e.active >= e.panels.len()
|
||||
|| e.panels.iter().any(|p| !panel_ok(*p))
|
||||
|| e.height.is_some_and(|v| !v.is_finite() || !(0.0..=MAX_COORD).contains(&v))
|
||||
})
|
||||
{
|
||||
return Err("invalid workspace panel stack".into());
|
||||
}
|
||||
@@ -168,7 +174,20 @@ impl WorkspaceStore {
|
||||
pub(crate) fn load(config: Option<&dyn ConfigStore>, ui: &mut UiState) -> Self {
|
||||
let loaded = config.map_or(Ok(None), |c| c.read_bounded(FILE, MAX_BYTES)).map_err(|e| e.to_string()).and_then(|text| {
|
||||
text.map(|text| {
|
||||
let snapshot = serde_json::from_str::<Snapshot>(&text).map_err(|e| e.to_string())?;
|
||||
let value: serde_json::Value = serde_json::from_str(&text).map_err(|e| e.to_string())?;
|
||||
// Only an explicitly legacy-shaped record can migrate. A versioned future
|
||||
// snapshot must never deserialize as an empty defaulted legacy record.
|
||||
let snapshot = if value.get("version").is_none()
|
||||
&& value.as_object().is_some_and(|fields| fields.contains_key("workspaces") || fields.contains_key("floating"))
|
||||
{
|
||||
let legacy: crate::SavedWorkspaces = serde_json::from_value(value).map_err(|e| e.to_string())?;
|
||||
let mut snapshot = Snapshot::capture(ui);
|
||||
snapshot.saved_workspaces = legacy.workspaces;
|
||||
snapshot.saved_floating = legacy.floating;
|
||||
snapshot
|
||||
} else {
|
||||
serde_json::from_value::<Snapshot>(value).map_err(|e| e.to_string())?
|
||||
};
|
||||
snapshot.validate()?;
|
||||
Ok(snapshot)
|
||||
})
|
||||
@@ -336,7 +355,7 @@ mod tests {
|
||||
let mut snapshot = Snapshot::capture(&UiState::default());
|
||||
let panel = PanelKind::Viewer(id);
|
||||
let dock = DockNode::Tabs { panels: vec![panel], active: 0 };
|
||||
let stack = DockNode::Stack { entries: vec![crate::dock::StackEntry { panel, open: true, height: None }] };
|
||||
let stack = DockNode::Stack { entries: vec![crate::dock::StackEntry::new(panel, true, None)] };
|
||||
let floating = vec![Floating { panels: vec![panel], active: 0, rect: [0.0, 0.0, 200.0, 100.0] }];
|
||||
match location {
|
||||
0 => snapshot.focused = panel,
|
||||
|
||||
Reference in New Issue
Block a user