Skip to content

EffectCraft: An open-source motion graphics and compositing tool written by scratch in pure Rust

Merge #2367 (egui 0.37) into craft-ui-docking

aiongg26dd2ab8143d
diff --cc Cargo.lock
index 68207f1c4,1509d171f..3d73dbc03
--- a/Cargo.lock
+++ b/Cargo.lock
@@@ -980,12 -976,12 +976,12 @@@ dependencies =
[[package]]
name = "craft-docpath"
version = "0.1.0"
- source = "git+https://github.com/storytold/craft-libs?rev=5bbe9f6254de3bb9f9707ae0740ab0db8170afd5#5bbe9f6254de3bb9f9707ae0740ab0db8170afd5"
-source = "git+https://github.com/storytold/craft-libs?rev=82a24b006eefa036b43c09a67fb9a3fbd17ffe63#82a24b006eefa036b43c09a67fb9a3fbd17ffe63"
++source = "git+https://github.com/storytold/craft-libs?rev=a0916808f7d78bed8c7b90cdf937176015454a7f#a0916808f7d78bed8c7b90cdf937176015454a7f"
[[package]]
name = "craft-pdf"
version = "0.1.0"
- source = "git+https://github.com/storytold/craft-libs?rev=5bbe9f6254de3bb9f9707ae0740ab0db8170afd5#5bbe9f6254de3bb9f9707ae0740ab0db8170afd5"
-source = "git+https://github.com/storytold/craft-libs?rev=9f75d3dc19b4b514c4f3d4847ed1ec1b0e86b4ef#9f75d3dc19b4b514c4f3d4847ed1ec1b0e86b4ef"
++source = "git+https://github.com/storytold/craft-libs?rev=a0916808f7d78bed8c7b90cdf937176015454a7f#a0916808f7d78bed8c7b90cdf937176015454a7f"
dependencies = [
"hayro-syntax",
"thiserror 2.0.21",
@@@ -994,13 -990,9 +990,13 @@@
[[package]]
name = "craft-ui"
version = "0.1.0"
- source = "git+https://github.com/storytold/craft-libs?rev=5bbe9f6254de3bb9f9707ae0740ab0db8170afd5#5bbe9f6254de3bb9f9707ae0740ab0db8170afd5"
-source = "git+https://github.com/storytold/craft-libs?rev=25da1314d443171b4adeaad2cd9454b273f35c6f#25da1314d443171b4adeaad2cd9454b273f35c6f"
++source = "git+https://github.com/storytold/craft-libs?rev=a0916808f7d78bed8c7b90cdf937176015454a7f#a0916808f7d78bed8c7b90cdf937176015454a7f"
dependencies = [
"egui",
+ "log",
+ "objc2 0.6.4",
+ "objc2-app-kit 0.3.2",
+ "objc2-foundation 0.3.2",
"serde",
]
@@@ -2730,7 -2720,7 +2724,7 @@@ checksum = "9f4d0e94ddd48749f06bbe4e538
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
- source = "git+https://github.com/storytold/craft-libs?rev=5bbe9f6254de3bb9f9707ae0740ab0db8170afd5#5bbe9f6254de3bb9f9707ae0740ab0db8170afd5"
-source = "git+https://github.com/storytold/craft-libs?rev=9f75d3dc19b4b514c4f3d4847ed1ec1b0e86b4ef#9f75d3dc19b4b514c4f3d4847ed1ec1b0e86b4ef"
++source = "git+https://github.com/storytold/craft-libs?rev=a0916808f7d78bed8c7b90cdf937176015454a7f#a0916808f7d78bed8c7b90cdf937176015454a7f"
dependencies = [
"hayro-ccitt",
]
@@@ -2744,7 -2734,7 +2738,7 @@@ checksum = "c75ab947623ef4ccaa7acf0579e
[[package]]
name = "hayro-syntax"
version = "0.7.2"
- source = "git+https://github.com/storytold/craft-libs?rev=5bbe9f6254de3bb9f9707ae0740ab0db8170afd5#5bbe9f6254de3bb9f9707ae0740ab0db8170afd5"
-source = "git+https://github.com/storytold/craft-libs?rev=9f75d3dc19b4b514c4f3d4847ed1ec1b0e86b4ef#9f75d3dc19b4b514c4f3d4847ed1ec1b0e86b4ef"
++source = "git+https://github.com/storytold/craft-libs?rev=a0916808f7d78bed8c7b90cdf937176015454a7f#a0916808f7d78bed8c7b90cdf937176015454a7f"
dependencies = [
"hayro-jbig2",
"hayro-jpeg2000",
diff --cc Cargo.toml
index 6fe7c2947,2f4049685..476ba6ef7
--- a/Cargo.toml
+++ b/Cargo.toml
@@@ -11,8 -11,8 +11,8 @@@ rust-version = "1.95
repository = "https://github.com/storytold/effectcraft"
[workspace.dependencies]
- craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "5bbe9f6254de3bb9f9707ae0740ab0db8170afd5", version = "=0.1.0", default-features = false, features = ["read"] }
- craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5bbe9f6254de3bb9f9707ae0740ab0db8170afd5" }
-craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "9f75d3dc19b4b514c4f3d4847ed1ec1b0e86b4ef", version = "=0.1.0", default-features = false, features = ["read"] }
-craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "82a24b006eefa036b43c09a67fb9a3fbd17ffe63" }
++craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "a0916808f7d78bed8c7b90cdf937176015454a7f", version = "=0.1.0", default-features = false, features = ["read"] }
++craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a0916808f7d78bed8c7b90cdf937176015454a7f" }
# internal
effectcraft-time = { path = "crates/time" }
effectcraft-geom = { path = "crates/geom" }
@@@ -106,10 -106,13 +106,13 @@@ pollster = "0.4
# ui
# Shared frontend components; keep this dependency above the engine boundary.
- craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5bbe9f6254de3bb9f9707ae0740ab0db8170afd5", features = ["serde"] }
- egui = "0.36"
- eframe = { version = "0.36", default-features = false }
- egui_kittest = "0.36"
+ # Shared UI and the complete egui family select reviewed immutable commits below.
-craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "25da1314d443171b4adeaad2cd9454b273f35c6f", features = ["serde"] }
++craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a0916808f7d78bed8c7b90cdf937176015454a7f", features = ["serde"] }
+ # `default_fonts` and `monochrome_emoji_fonts` are explicit: the app's `FontDefinitions::default()`
+ # and its `✔`/`▣` chrome glyphs need both, and kittest's own dev-dependencies do not propagate.
+ egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] }
+ eframe = { version = "0.37", default-features = false }
+ egui_kittest = "0.37"
rfd = "0.17"
cpal = "0.16"
# The operating system's interface language (MIT/Apache-2.0, no dependencies on desktop).
@@@ -216,5 -219,20 +219,20 @@@ lto = "thin
codegen-units = 1
[patch.crates-io]
- hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "5bbe9f6254de3bb9f9707ae0740ab0db8170afd5", version = "=0.7.2" }
- hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "5bbe9f6254de3bb9f9707ae0740ab0db8170afd5", version = "=0.3.0" }
-hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "9f75d3dc19b4b514c4f3d4847ed1ec1b0e86b4ef", version = "=0.7.2" }
-hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "9f75d3dc19b4b514c4f3d4847ed1ec1b0e86b4ef", version = "=0.3.0" }
++hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "a0916808f7d78bed8c7b90cdf937176015454a7f", version = "=0.7.2" }
++hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "a0916808f7d78bed8c7b90cdf937176015454a7f", version = "=0.3.0" }
+ ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
+ emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
+ epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
+ epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
+ egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
+ egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
+ egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
+ egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
+ egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
+ egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
+ egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
+ eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
+ egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
+ egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
+ winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
diff --cc apps/effectcraft/src/main.rs
index ba30e22fe,a95e79a49..335a01046
--- a/apps/effectcraft/src/main.rs
+++ b/apps/effectcraft/src/main.rs
@@@ -447,10 -435,8 +448,11 @@@ impl eframe::App for Desktop
fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
#[cfg(target_os = "macos")]
self.menu.update(&mut self.app, ctx);
- self.app.logic(ctx, frame);
+ self.app.tick(ctx, frame);
+ self.app.finish_ime_logic(ctx);
+ if let Some(asked) = &self.file_dialogs {
+ sheet_dialogs::show_asked(asked, frame, ctx);
+ }
}
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
diff --cc crates/pdf/README.md
index 7d90ccf98,e4970edc9..bce90ab3b
--- a/crates/pdf/README.md
+++ b/crates/pdf/README.md
@@@ -138,7 -138,7 +138,7 @@@ ffmpeg elsewhere) to check the code tab
## Shared parser setup and bounds
The workspace pins `craft-pdf` to `craft-libs` Git revision
- `5bbe9f6254de3bb9f9707ae0740ab0db8170afd5`, with `default-features = false` and only the explicit `read`
-`9f75d3dc19b4b514c4f3d4847ed1ec1b0e86b4ef`, with `default-features = false` and only the explicit `read`
++`a0916808f7d78bed8c7b90cdf937176015454a7f`, with `default-features = false` and only the explicit `read`
feature. This excludes the backend's bundled fonts and Adobe CMaps and preserves EffectCraft's
font and asset policies. The shared parser does not change the supported drawing operators,
image codecs, continuously rasterized SVG tree, editable shapes, or EPS interpreter.
diff --cc crates/ui-egui/src/control.rs
index 83715fab4,a481d96ac..d89f3b988
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@@ -169,330 -170,360 +170,360 @@@ fn point(app: &EffectcraftApp, p: &Valu
Ok(egui::pos2(x as f32, y as f32))
}
- pub fn handle(app: &mut EffectcraftApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome {
+ pub fn handle(app: &mut EffectcraftApp, ctx: &egui::Context, req: &ControlRequest, now: f64) -> Outcome {
let p = &req.params;
- let s = |k: &str| p.get(k).and_then(Value::as_str);
match req.method.as_str() {
- "engine.execute" | "ui.menu.invoke" => {
- let Some(id) = s("command").or(s("id")) else { return err("missing `command`") };
- let params = p.get("params").cloned().filter(|v| !v.is_null()).unwrap_or(json!({}));
- // `engine.execute` runs engine commands exactly as headless (never opens a dialog, e.g.
- // `comp.new {}` creates a default comp); UI-only ids (`tool.*`, `view.*`, `window.*`,
- // `playback.*` …) and `ui.menu.invoke` go through the menu dispatcher like a click.
- let r = if req.method == "engine.execute" && effectcraft_engine::find_command(id).is_some() {
- execute_engine(app, id, params)
- } else {
- crate::menus::invoke(app, ctx, id, params).map(ok)
- };
- match r {
- Ok(o) => o,
- Err(e) => {
- app.ui.status = e.clone();
- err(e)
- }
- }
- }
- "engine.commands" => match app.session.execute("command.list", json!({"filter": p.get("filter"), "enabledOnly": p.get("enabledOnly")})) {
- Ok(v) => ok(v),
- Err(e) => err(e),
- },
+ "engine.execute" | "ui.menu.invoke" => execute_command(app, ctx, &req.method, p),
+ "engine.commands" => engine_commands(app, p),
"ui.menu.list" => ok(serde_json::to_value(crate::menus::menu_items(app)).unwrap_or_default()),
"ui.inspect" => ok(inspect(app, ctx)),
- "ui.elements" => {
- let prefix = s("prefix").unwrap_or("");
- ok(serde_json::to_value(app.auto.query(prefix)).unwrap_or_default())
- }
- "ui.set" => {
- if let Some(t) = s("tool") {
- match Tool::from_name(t) {
- Some(t) => app.ui.tool = t,
- None => return err(format!("unknown tool `{t}`")),
- }
- }
- if let Some(w) = s("workspace") {
- match crate::dock::WORKSPACES.iter().find(|x| x.eq_ignore_ascii_case(w)) {
- Some(w) => app.set_workspace(w),
- None => return err(format!("unknown workspace `{w}`")),
- }
- }
- if let Some(th) = s("theme") {
- match crate::theme::ThemeKind::from_name(th) {
- Some(k) => app.set_theme(ctx, k),
- None => return err("unknown theme (dark, darker, light)"),
- }
- }
- if let Some(f) = s("focused").and_then(PanelKind::from_name) {
- app.ui.focused = f;
- }
- if let Some(v) = p.get("viewer") {
- if let Some(z) = v.get("zoom") {
- app.ui.viewer.zoom = z.as_f64().map(|z| z as f32);
- }
- // The active comp's Resolution (`view.res.*`), saved with the project.
- if let Some(r) = v.get("res").and_then(Value::as_str) {
- let Some(res) = Resolution::ALL.into_iter().find(|x| x.label().eq_ignore_ascii_case(r)) else {
- return err(format!("unknown resolution `{r}` (auto, full, half, third, quarter)"));
- };
- if let Some(cid) = app.session.active_comp_id()
- && let Err(e) = app.session.set_resolution(cid, res)
- {
- return err(e);
- }
- }
- if let Some(Value::Array(a)) = v.get("pan") {
- app.ui.viewer.pan = [a.first().and_then(Value::as_f64).unwrap_or(0.0) as f32, a.get(1).and_then(Value::as_f64).unwrap_or(0.0) as f32];
- }
- for (k, slot) in [
- ("grid", &mut app.ui.viewer.grid),
- ("rulers", &mut app.ui.viewer.rulers),
- ("safeMargins", &mut app.ui.viewer.safe_margins),
- ("transparencyGrid", &mut app.ui.viewer.transparency_grid),
- ] {
- if let Some(b) = v.get(k).and_then(Value::as_bool) {
- *slot = b;
- }
- }
- }
- if let Some(tl) = p.get("timeline") {
- if let Some(v) = tl.get("pps") {
- app.ui.timeline.pps = v.as_f64();
- }
- if let Some(v) = tl.get("start").and_then(Value::as_f64) {
- app.ui.timeline.start = v;
- }
- if let Some(v) = tl.get("graphEditor").and_then(Value::as_bool) {
- app.ui.timeline.graph_editor = v;
- }
- if let Some(v) = tl.get("showModes").and_then(Value::as_bool) {
- app.ui.timeline.show_modes = v;
- }
- if let Some(Value::Array(a)) = tl.get("openLayers") {
- app.ui.timeline.open_layers = a.iter().filter_map(Value::as_u64).collect();
- }
- if let Some(Value::Array(a)) = tl.get("openGroups") {
- app.ui.timeline.open_groups = a.iter().filter_map(Value::as_u64).collect();
- }
- }
- if let Some(b) = p.get("menuBar").and_then(Value::as_bool) {
- app.ui.show_menu_bar = b;
- }
- // Project panel optional columns, e.g. ["type", "duration", "path", "comment"].
- if let Some(Value::Array(a)) = p.get("projectColumns") {
- let mut cols = vec![];
- for k in a.iter().filter_map(Value::as_str) {
- crate::panels::project::set_column(&mut cols, k, true);
- }
- app.ui.project_columns = cols;
- }
- // Wiggler / Smoother / Motion Sketch settings (fields of `AnimToolsState`).
- if let Some(Value::Object(m)) = p.get("animTools") {
- let mut cur = serde_json::to_value(&app.ui.anim_tools).unwrap_or_default();
- for (k, v) in m {
- cur[k] = v.clone();
- }
- match serde_json::from_value(cur) {
- Ok(v) => app.ui.anim_tools = v,
- Err(e) => return err(format!("animTools: {e}")),
- }
- }
- if let Some(b) = p.get("home").and_then(Value::as_bool) {
- app.ui.start_screen = b;
- }
- // Home screen tab: "home", "templates" or "learn".
- if let Some(tab) = p.get("homeTab").and_then(Value::as_str) {
- app.ui.home_learn = tab == "learn";
- app.ui.home_templates = tab == "templates";
- }
- ok(Value::Null)
- }
- "ui.panel.show" | "ui.panel.close" => {
- let Some(panel) = s("panel").and_then(PanelKind::from_name) else { return err("unknown `panel`") };
- if req.method == "ui.panel.show" {
- app.show_panel(panel);
- } else {
- app.close_panel(panel);
- }
- ok(Value::Null)
- }
- "ui.click" | "ui.move" => {
- let pos = match point(app, p) {
- Ok(p) => p,
- Err(e) if e.starts_with(RETRY) => return Outcome::Retry(e.trim_start_matches(RETRY).to_string()),
- Err(e) => return err(e),
- };
- let m = modifiers(p);
- // Validate the complete gesture before mutating the queue; the loopback control
- // channel is externally reachable and must not amplify tiny requests into huge work.
- const MAX_PENDING_EVENTS: usize = 4096;
- const MAX_CLICK_COUNT: u64 = 512;
- let pending = app.synthetic.len();
- let gesture_events = if req.method == "ui.click" {
- let count = p.get("count").and_then(Value::as_u64).unwrap_or(1);
- if count == 0 || count > MAX_CLICK_COUNT {
- return err(format!("`count` must be between 1 and {MAX_CLICK_COUNT}"));
- }
- let Some(events) = usize::try_from(count).ok().and_then(|n| n.checked_mul(2)).and_then(|n| n.checked_add(3)) else {
- return err("click event count overflow");
- };
- events
- } else {
- 3
- };
- if pending.checked_add(gesture_events).is_none_or(|n| n > MAX_PENDING_EVENTS) {
- return err("synthetic input queue is full");
- }
- // egui keeps the modifiers from `ModifiersChanged` (not the ones on a pointer event)
- // and the synthetic events arrive one per frame: hold them for the whole gesture.
- app.synthetic.push(egui::Event::ModifiersChanged(m));
- app.synthetic.push(egui::Event::PointerMoved(pos));
- if req.method == "ui.click" {
- let button = match s("button") {
- Some("right") => egui::PointerButton::Secondary,
- Some("middle") => egui::PointerButton::Middle,
- _ => egui::PointerButton::Primary,
- };
- let count = p.get("count").and_then(Value::as_u64).unwrap_or(1);
- for _ in 0..count {
- app.synthetic.push(egui::Event::PointerButton { pos, button, pressed: true, modifiers: m });
- app.synthetic.push(egui::Event::PointerButton { pos, button, pressed: false, modifiers: m });
- }
- }
- app.synthetic.push(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
- Outcome::AfterInput
- }
- "ui.drag" => {
- let (Some(from), Some(to)) = (p.get("from"), p.get("to")) else { return err("need `from` and `to`") };
- let (a, b) = match (point(app, from), point(app, to)) {
- (Ok(a), Ok(b)) => (a, b),
- (Err(e), _) | (_, Err(e)) if e.starts_with(RETRY) => return Outcome::Retry(e.trim_start_matches(RETRY).to_string()),
- (Err(e), _) | (_, Err(e)) => return err(e),
- };
- let steps = p.get("steps").and_then(Value::as_u64).unwrap_or(12).max(2);
- const MAX_PENDING_EVENTS: usize = 4096;
- const MAX_DRAG_STEPS: u64 = 2048;
- if steps > MAX_DRAG_STEPS {
- return err(format!("`steps` must be at most {MAX_DRAG_STEPS}"));
- }
- let Some(gesture_events) = usize::try_from(steps).ok().and_then(|n| n.checked_add(5)) else { return err("drag event count overflow") };
- if app.synthetic.len().checked_add(gesture_events).is_none_or(|n| n > MAX_PENDING_EVENTS) {
- return err("synthetic input queue is full");
- }
- let m = modifiers(p);
- app.synthetic.push(egui::Event::ModifiersChanged(m));
- app.synthetic.push(egui::Event::PointerMoved(a));
- app.synthetic.push(egui::Event::PointerButton { pos: a, button: egui::PointerButton::Primary, pressed: true, modifiers: m });
- for i in 1..=steps {
- let f = i as f32 / steps as f32;
- app.synthetic.push(egui::Event::PointerMoved(a + (b - a) * f));
- }
- app.synthetic.push(egui::Event::PointerButton { pos: b, button: egui::PointerButton::Primary, pressed: false, modifiers: m });
- app.synthetic.push(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
- Outcome::AfterInput
- }
- "ui.scroll" => {
- let pos = match point(app, p) {
- Ok(p) => p,
- Err(e) => return err(e),
- };
- let dx = p.get("dx").and_then(Value::as_f64).unwrap_or(0.0) as f32;
- let dy = p.get("dy").and_then(Value::as_f64).unwrap_or(0.0) as f32;
- app.synthetic.push(egui::Event::PointerMoved(pos));
- app.synthetic.push(egui::Event::MouseWheel {
- unit: egui::MouseWheelUnit::Point,
- delta: egui::vec2(dx, dy),
- modifiers: modifiers(p),
- phase: egui::TouchPhase::Move,
- });
- app.synthetic.push(egui::Event::PointerButton {
- pos: egui::pos2(-100.0, -100.0),
- button: egui::PointerButton::Extra1,
- pressed: false,
- modifiers: Default::default(),
- });
- Outcome::AfterInput
- }
- "ui.key" => {
- let Some(name) = s("key") else { return err("missing `key`") };
- let Some((mut m, key)) = crate::menus::parse_shortcut(name) else { return err(format!("unknown key `{name}`")) };
- let extra = modifiers(p);
- m |= extra;
- let physical_key = name.starts_with("Physical+").then_some(key);
- app.synthetic.push(egui::Event::Key { key, physical_key, pressed: true, repeat: false, modifiers: m });
- app.synthetic.push(egui::Event::Key { key, physical_key, pressed: false, repeat: false, modifiers: m });
- Outcome::AfterInput
- }
- "ui.type" => {
- let Some(text) = s("text") else { return err("missing `text`") };
- app.synthetic.push(egui::Event::Text(text.to_string()));
- app.synthetic.push(egui::Event::Key { key: egui::Key::F35, physical_key: None, pressed: false, repeat: false, modifiers: Default::default() });
- Outcome::AfterInput
- }
- "ui.viewer.locate" => {
- let (Some(x), Some(y)) = (p.get("x").and_then(Value::as_f64), p.get("y").and_then(Value::as_f64)) else {
- return err("need `x`, `y` (comp pixels)");
- };
- match crate::panels::viewer::comp_to_screen(ctx, [x as f32, y as f32]) {
- Some(pt) => ok(json!({"x": pt.x, "y": pt.y})),
- None => Outcome::Retry("the composition viewer is not visible".into()),
- }
+ "ui.elements" => elements(app, p),
+ "ui.set" => set_ui(app, ctx, p),
+ "ui.panel.show" | "ui.panel.close" => panel(app, &req.method, p),
+ "ui.click" | "ui.move" => click_or_move(app, &req.method, p),
+ "ui.drag" => drag(app, p),
+ "ui.scroll" => scroll(app, p),
+ "ui.key" => key(app, p),
+ "ui.type" => type_text(app, p),
+ "ui.viewer.locate" => viewer_locate(ctx, p),
+ "ui.viewer.hit" => viewer_hit(app, ctx, p),
+ "ui.timeline.locate" => timeline_locate(app, p),
+ "ui.playback" => playback(app, p, now),
+ "ui.screenshot" => screenshot(app, ctx, p),
+ "render.frame" => render_frame(app, p),
+ "ui.resize" => resize(ctx, p),
+ "ui.focus" => focus(ctx),
+ "app.quit" => quit(app, ctx, p),
+ m => err(format!("unknown method `{m}`")),
+ }
+ }
+
+ fn execute_command(app: &mut EffectcraftApp, ctx: &egui::Context, method: &str, p: &Value) -> Outcome {
+ let s = |k: &str| p.get(k).and_then(Value::as_str);
+ let Some(id) = s("command").or(s("id")) else { return err("missing `command`") };
+ let params = p.get("params").cloned().filter(|v| !v.is_null()).unwrap_or(json!({}));
+ // `engine.execute` runs engine commands exactly as headless (never opens a dialog, e.g.
+ // `comp.new {}` creates a default comp); UI-only ids (`tool.*`, `view.*`, `window.*`,
+ // `playback.*` …) and `ui.menu.invoke` go through the menu dispatcher like a click.
+ let r = if method == "engine.execute" && effectcraft_engine::find_command(id).is_some() {
+ execute_engine(app, id, params)
+ } else {
+ crate::menus::invoke(app, ctx, id, params).map(ok)
+ };
+ match r {
+ Ok(o) => o,
+ Err(e) => {
+ app.ui.status = e.clone();
+ err(e)
}
- "ui.viewer.hit" => {
- let pos = match point(app, p) {
- Ok(p) => p,
- Err(e) => return err(e),
- };
- match crate::panels::viewer::screen_to_comp(ctx, pos) {
- Some(c) => ok(json!({"x": c[0], "y": c[1]})),
- None => err("the composition viewer is not visible"),
- }
+ }
+ }
+
+ fn engine_commands(app: &mut EffectcraftApp, p: &Value) -> Outcome {
+ match app.session.execute("command.list", json!({"filter": p.get("filter"), "enabledOnly": p.get("enabledOnly")})) {
+ Ok(v) => ok(v),
+ Err(e) => err(e),
+ }
+ }
+
+ fn elements(app: &EffectcraftApp, p: &Value) -> Outcome {
+ let prefix = p.get("prefix").and_then(Value::as_str).unwrap_or("");
+ ok(serde_json::to_value(app.auto.query(prefix)).unwrap_or_default())
+ }
+
+ /// Explicit request: activate the app and take keyboard focus.
+ fn focus(ctx: &egui::Context) -> Outcome {
+ ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
+ ok(Value::Null)
+ }
+
+ fn set_ui(app: &mut EffectcraftApp, ctx: &egui::Context, p: &Value) -> Outcome {
+ let s = |k: &str| p.get(k).and_then(Value::as_str);
+ if let Some(t) = s("tool") {
+ match Tool::from_name(t) {
+ Some(t) => app.ui.tool = t,
+ None => return err(format!("unknown tool `{t}`")),
}
- "ui.timeline.locate" => {
- let Some(l) = p.get("layer").and_then(Value::as_u64) else { return err("need `layer` (id)") };
- match crate::panels::timeline::locate(app, l, p.get("time").and_then(Value::as_f64)) {
- Some((x, y)) => ok(json!({"x": x, "y": y})),
- None => Outcome::Retry("layer not visible in the timeline".into()),
- }
+ }
+ if let Some(w) = s("workspace") {
+ match crate::dock::WORKSPACES.iter().find(|x| x.eq_ignore_ascii_case(w)) {
+ Some(w) => app.set_workspace(w),
+ None => return err(format!("unknown workspace `{w}`")),
}
- "ui.playback" => {
- let now = ctx.input(|i| i.time);
- match s("action").unwrap_or("toggle") {
- "play" => app.play(now),
- "stop" => app.stop(),
- "status" => {}
- _ => app.toggle_play(now),
- }
- ok(
- json!({"playing": app.playback.playing, "time": app.session.time().seconds(), "audio": app.audio.is_some(), "levelsDb": app.meter.level_db, "peaksDb": app.meter.peak_db}),
- )
+ }
+ if let Some(th) = s("theme") {
+ match crate::theme::ThemeKind::from_name(th) {
+ Some(k) => app.set_theme(ctx, k),
+ None => return err("unknown theme (dark, darker, light)"),
}
- "ui.screenshot" => {
- let crop = s("panel").and_then(PanelKind::from_name).and_then(|pk| app.auto.find(&format!("panel.{}", pk.id())).map(|e| e.rect));
- let crop = crop.or_else(|| s("id").and_then(|id| app.auto.find(id).map(|e| e.rect)));
- // Bring the window on screen so a frame is presented, without taking keyboard focus.
- app.raise_for_control(ctx);
- Outcome::Screenshot { path: s("path").map(str::to_string), crop }
+ }
+ if let Some(f) = s("focused").and_then(PanelKind::from_name) {
+ app.ui.focused = f;
+ }
+ if let Some(v) = p.get("viewer")
+ && let Err(e) = apply_viewer(app, v)
+ {
+ return err(e);
+ }
+ set_ui_layout(app, p)
+ }
+
+ /// The remaining `ui.set` fields, applied in the same order after the viewer settings.
+ fn set_ui_layout(app: &mut EffectcraftApp, p: &Value) -> Outcome {
+ if let Some(tl) = p.get("timeline") {
+ apply_timeline(app, tl);
+ }
+ if let Some(b) = p.get("menuBar").and_then(Value::as_bool) {
+ app.ui.show_menu_bar = b;
+ }
+ // Project panel optional columns, e.g. ["type", "duration", "path", "comment"].
+ if let Some(Value::Array(a)) = p.get("projectColumns") {
+ apply_project_columns(app, a);
+ }
+ // Wiggler / Smoother / Motion Sketch settings (fields of `AnimToolsState`).
+ if let Some(Value::Object(m)) = p.get("animTools")
+ && let Err(e) = apply_anim_tools(app, m)
+ {
+ return err(e);
+ }
+ if let Some(b) = p.get("home").and_then(Value::as_bool) {
+ app.ui.start_screen = b;
+ }
+ // Home screen tab: "home", "templates" or "learn".
+ if let Some(tab) = p.get("homeTab").and_then(Value::as_str) {
+ app.ui.home_learn = tab == "learn";
+ app.ui.home_templates = tab == "templates";
+ }
+ ok(Value::Null)
+ }
+
+ fn apply_viewer(app: &mut EffectcraftApp, v: &Value) -> Result<(), String> {
+ if let Some(z) = v.get("zoom") {
+ app.ui.viewer.zoom = z.as_f64().map(|z| z as f32);
+ }
+ // The active comp's Resolution (`view.res.*`), saved with the project.
+ if let Some(r) = v.get("res").and_then(Value::as_str) {
+ let Some(res) = Resolution::ALL.into_iter().find(|x| x.label().eq_ignore_ascii_case(r)) else {
+ return Err(format!("unknown resolution `{r}` (auto, full, half, third, quarter)"));
+ };
+ if let Some(cid) = app.session.active_comp_id()
+ && let Err(e) = app.session.set_resolution(cid, res)
+ {
+ return Err(e.to_string());
}
- "render.frame" => render_frame(app, p),
- "ui.resize" => {
- let w = p.get("width").and_then(Value::as_f64).unwrap_or(1600.0) as f32;
- let h = p.get("height").and_then(Value::as_f64).unwrap_or(1000.0) as f32;
- ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(egui::vec2(w, h)));
- ok(Value::Null)
+ }
+ if let Some(Value::Array(a)) = v.get("pan") {
+ app.ui.viewer.pan = [a.first().and_then(Value::as_f64).unwrap_or(0.0) as f32, a.get(1).and_then(Value::as_f64).unwrap_or(0.0) as f32];
+ }
+ for (k, slot) in [
+ ("grid", &mut app.ui.viewer.grid),
+ ("rulers", &mut app.ui.viewer.rulers),
+ ("safeMargins", &mut app.ui.viewer.safe_margins),
+ ("transparencyGrid", &mut app.ui.viewer.transparency_grid),
+ ] {
+ if let Some(b) = v.get(k).and_then(Value::as_bool) {
+ *slot = b;
}
- "ui.focus" => {
- // Explicit request: activate the app and take keyboard focus.
- ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
- ok(Value::Null)
+ }
+ Ok(())
+ }
+
+ fn apply_timeline(app: &mut EffectcraftApp, tl: &Value) {
+ if let Some(v) = tl.get("pps") {
+ app.ui.timeline.pps = v.as_f64();
+ }
+ if let Some(v) = tl.get("start").and_then(Value::as_f64) {
+ app.ui.timeline.start = v;
+ }
+ if let Some(v) = tl.get("graphEditor").and_then(Value::as_bool) {
+ app.ui.timeline.graph_editor = v;
+ }
+ if let Some(v) = tl.get("showModes").and_then(Value::as_bool) {
+ app.ui.timeline.show_modes = v;
+ }
+ if let Some(Value::Array(a)) = tl.get("openLayers") {
+ app.ui.timeline.open_layers = a.iter().filter_map(Value::as_u64).collect();
+ }
+ if let Some(Value::Array(a)) = tl.get("openGroups") {
+ app.ui.timeline.open_groups = a.iter().filter_map(Value::as_u64).collect();
+ }
+ }
+
+ fn apply_project_columns(app: &mut EffectcraftApp, a: &[Value]) {
+ let mut cols = vec![];
+ for k in a.iter().filter_map(Value::as_str) {
+ crate::panels::project::set_column(&mut cols, k, true);
+ }
+ app.ui.project_columns = cols;
+ }
+
+ fn apply_anim_tools(app: &mut EffectcraftApp, m: &serde_json::Map<String, Value>) -> Result<(), String> {
+ let mut cur = serde_json::to_value(&app.ui.anim_tools).unwrap_or_default();
+ for (k, v) in m {
+ cur[k] = v.clone();
+ }
+ match serde_json::from_value(cur) {
+ Ok(v) => {
+ app.ui.anim_tools = v;
+ Ok(())
}
- "app.quit" => {
- // A modified project asks to save first unless `force: true`.
- if p.get("force").and_then(Value::as_bool).unwrap_or(false) {
- app.dialog_state.unsaved.quitting = true;
- }
- ctx.send_viewport_cmd(egui::ViewportCommand::Close);
- ok(Value::Null)
+ Err(e) => Err(format!("animTools: {e}")),
+ }
+ }
+
+ fn panel(app: &mut EffectcraftApp, method: &str, p: &Value) -> Outcome {
+ let s = |k: &str| p.get(k).and_then(Value::as_str);
+ let Some(panel) = s("panel").and_then(PanelKind::from_name) else { return err("unknown `panel`") };
+ if method == "ui.panel.show" {
+ app.show_panel(panel);
+ } else {
- app.ui.dock.close(panel);
++ app.close_panel(panel);
+ }
+ ok(Value::Null)
+ }
+
+ fn click_gesture_events(method: &str, p: &Value) -> Result<usize, String> {
+ if method != "ui.click" {
+ return Ok(3);
+ }
+ const MAX_CLICK_COUNT: u64 = 512;
+ let count = p.get("count").and_then(Value::as_u64).unwrap_or(1);
+ if count == 0 || count > MAX_CLICK_COUNT {
+ return Err(format!("`count` must be between 1 and {MAX_CLICK_COUNT}"));
+ }
+ usize::try_from(count).ok().and_then(|n| n.checked_mul(2)).and_then(|n| n.checked_add(3)).ok_or_else(|| "click event count overflow".to_string())
+ }
+
+ fn click_or_move(app: &mut EffectcraftApp, method: &str, p: &Value) -> Outcome {
+ let s = |k: &str| p.get(k).and_then(Value::as_str);
+ let pos = match point(app, p) {
+ Ok(p) => p,
+ Err(e) if e.starts_with(RETRY) => return Outcome::Retry(e.trim_start_matches(RETRY).to_string()),
+ Err(e) => return err(e),
+ };
+ let m = modifiers(p);
+ // Validate the complete gesture before mutating the queue; the loopback control
+ // channel is externally reachable and must not amplify tiny requests into huge work.
+ const MAX_PENDING_EVENTS: usize = 4096;
+ let pending = app.synthetic.len();
+ let gesture_events = match click_gesture_events(method, p) {
+ Ok(events) => events,
+ Err(e) => return err(e),
+ };
+ if pending.checked_add(gesture_events).is_none_or(|n| n > MAX_PENDING_EVENTS) {
+ return err("synthetic input queue is full");
+ }
+ // egui keeps the modifiers from `ModifiersChanged` (not the ones on a pointer event)
+ // and the synthetic events arrive one per frame: hold them for the whole gesture.
+ app.synthetic.push(egui::Event::ModifiersChanged(m));
+ app.synthetic.push(egui::Event::PointerMoved(pos));
+ if method == "ui.click" {
+ let button = match s("button") {
+ Some("right") => egui::PointerButton::Secondary,
+ Some("middle") => egui::PointerButton::Middle,
+ _ => egui::PointerButton::Primary,
+ };
+ let count = p.get("count").and_then(Value::as_u64).unwrap_or(1);
+ for _ in 0..count {
+ app.synthetic.push(egui::Event::PointerButton { pos, button, pressed: true, modifiers: m });
+ app.synthetic.push(egui::Event::PointerButton { pos, button, pressed: false, modifiers: m });
}
- m => err(format!("unknown method `{m}`")),
+ }
+ app.synthetic.push(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
+ Outcome::AfterInput
+ }
+
+ fn drag(app: &mut EffectcraftApp, p: &Value) -> Outcome {
+ let (Some(from), Some(to)) = (p.get("from"), p.get("to")) else { return err("need `from` and `to`") };
+ let (a, b) = match (point(app, from), point(app, to)) {
+ (Ok(a), Ok(b)) => (a, b),
+ (Err(e), _) | (_, Err(e)) if e.starts_with(RETRY) => return Outcome::Retry(e.trim_start_matches(RETRY).to_string()),
+ (Err(e), _) | (_, Err(e)) => return err(e),
+ };
+ let steps = p.get("steps").and_then(Value::as_u64).unwrap_or(12).max(2);
+ const MAX_PENDING_EVENTS: usize = 4096;
+ const MAX_DRAG_STEPS: u64 = 2048;
+ if steps > MAX_DRAG_STEPS {
+ return err(format!("`steps` must be at most {MAX_DRAG_STEPS}"));
+ }
+ let Some(gesture_events) = usize::try_from(steps).ok().and_then(|n| n.checked_add(5)) else { return err("drag event count overflow") };
+ if app.synthetic.len().checked_add(gesture_events).is_none_or(|n| n > MAX_PENDING_EVENTS) {
+ return err("synthetic input queue is full");
+ }
+ let m = modifiers(p);
+ app.synthetic.push(egui::Event::ModifiersChanged(m));
+ app.synthetic.push(egui::Event::PointerMoved(a));
+ app.synthetic.push(egui::Event::PointerButton { pos: a, button: egui::PointerButton::Primary, pressed: true, modifiers: m });
+ for i in 1..=steps {
+ let f = i as f32 / steps as f32;
+ app.synthetic.push(egui::Event::PointerMoved(a + (b - a) * f));
+ }
+ app.synthetic.push(egui::Event::PointerButton { pos: b, button: egui::PointerButton::Primary, pressed: false, modifiers: m });
+ app.synthetic.push(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
+ Outcome::AfterInput
+ }
+
+ fn scroll(app: &mut EffectcraftApp, p: &Value) -> Outcome {
+ let pos = match point(app, p) {
+ Ok(p) => p,
+ Err(e) => return err(e),
+ };
+ let dx = p.get("dx").and_then(Value::as_f64).unwrap_or(0.0) as f32;
+ let dy = p.get("dy").and_then(Value::as_f64).unwrap_or(0.0) as f32;
+ app.synthetic.push(egui::Event::PointerMoved(pos));
+ app.synthetic.push(egui::Event::MouseWheel {
+ unit: egui::MouseWheelUnit::Point,
+ delta: egui::vec2(dx, dy),
+ modifiers: modifiers(p),
+ phase: egui::TouchPhase::Move,
+ source: egui::MouseWheelSource::Wheel,
+ });
+ app.synthetic.push(egui::Event::PointerButton {
+ pos: egui::pos2(-100.0, -100.0),
+ button: egui::PointerButton::Extra1,
+ pressed: false,
+ modifiers: Default::default(),
+ });
+ Outcome::AfterInput
+ }
+
+ fn key(app: &mut EffectcraftApp, p: &Value) -> Outcome {
+ let s = |k: &str| p.get(k).and_then(Value::as_str);
+ let Some(name) = s("key") else { return err("missing `key`") };
+ let Some((mut m, key)) = crate::menus::parse_shortcut(name) else { return err(format!("unknown key `{name}`")) };
+ let extra = modifiers(p);
+ m |= extra;
+ let physical_key = name.starts_with("Physical+").then_some(key);
+ app.synthetic.push(egui::Event::Key { key, physical_key, pressed: true, repeat: false, modifiers: m });
+ app.synthetic.push(egui::Event::Key { key, physical_key, pressed: false, repeat: false, modifiers: m });
+ Outcome::AfterInput
+ }
+
+ fn type_text(app: &mut EffectcraftApp, p: &Value) -> Outcome {
+ let Some(text) = p.get("text").and_then(Value::as_str) else { return err("missing `text`") };
+ app.synthetic.push(egui::Event::Text(text.to_string()));
+ app.synthetic.push(egui::Event::Key { key: egui::Key::F35, physical_key: None, pressed: false, repeat: false, modifiers: Default::default() });
+ Outcome::AfterInput
+ }
+
+ fn viewer_locate(ctx: &egui::Context, p: &Value) -> Outcome {
+ let (Some(x), Some(y)) = (p.get("x").and_then(Value::as_f64), p.get("y").and_then(Value::as_f64)) else {
+ return err("need `x`, `y` (comp pixels)");
+ };
+ match crate::panels::viewer::comp_to_screen(ctx, [x as f32, y as f32]) {
+ Some(pt) => ok(json!({"x": pt.x, "y": pt.y})),
+ None => Outcome::Retry("the composition viewer is not visible".into()),
+ }
+ }
+
+ fn viewer_hit(app: &mut EffectcraftApp, ctx: &egui::Context, p: &Value) -> Outcome {
+ let pos = match point(app, p) {
+ Ok(p) => p,
+ Err(e) => return err(e),
+ };
+ match crate::panels::viewer::screen_to_comp(ctx, pos) {
+ Some(c) => ok(json!({"x": c[0], "y": c[1]})),
+ None => err("the composition viewer is not visible"),
}
}
diff --cc crates/ui-egui/src/dock.rs
index a19ef5ac4,3dbc83714..40ce78b9b
--- a/crates/ui-egui/src/dock.rs
+++ b/crates/ui-egui/src/dock.rs
@@@ -518,97 -921,440 +518,97 @@@ pub struct DocTab
pub active: bool,
}
-/// What a group's tabs show: labels, the comp swatch / close / lock decorations and the panels
-/// that show one tab per document.
-pub struct TabInfo<'a> {
- pub title: &'a dyn Fn(PanelKind) -> String,
- pub decos: &'a [(PanelKind, TabDeco)],
- pub docs: &'a [(PanelKind, Vec<DocTab>)],
-}
-
-/// What drawing a group's chrome produced: actions and where each panel's tabs are (a panel with
-/// document tabs spans all of them; tabs hidden behind the overflow chevron are left out).
-#[derive(Default)]
-pub struct Chrome {
- pub actions: Vec<DockAction>,
- pub tabs: Vec<(PanelKind, Rect)>,
+/// What the Timeline's comp tabs did this frame.
+#[derive(Debug, Clone, PartialEq)]
+pub enum DocAction {
+ /// Show comp `id`.
+ Activate(u64),
+ /// Close comp `id`'s Timeline (its ×, or a middle click).
+ Close(u64),
}
-/// After Effects-style extras on a tab that shows a composition (Composition, Timeline): a close
-/// button (×), the item's label colour as a small square and the viewer lock.
-#[derive(Debug, Clone, Copy, PartialEq)]
-pub struct TabDeco {
- pub swatch: egui::Color32,
- pub locked: bool,
- /// Close button and lock (Composition, Timeline); Effect Controls shows just the swatch.
- pub viewer: bool,
-}
+const DOC_PAD: f32 = 8.0;
+const DOC_SWATCH: f32 = 14.0;
+const DOC_CLOSE: f32 = 16.0;
-/// Lay out the tree into group rects (with `gap` gutters) and handle gutter dragging.
-pub fn layout(ui: &mut egui::Ui, node: &mut DockNode, rect: Rect, t: &Tokens, path: &str, out: &mut Vec<Group>, reg: &mut crate::automation::Registry) {
- let mut actions = Vec::new();
- layout_with_actions(ui, node, rect, t, path, out, reg, &mut actions);
- for action in actions {
- crate::dock_shared::apply_tree(node, action);
- }
+fn doc_width(ui: &egui::Ui, doc: &DocTab) -> f32 {
+ let label = ui.painter().layout_no_wrap(doc.title.clone(), Tokens::ui(12.0), egui::Color32::WHITE).size().x;
+ DOC_PAD + DOC_SWATCH + label + if doc.active { DOC_CLOSE } else { 0.0 } + DOC_PAD
}
-/// Lay out chrome while returning mutations for the application's UI command route.
-pub fn layout_with_actions(
- ui: &mut egui::Ui,
- node: &mut DockNode,
- rect: Rect,
- t: &Tokens,
- path: &str,
- out: &mut Vec<Group>,
- reg: &mut crate::automation::Registry,
- actions: &mut Vec<craft_ui::docking::Action<PanelKind>>,
-) {
- layout_inner(ui, node, rect, t, path, &[], out, reg, actions);
+/// The width the comp tabs ask for in the Timeline's tab strip.
+pub fn doc_tabs_width(ui: &egui::Ui, docs: &[DocTab]) -> f32 {
+ docs.iter().map(|d| doc_width(ui, d)).sum()
}
-fn layout_inner(
- ui: &mut egui::Ui,
- node: &mut DockNode,
- rect: Rect,
- t: &Tokens,
- path: &str,
- tree_path: &[bool],
- out: &mut Vec<Group>,
- reg: &mut crate::automation::Registry,
- actions: &mut Vec<craft_ui::docking::Action<PanelKind>>,
-) {
- match node {
- DockNode::Tabs { panels, active } => {
- let tab_h = if panels.len() == 1 && panels[0].compact() { 8.0 } else { t.tab_h };
- let content = Rect::from_min_max(pos2(rect.min.x, rect.min.y + tab_h), rect.max);
- out.push(Group { path: path.to_string(), rect, content, panels: panels.clone(), active: *active, stacked: None });
- }
- DockNode::Stack { entries } => {
- // A header for every entry; the open panels' bodies share the rest.
- let head = t.tab_h;
- let g = t.gap;
- let n = entries.len() as f32;
- let avail = rect.height() - n * head - (n - 1.0).max(0.0) * g;
- let bodies = stack_bodies(entries, avail);
- let mut y = rect.min.y;
- let mut drag = None;
- for (i, e) in entries.iter().enumerate() {
- let body = bodies.get(i).copied().unwrap_or(0.0);
- let r = Rect::from_min_max(pos2(rect.min.x, y), pos2(rect.max.x, (y + head + body).min(rect.max.y)));
- let content = Rect::from_min_max(pos2(r.min.x, r.min.y + head), r.max);
- let group = format!("{path}s{i}");
- // The gap below a panel resizes the open panels on either side of it.
- let above = entries.get(..=i).and_then(|s| s.iter().rposition(|x| x.open));
- let below = entries.get(i + 1..).and_then(|s| s.iter().position(|x| x.open)).map(|k| i + 1 + k);
- if let (Some(above), Some(below)) = (above, below) {
- let gap = Rect::from_min_max(pos2(rect.min.x, r.max.y), pos2(rect.max.x, r.max.y + g));
- if let Some(d) = gutter(ui, gap, true, &group, t, reg) {
- drag = Some((above, below, d));
- }
- }
- 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
- && let Some(panel) = after.shown()
- {
- actions.push(craft_ui::docking::Action::ResizeStack { panel, height: after.height });
- }
- }
+/// Draw the Timeline's comp tabs into `strip` (in its group header): the comp's label swatch, its
+/// name, and × on the shown one. Tabs past the strip's end are left out; Shift+, and Shift+. step
+/// through every open comp. Automation: `panel.tab.Timeline.<comp>`, and `panel.tab.Timeline.close`
+/// for the shown comp's ×.
+pub fn doc_tabs(ui: &mut egui::Ui, strip: Rect, docs: &[DocTab], t: &Tokens, reg: &mut crate::automation::Registry) -> Vec<DocAction> {
+ let mut out = Vec::new();
+ let painter = ui.painter().clone();
+ let mut x = strip.min.x;
+ let mid = strip.center().y;
+ for doc in docs {
+ let w = doc_width(ui, doc);
+ if x + w > strip.max.x {
+ break;
+ }
+ let tab = Rect::from_min_size(pos2(x, strip.min.y), vec2(w, strip.height()));
- let resp = ui.interact(tab, egui::Id::new(("comp-tab", doc.id)), Sense::click());
++ let resp = ui.interact(tab, egui::Id::unique(("comp-tab", doc.id)), Sense::click());
+ reg.add_response(&format!("panel.tab.{}.{}", PanelKind::Timeline.id(), doc.id), &resp, &doc.title);
+ if doc.active {
+ painter.rect_filled(tab, 0.0, t.panel_bg);
+ }
+ let sw = Rect::from_center_size(pos2(tab.min.x + DOC_PAD + 5.0, mid), vec2(9.0, 9.0));
+ painter.rect_filled(sw, 1.0, doc.swatch);
+ let color = if doc.active || resp.hovered() { t.tab_text_active } else { t.tab_text };
+ let galley = painter.layout_no_wrap(doc.title.clone(), Tokens::ui(12.0), color);
+ let label_x = tab.min.x + DOC_PAD + DOC_SWATCH;
+ let label_w = galley.size().x;
+ painter.galley(pos2(label_x, mid - galley.size().y / 2.0), galley, color);
+ if doc.active {
+ painter.line_segment([pos2(label_x, strip.max.y - 3.0), pos2(label_x + label_w, strip.max.y - 3.0)], Stroke::new(1.0, t.tab_text_active));
+ let cr = Rect::from_center_size(pos2(label_x + label_w + DOC_CLOSE / 2.0 + 2.0, mid), vec2(10.0, 10.0));
- let close = ui.interact(cr.expand(2.0), egui::Id::new(("comp-tab-close", doc.id)), Sense::click());
++ let close = ui.interact(cr.expand(2.0), egui::Id::unique(("comp-tab-close", doc.id)), Sense::click());
+ let cc = if close.hovered() { t.tab_text_active } else { t.tab_text };
+ let k = 3.5;
+ painter.line_segment([cr.center() + vec2(-k, -k), cr.center() + vec2(k, k)], Stroke::new(1.2, cc));
+ painter.line_segment([cr.center() + vec2(-k, k), cr.center() + vec2(k, -k)], Stroke::new(1.2, cc));
+ reg.add_response(&format!("panel.tab.{}.close", PanelKind::Timeline.id()), &close, "Close");
+ crate::widgets::focus_outline(ui, &close, t);
+ if close.clicked() {
+ out.push(DocAction::Close(doc.id));
}
}
- DockNode::Split { vertical, size, a, b } => {
- let axis = if *vertical { SplitAxis::Vertical } else { SplitAxis::Horizontal };
- let Some(split) = split_rect(rect, axis, size.shared(), t.gap, 20.0) else { return };
- let response = resize_handle(split.divider, *vertical, path, t).value(split.first_size(), 0.0..=split.available()).show(ui);
- reg.add(&format!("dock.gutter.{path}"), response.response.rect, "gutter");
- if response.delta != 0.0
- && let Some(resized) = split.resized(size.shared(), response.delta, 40.0)
- {
- actions.push(craft_ui::docking::Action::ResizeSplit { path: tree_path.to_vec(), size: resized });
- }
- let mut first_path = tree_path.to_vec();
- first_path.push(false);
- let mut second_path = tree_path.to_vec();
- second_path.push(true);
- layout_inner(ui, a, split.first, t, &format!("{path}a"), &first_path, out, reg, actions);
- layout_inner(ui, b, split.second, t, &format!("{path}b"), &second_path, out, reg, actions);
+ crate::widgets::focus_outline(ui, &resp, t);
+ if resp.clicked() {
+ out.push(DocAction::Activate(doc.id));
}
- }
-}
-
-/// A gap between dock areas that drags to resize them (`vertical`: up and down), with a slightly
-/// larger hit area than the gap. Returns the drag this frame.
-fn gutter(ui: &mut egui::Ui, gap: Rect, vertical: bool, path: &str, t: &Tokens, reg: &mut crate::automation::Registry) -> Option<f32> {
- let response = resize_handle(gap, vertical, path, t).show(ui);
- reg.add(&format!("dock.gutter.{path}"), response.response.rect, "gutter");
- (response.delta != 0.0).then_some(response.delta)
-}
-
-fn resize_handle(gap: Rect, vertical: bool, path: &str, t: &Tokens) -> ResizeHandle<'static> {
- let axis = if vertical { SplitAxis::Vertical } else { SplitAxis::Horizontal };
- let style = ResizeHandleStyle { hovered: t.focus.gamma_multiply(0.4), dragged: t.focus.gamma_multiply(0.9), focused: t.focus };
- let label = if vertical { crate::i18n::tr("Height:") } else { crate::i18n::tr("Width:") };
- ResizeHandle::new(egui::Id::unique(("dock-gutter", path.to_string())), axis, gap, label, style)
-}
-
-/// The least body height of an open stacked panel (when the stack has room for it).
-const STACK_MIN: f32 = 40.0;
-
-/// An open stacked panel without a height of its own: it shares the room the others leave.
-fn flexible(e: &StackEntry) -> bool {
- e.open && !e.height.is_some_and(f32::is_finite)
-}
-
-/// The body heights of a stack's panels in `avail` points (headers and gaps taken out). Open
-/// panels with a height keep it and the others share the rest; when no panel takes the rest, or
-/// there is too little room, the heights grow or shrink in proportion (down to [`STACK_MIN`]) so
-/// the open panels fill the stack.
-fn stack_bodies(entries: &[StackEntry], avail: f32) -> Vec<f32> {
- let avail = if avail.is_finite() { avail.max(0.0) } else { 0.0 };
- let open = entries.iter().filter(|e| e.open).count();
- let min = STACK_MIN.min(avail / open.max(1) as f32);
- let fixed: Vec<f32> = entries.iter().filter(|e| e.open && !flexible(e)).filter_map(|e| e.height).map(|h| h.max(min)).collect();
- let flex = open.saturating_sub(fixed.len());
- let k = fixed.len() as f32;
- // What the panels with a height may take, and how much of it lies above their minimum.
- let room = avail - flex as f32 * min;
- let sum: f32 = fixed.iter().sum();
- let (excess, target) = (sum - k * min, (room - k * min).max(0.0));
- let fit = flex == 0 || sum > room;
- let size = |h: f32| match (fit, excess > 0.0) {
- (false, _) => h,
- (true, true) => min + (h - min) / excess * target,
- (true, false) => min + target / k.max(1.0),
- };
- let used: f32 = fixed.iter().map(|&h| size(h)).sum();
- let share = (avail - used).max(0.0) / flex.max(1) as f32;
- entries
- .iter()
- .map(|e| match (e.open, flexible(e)) {
- (false, _) => 0.0,
- (true, true) => share,
- (true, false) => size(e.height.unwrap_or(min).max(min)),
- })
- .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
-/// (so the stack still fills its column when the window is resized).
-fn resize_stacked(entries: &mut [StackEntry], bodies: &[f32], above: usize, below: usize, d: f32) {
- let (Some(&a), Some(&b)) = (bodies.get(above), bodies.get(below)) else { return };
- let pair = a + b;
- let lo = STACK_MIN.min(pair / 2.0);
- let na = (a + d).max(lo).min(pair - lo);
- for (i, h) in [(above, na), (below, pair - na)] {
- let last_flexible = entries.iter().filter(|e| flexible(e)).count() == 1;
- if let Some(e) = entries.get_mut(i)
- && !(last_flexible && flexible(e))
- {
- e.height = Some(h);
+ if resp.middle_clicked() {
+ out.push(DocAction::Close(doc.id));
}
+ x += w;
}
+ out
}
-/// Draw a group's frame + tab strip: one tab per panel, or per document for panels that show
-/// several (the Timeline's comps). Tab labels may name the comp or layer they show (After
-/// Effects style).
-pub fn draw_group_chrome(ui: &mut egui::Ui, g: &Group, t: &Tokens, reg: &mut crate::automation::Registry, info: &TabInfo) -> Chrome {
- struct Entry {
- panel: PanelKind,
- doc: Option<u64>,
- label: String,
- deco: Option<TabDeco>,
- /// The group's shown tab.
- active: bool,
- /// The document its panel shows (even behind another tab).
- shown_doc: bool,
- }
- let mut out = Chrome::default();
- let painter = ui.painter().clone();
- painter.rect_filled(g.rect, t.radius, t.panel_bg);
- let active_panel = g.panels.get(g.active).copied();
- let compact = g.panels.len() == 1 && g.panels[0].compact();
- if compact {
- // grip dots
- let c = pos2(g.rect.center().x, g.rect.min.y + 4.0);
- for dx in [-4.0, 0.0, 4.0] {
- painter.circle_filled(c + vec2(dx, 0.0), 1.0, t.text_faint);
- }
+/// A viewer lock button (Composition viewers and the Timeline keep their comp while locked).
+/// Returns true when clicked. Automation: `panel.tab.<panel>.lock`.
+pub fn lock_button(ui: &mut egui::Ui, rect: Rect, panel: PanelKind, locked: bool, t: &Tokens, reg: &mut crate::automation::Registry) -> bool {
- let resp = ui.interact(rect, egui::Id::new(("tab-lock", panel.id())), Sense::click());
++ let resp = ui.interact(rect, egui::Id::unique(("tab-lock", panel.id())), Sense::click());
+ let color = if locked {
+ t.tab_text_active
+ } else if resp.hovered() {
+ t.tab_text
} else {
- let mut entries: Vec<Entry> = vec![];
- for (pi, p) in g.panels.iter().enumerate() {
- let shown = pi == g.active;
- match info.docs.iter().find(|(k, d)| k == p && !d.is_empty()) {
- Some((_, docs)) => entries.extend(docs.iter().map(|d| Entry {
- panel: *p,
- doc: Some(d.id),
- label: d.title.clone(),
- deco: d.deco,
- active: shown && d.active,
- shown_doc: d.active,
- })),
- None => entries.push(Entry {
- panel: *p,
- doc: None,
- label: (info.title)(*p),
- deco: info.decos.iter().find(|(k, _)| k == p).map(|(_, d)| *d),
- active: shown,
- shown_doc: false,
- }),
- }
- }
- let ai = entries.iter().position(|e| e.active).unwrap_or(0);
- let strip = Rect::from_min_size(g.rect.min, vec2(g.rect.width(), t.tab_h));
- if t.gradients {
- // Settings ▸ Appearance ▸ Use Gradients.
- crate::theme::gradient_rect(&painter, strip.shrink2(vec2(t.radius, 0.0)), t.grad_top(t.panel_bg), t.panel_bg);
- }
- let activate = |e: &Entry| match e.doc {
- Some(id) => DockAction::ActivateDoc(e.panel, id),
- None => DockAction::Activate(e.panel),
- };
- let close = |e: &Entry| match e.doc {
- Some(id) => DockAction::CloseDoc(e.panel, id),
- None => DockAction::Close(e.panel),
- };
- let mut x = strip.min.x + 12.0;
- let text_y = strip.min.y + 16.0;
- for (k, e) in entries.iter().enumerate() {
- let p = &e.panel;
- // A collapsed stacked panel's header is plain text (no underline or panel menu).
- let is_active = k == ai && g.stacked != Some(false);
- let galley = painter.layout_no_wrap(e.label.clone(), Tokens::ui(12.0), if is_active { t.tab_text_active } else { t.tab_text });
- let menu_w = if is_active { 20.0 } else { 0.0 };
- // The lock belongs to the panel: on its shown document's tab only.
- let lock = e.deco.is_some_and(|d| d.viewer) && (e.doc.is_none() || is_active);
- // × (active tab only), swatch and lock before the label.
- let deco_w = match e.deco {
- Some(d) if d.viewer => (if is_active { 16.0 } else { 0.0 }) + 14.0 + if lock { 16.0 } else { 0.0 },
- Some(_) => 14.0,
- None => 0.0,
- };
- let w = galley.size().x + 16.0 + menu_w + deco_w;
- if x + w > strip.max.x - 20.0 && k > ai {
- let r = Rect::from_min_size(pos2(strip.max.x - 22.0, strip.min.y + 6.0), vec2(18.0, 20.0));
- let resp = ui.interact(r, egui::Id::unique(("tab-overflow", g.path.clone())), Sense::click());
- icons::paint(&painter, r.shrink(4.0).translate(vec2(-2.0, 0.0)), Icon::ChevronRight, t.tab_text);
- icons::paint(&painter, r.shrink(4.0).translate(vec2(2.0, 0.0)), Icon::ChevronRight, t.tab_text);
- crate::widgets::focus_outline(ui, &resp, t);
- reg.add_response(&format!("panel.overflow.{}", g.path), &resp, "More tabs");
- if resp.clicked()
- && let Some(next) = entries.get((ai + 1) % entries.len())
- {
- out.actions.push(activate(next));
- }
- break;
- }
- let tab = Rect::from_min_size(pos2(x, strip.min.y), vec2(w, t.tab_h));
- match out.tabs.iter_mut().find(|(q, _)| q == p) {
- Some((_, r)) => *r = r.union(tab),
- None => out.tabs.push((*p, tab)),
- }
- let resp = ui.interact(tab, egui::Id::unique(("tab", g.path.clone(), k)), Sense::click_and_drag());
- if resp.drag_started() {
- out.actions.push(DockAction::BeginDrag(*p));
- }
- // A document tab also answers to the panel's id while it is the shown one.
- let auto_id = match e.doc {
- Some(id) => format!("panel.tab.{}.{id}", p.id()),
- None => format!("panel.tab.{}", p.id()),
- };
- reg.add_response(&auto_id, &resp, &e.label);
- if e.shown_doc {
- reg.add_response(&format!("panel.tab.{}", p.id()), &resp, &e.label);
- }
- let mut label_x = tab.min.x + 8.0;
- if let Some(d) = e.deco {
- let mut dx = tab.min.x + 6.0;
- if is_active && d.viewer {
- let cr = Rect::from_center_size(pos2(dx + 5.0, text_y), vec2(10.0, 10.0));
- let cresp = ui.interact(cr.expand(2.0), egui::Id::unique(("tab-close", g.path.clone(), k)), Sense::click());
- let cc = if cresp.hovered() { t.tab_text_active } else { t.tab_text };
- let kk = 3.5;
- painter.line_segment([cr.center() + vec2(-kk, -kk), cr.center() + vec2(kk, kk)], Stroke::new(1.2, cc));
- painter.line_segment([cr.center() + vec2(-kk, kk), cr.center() + vec2(kk, -kk)], Stroke::new(1.2, cc));
- reg.add_response(&format!("panel.tab.{}.close", p.id()), &cresp, "Close");
- crate::widgets::focus_outline(ui, &cresp, t);
- if cresp.clicked() {
- out.actions.push(close(e));
- }
- dx += 16.0;
- }
- let sw = Rect::from_center_size(pos2(dx + 5.0, text_y), vec2(9.0, 9.0));
- painter.rect_filled(sw, 1.0, d.swatch);
- dx += 14.0;
- label_x = dx;
- if lock {
- let lr = Rect::from_center_size(pos2(dx + 6.0, text_y), vec2(12.0, 12.0));
- let lresp = ui.interact(lr.expand(2.0), egui::Id::unique(("tab-lock", g.path.clone(), k)), Sense::click());
- let lc = if d.locked {
- t.tab_text_active
- } else if lresp.hovered() {
- t.tab_text
- } else {
- t.text_faint
- };
- icons::paint(&painter, lr, Icon::Lock, lc);
- reg.add_response(&format!("panel.tab.{}.lock", p.id()), &lresp, if d.locked { "Unlock" } else { "Lock" });
- crate::widgets::focus_outline(ui, &lresp, t);
- if lresp.clicked() {
- out.actions.push(DockAction::ToggleLock(*p));
- }
- label_x = dx + 16.0;
- }
- }
- let label_w = galley.size().x;
- let col = if is_active || resp.hovered() { t.tab_text_active } else { t.tab_text };
- painter.galley_with_override_text_color(pos2(label_x, text_y - galley.size().y / 2.0), galley, col);
- if is_active {
- let mr = Rect::from_center_size(pos2(label_x + label_w + 12.0, text_y), vec2(12.0, 10.0));
- let mresp = ui.interact(mr.expand(3.0), egui::Id::unique(("tab-menu", g.path.clone())), Sense::click());
- reg.add_response(&format!("panel.menu.{}", p.id()), &mresp, "panel menu");
- let mc = if mresp.hovered() { t.tab_text_active } else { t.tab_text };
- for dy in [-3.5, 0.0, 3.5] {
- painter.line_segment([pos2(mr.min.x, mr.center().y + dy), pos2(mr.max.x, mr.center().y + dy)], Stroke::new(1.5, mc));
- }
- let uy = strip.min.y + 23.0;
- painter.line_segment([pos2(label_x, uy), pos2(mr.max.x, uy)], Stroke::new(1.0, t.tab_text_active));
- crate::widgets::focus_outline(ui, &mresp, t);
- if mresp.clicked() {
- out.actions.push(DockAction::PanelMenu(*p, mr.left_bottom()));
- }
- }
- crate::widgets::focus_outline(ui, &resp, t);
- if resp.clicked() {
- // 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));
- }
- out.actions.push(DockAction::Focus(*p));
- }
- if resp.middle_clicked() {
- out.actions.push(close(e));
- }
- 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::unique(("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; a press on another of its tabs waits for that
- // tab's click, which focuses the panel actually chosen (a text edit stays open in Character)
- let at = ui.input(|i| i.pointer.interact_pos());
- if let Some(p) = active_panel
- && ui.rect_contains_pointer(g.rect)
- && ui.input(|i| i.pointer.any_pressed())
- && !out.tabs.iter().any(|(q, r)| *q != p && at.is_some_and(|a| r.contains(a)))
- {
- out.actions.push(DockAction::Focus(p));
- }
- out
+ t.text_faint
+ };
+ icons::paint(ui.painter(), rect.shrink(2.0), Icon::Lock, color);
+ reg.add_response(&format!("panel.tab.{}.lock", panel.id()), &resp, if locked { "Unlock" } else { "Lock" });
+ crate::widgets::focus_outline(ui, &resp, t);
+ resp.clicked()
}
/// Placeholder body for panels that are not implemented yet.
diff --cc crates/ui-egui/src/dock_ui.rs
index ffde5f2e4,559cb2191..7c7cd4f45
--- a/crates/ui-egui/src/dock_ui.rs
+++ b/crates/ui-egui/src/dock_ui.rs
@@@ -1,143 -1,19 +1,143 @@@
-//! The dock area: lays out the docked tree (or the maximized panel), draws each group's chrome
-//! and body, floating (undocked) panel groups over it, and tab drag-and-drop: drag a tab onto a
-//! group to tab it there (center) or split it off to a side (After Effects' drop zones, with a
-//! highlight of where it will land); hold Cmd/Ctrl when releasing, or drop outside every group,
-//! to float it. `` ` `` maximizes the panel under the pointer. A floating group can also move
-//! out of the main window into its own native window ([`EffectcraftApp::set_panel_window`]),
-//! which can sit on another monitor.
+//! EffectCraft's panels in craft-ui's shared docking. craft-ui draws the frames, tab strips,
+//! stacked panels, floating windows, dividers and drop previews and owns the gestures (drag a tab
+//! onto a group to tab it there or split it off to a side; hold Cmd/Ctrl at the release, or drop
+//! outside every group, to float it). EffectCraft draws the panel bodies, the ≡ panel menu, the
+//! Timeline's comp tabs and the viewer locks in each group header, and runs every layout change
+//! through its command path (`window.dockAction`), so pointer, menu and control-channel changes
+//! share one route.
-use egui::{Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
+use crate::state::UiState;
+use craft_ui::docking::{Action, Divider, DockArea, DockCommand, DockContent, DockError, DockEvent, DockStyle, FloatSpace, Hit, ResizeEdge, UiDock};
+use egui::{Rect, Sense, Stroke, StrokeKind, pos2, vec2};
+use serde_json::{Value, json};
-use crate::dock::{self, DockAction, DockNode, Group, Layout, PanelKind, PanelWindow};
+use crate::dock::{self, DocAction, DocTab, PanelKind, Workspace, WorkspaceExt as _};
+use crate::icons::{self, Icon};
+use crate::theme::Tokens;
use crate::{EffectcraftApp, panels};
-use craft_ui::docking::{Action, DropTarget, resolve_drop};
-fn drag_id() -> egui::Id {
- egui::Id::unique("dock-tab-drag")
+/// The dock area's egui id; `DockArea::hit_rects` and `float_space` read by it.
+pub fn area_id() -> egui::Id {
- egui::Id::new("effectcraft-docking")
++ egui::Id::unique("effectcraft-docking")
+}
+
+/// Width of the ≡ panel menu button at the end of each tab strip.
+const MENU_W: f32 = 26.0;
+/// Width of the viewer lock before it.
+const LOCK_W: f32 = 18.0;
+
+/// The smallest and largest native panel window, in points.
+pub const PANEL_WINDOW_MIN: [f32; 2] = [160.0, 100.0];
+pub const PANEL_WINDOW_MAX: f32 = 16_384.0;
+/// The farthest a native panel window may sit from the desktop origin, in points.
+pub const PANEL_WINDOW_MAX_POS: f32 = 100_000.0;
+
+/// A native panel window's desktop rect made safe to hand to the windowing system: finite, with
+/// a size within [`PANEL_WINDOW_MIN`]..=[`PANEL_WINDOW_MAX`] and a position within
+/// ±[`PANEL_WINDOW_MAX_POS`] (hostile workspace files and bad monitor reports included).
+pub fn sanitized_window_rect(rect: [f32; 4]) -> [f32; 4] {
+ let finite = |v: f32, fallback: f32| if v.is_finite() { v } else { fallback };
+ let [x, y, w, h] = rect;
+ [
+ finite(x, 0.0).clamp(-PANEL_WINDOW_MAX_POS, PANEL_WINDOW_MAX_POS),
+ finite(y, 0.0).clamp(-PANEL_WINDOW_MAX_POS, PANEL_WINDOW_MAX_POS),
+ finite(w, 420.0).clamp(PANEL_WINDOW_MIN[0], PANEL_WINDOW_MAX),
+ finite(h, 320.0).clamp(PANEL_WINDOW_MIN[1], PANEL_WINDOW_MAX),
+ ]
+}
+
+/// How long to wait for the main window to report its frame before migrated native windows
+/// keep their places as they are, in seconds.
+const FRAME_REPORT_WAIT: f64 = 2.0;
+
+/// Moves the native rects of [`UiState::native_outer`]'s windows from the OS window's outer
+/// position to its content position, by the main window's frame offset (`inner` less `outer`,
+/// the main window's desktop rects): the earlier version's windows had the same OS title bar.
+/// Without a report by [`FRAME_REPORT_WAIT`] (a backend without window positions), the places
+/// stay as they are.
+pub(crate) fn native_outer_to_content(ui: &mut UiState, outer: Option<Rect>, inner: Option<Rect>, now: f64) {
+ let offset = match (outer, inner) {
+ (Some(outer), Some(inner)) if outer.min.is_finite() && inner.min.is_finite() => inner.min - outer.min,
+ _ if now < FRAME_REPORT_WAIT => return,
+ _ => egui::Vec2::ZERO,
+ };
+ let ids = std::mem::take(&mut ui.native_outer);
+ for window in ui.dock.layout.floating.iter_mut().filter(|w| ids.contains(&w.id)) {
+ if let Some([x, y, w, h]) = window.native {
+ window.native = Some(sanitized_window_rect([x + offset.x, y + offset.y, w, h]));
+ }
+ }
+}
+
+/// A new floating group's default rect near the centre of `screen`.
+pub fn default_float_rect(screen: Rect) -> [f32; 4] {
+ let c = screen.center();
+ [c.x - 210.0, c.y - 160.0, 420.0, 320.0]
+}
+
+/// A panel named by its title or id ("Effect Controls", "EffectControls") or its serialized
+/// form (`{"Viewer": 2}`).
+fn panel_param(value: &Value) -> Result<PanelKind, String> {
+ match value.as_str() {
+ Some(name) => PanelKind::from_name(name).ok_or(format!("unknown panel `{name}`")),
+ None => serde_json::from_value::<PanelKind>(value.clone()).map_err(|_| "unknown `panel`".to_string()),
+ }
+}
+
+/// The docking commands: `window.dockAction {action}`, craft-ui's `window.panel.*` commands,
+/// `ui.dock` and `ui.dock.reset`. `None` for any other id.
+pub(crate) fn route(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option<Result<Value, String>> {
+ match id {
+ "window.dockAction" => Some((|| {
+ let value = params.get("action").cloned().ok_or("missing docking action")?;
+ let action: Action<PanelKind> = serde_json::from_value(value).map_err(|error| format!("invalid docking action: {error}"))?;
+ if matches!(&action, Action::Open { .. } | Action::OpenAt { .. }) {
+ return Err("use the panel open commands to preserve viewer and ScriptUI lifecycle callbacks".into());
+ }
+ app.apply_dock(action)?;
+ Ok(Value::Null)
+ })()),
+ "ui.dock.reset" => {
+ let name = app.ui.workspace.clone();
+ app.set_workspace(&name);
+ Some(Ok(json!({"docking": app.ui.dock})))
+ }
+ "ui.dock" => Some((|| {
+ let mut tagged = if params.is_object() { params.clone() } else { json!({}) };
+ if let Some(fields) = tagged.as_object_mut() {
+ fields.insert("command".into(), json!("ui.dock"));
+ }
+ let command: DockCommand<PanelKind> = serde_json::from_value(tagged).map_err(|error| format!("invalid ui.dock params: {error}"))?;
+ app.run_dock_command(ctx, command)?;
+ Ok(json!({"docking": app.ui.dock}))
+ })()),
+ _ if id.starts_with("window.panel.") && DockCommand::<PanelKind>::IDS.contains(&id) => Some((|| {
+ let mut tagged = if params.is_object() { params.clone() } else { json!({}) };
+ if let Some(fields) = tagged.as_object_mut() {
+ fields.insert("command".into(), json!(id));
+ // EffectCraft's panel names ("Effect Controls") as well as craft-ui's ids.
+ for key in ["panel", "anchor", "before"] {
+ if let Some(name) = fields.get(key).and_then(Value::as_str) {
+ let panel = PanelKind::from_name(name).ok_or(format!("unknown panel `{name}`"))?;
+ fields.insert(key.into(), json!(panel));
+ }
+ }
+ }
+ let command: DockCommand<PanelKind> = serde_json::from_value(tagged).map_err(|error| format!("invalid docking command: {error}"))?;
+ app.run_dock_command(ctx, command)?;
+ Ok(Value::Null)
+ })()),
+ "window.panelWindow" => Some((|| {
+ let panel = panel_param(params.get("panel").ok_or("panelWindow: need `panel`")?).map_err(|e| format!("panelWindow: {e}"))?;
+ let window = match params.get("window") {
+ None | Some(Value::Null) => None,
+ Some(value) => Some(value.as_bool().ok_or("panelWindow: `window` must be true or false")?),
+ };
+ let window = app.set_panel_window(ctx, panel, window)?;
+ Ok(json!({"window": window}))
+ })()),
+ _ => None,
+ }
}
impl EffectcraftApp {
@@@ -424,284 -238,443 +424,304 @@@
panels::home::show(self, &mut child, body);
return;
}
- // The maximized panel fills the area; the tree is kept as it is.
- let maximized = self.ui.maximized.filter(|m| self.ui.dock.contains(*m));
- let mut dock = match maximized {
- Some(m) => DockNode::Tabs { panels: vec![m], active: 0 },
- None => std::mem::replace(&mut self.ui.dock, DockNode::Tabs { panels: vec![], active: 0 }),
- };
- let mut groups = Vec::new();
- let mut layout_actions = Vec::new();
- dock::layout_with_actions(ui, &mut dock, body, &t, "", &mut groups, &mut self.auto, &mut layout_actions);
- let mut actions = Vec::new();
- let titles = self.tab_titles();
- let decos = self.tab_decos();
+ let style = dock_style(ui, &t);
+ let maximized = self.ui.maximized.filter(|m| self.ui.dock.is_docked(*m));
+ let mut area = DockArea::new(area_id()).float_bounds(body).maximized(maximized).locked(self.ui.dock.locked).input_blocked(self.floats_blocked(&ctx));
+ if let Some(panel) = self.pending_panel_raise.take() {
+ area = area.raise_panel(panel);
+ }
+ let layout = self.ui.dock.layout.clone();
+ let mut child = ui.new_child(egui::UiBuilder::new().max_rect(body).id_salt("effectcraft-dock-area"));
+ child.set_clip_rect(body.intersect(ui.clip_rect()));
let docs = self.tab_docs();
- let title = |p: PanelKind| {
- titles.iter().find(|(k, _)| *k == p).map(|(_, s)| s.clone()).unwrap_or_else(|| crate::i18n::command_label("window.panel", p.title()).to_string())
+ let doc_width = dock::doc_tabs_width(ui, &docs);
+ let mut content = EffectContent {
+ titles: self.tab_titles(),
+ swatches: self.tab_swatches(),
+ docs,
+ doc_width,
+ app: self,
+ tokens: t,
+ doc_actions: Vec::new(),
+ locks: Vec::new(),
+ menu: None,
+ bodies: Vec::new(),
++ viewports: Vec::new(),
};
- let info = dock::TabInfo { title: &title, decos: &decos, docs: &docs };
- // Where each group's tabs are (tab drags show where a tab will land between them).
- let mut tab_rects: Vec<(String, Vec<(PanelKind, Rect)>)> = vec![];
- for g in &groups {
- let c = dock::draw_group_chrome(ui, g, &t, &mut self.auto, &info);
- actions.extend(c.actions);
- tab_rects.push((g.path.clone(), c.tabs));
- }
- self.label_tab_marks(ui);
- if maximized.is_none() {
- self.ui.dock = dock;
- }
- self.dock_rects = groups.iter().filter_map(|g| Some((*g.panels.get(g.active)?, g.rect))).collect();
- for g in &groups {
- let Some(p) = g.panels.get(g.active).copied() else { continue };
- if g.content.height() < 2.0 {
- continue; // a collapsed stacked panel: header only
- }
- self.panel_body(ui, p, g.content);
- }
- for g in &groups {
- if g.panels.get(g.active) == Some(&self.ui.focused) {
- ui.painter().rect_stroke(g.rect, 0.0, Stroke::new(1.0, t.focus), StrokeKind::Inside);
- }
- }
- // Floating groups over the dock.
- let mut float_groups: Vec<Group> = vec![];
- let layers = ctx.memory(|memory| memory.layer_ids().collect::<Vec<_>>());
- let mut floating_order: Vec<_> = (0..self.ui.floating.len()).collect();
- floating_order.sort_by_key(|index| {
- self.ui
- .floating
- .get(*index)
- .and_then(|group| group.panels.first())
- .and_then(|panel| {
- let id = egui::Id::unique(("floating-panel", panel.id()));
- layers.iter().position(|layer| layer.id == id)
- })
- .unwrap_or(usize::MAX)
- });
- // A native window is kept only for a panel that still floats. A native viewport that
- // goes away releases its IME context: its composition must not reappear elsewhere.
- let ui_state = &mut self.ui;
- let gone: Vec<egui::ViewportId> = ui_state
- .panel_windows
- .iter()
- .filter(|w| !ui_state.floating.iter().any(|group| group.panels.contains(&w.panel)))
- .map(|w| panel_window_id(w.panel))
- .collect();
- ui_state.panel_windows.retain(|w| ui_state.floating.iter().any(|group| group.panels.contains(&w.panel)));
+ let mut output = area.show_content(&mut child, &layout, &style, &mut content);
- let EffectContent { doc_actions, locks, menu, bodies, .. } = content;
++ let EffectContent { doc_actions, locks, menu, bodies, viewports, .. } = content;
+ self.dock_rects = bodies;
++ // A window that closed or docked takes its composition with it.
++ let previous = std::mem::replace(&mut self.native_viewports, viewports);
++ let gone: Vec<_> = previous.into_iter().filter(|v| !self.native_viewports.contains(v)).collect();
+ for viewport in gone {
+ panels::viewer_text::end_viewport(self, &ctx, viewport);
+ }
- for i in floating_order {
- // Groups in their own native window take no tab drops from the main window.
- if let Some(window) = self.ui.floating.get(i).and_then(|group| self.panel_window_of(&group.panels)) {
- self.panel_window(&ctx, i, window, &info);
- continue;
- }
- if let Some((g, tabs)) = self.floating_window(&ctx, i, &info, &mut actions) {
- tab_rects.push((g.path.clone(), tabs));
- float_groups.push(g);
- }
- }
- for action in layout_actions {
- let _ = self.dock_command(&ctx, action);
+ self.forward_window_input(&ctx, std::mem::take(&mut output.forwarded_events), std::mem::take(&mut output.window_files));
+ if let Some(panel) = output.focused {
+ self.focus_panel(&ctx, panel);
}
- for a in actions {
- self.handle_dock_action(&ctx, a);
+ if let Some(error) = output.error {
+ self.ui.status = error.to_string();
}
- self.tab_drag(&ctx, &groups, &float_groups, &tab_rects);
- panels::panel_menu_popup(self, ui);
- }
-
- /// One floating group: a window with a tab strip (drag the empty strip to move it, the
- /// corner to resize it) and the active panel's body.
- fn floating_window(
- &mut self,
- ctx: &egui::Context,
- i: usize,
- info: &dock::TabInfo,
- actions: &mut Vec<DockAction>,
- ) -> Option<(Group, Vec<(PanelKind, Rect)>)> {
- let t = self.tokens;
- let f = self.ui.floating.get(i)?.clone();
- let screen = ctx.content_rect();
- let mut rect = Rect::from_min_size(pos2(f.rect[0], f.rect[1]), vec2(f.rect[2].max(160.0), f.rect[3].max(100.0)));
- // Keep the strip reachable.
- rect = rect.translate(vec2(
- (screen.min.x - rect.min.x).max(0.0) + (screen.max.x - 40.0 - rect.min.x).min(0.0),
- (screen.min.y - rect.min.y).max(0.0) + (screen.max.y - 30.0 - rect.min.y).min(0.0),
- ));
- let id = egui::Id::unique(("floating-panel", f.panels.first().map(|p| p.id()).unwrap_or_default()));
- let mut group = None;
- // Not constrained to the window: the group is drawn where its rect says (the clamp above
- // keeps its strip reachable), so it follows the pointer past the window's edges.
- egui::Area::new(id).order(egui::Order::Middle).fixed_pos(rect.min).constrain(false).interactable(true).show(ctx, |ui| {
- let (r, _) = ui.allocate_exact_size(rect.size(), Sense::hover());
- ui.painter().rect_filled(r.expand(1.0), t.radius, Color32::from_black_alpha(90));
- let strip = Rect::from_min_size(r.min, vec2(r.width(), t.tab_h));
- // Move by the strip (tabs, registered later, take precedence over it).
- // (`id.with("move")` is the id of the `Area`'s own background widget.)
- let mv = ui.interact(strip, id.with("strip"), Sense::drag());
- self.auto.add(&format!("panel.float.{i}.move"), strip, "Move floating panel");
- let mut nr = r;
- if mv.dragged() {
- nr = nr.translate(mv.drag_delta());
- }
- let g = Group {
- path: format!("f{i}"),
- rect: r,
- content: Rect::from_min_max(pos2(r.min.x, r.min.y + t.tab_h), r.max),
- panels: f.panels.clone(),
- active: f.active.min(f.panels.len().saturating_sub(1)),
- stacked: None,
- };
- let c = dock::draw_group_chrome(ui, &g, &t, &mut self.auto, info);
- actions.extend(c.actions);
- if let Some(p) = g.panels.get(g.active).copied() {
- self.panel_body(ui, p, g.content);
- }
- ui.painter().rect_stroke(r, t.radius, Stroke::new(1.0, t.field_border), StrokeKind::Outside);
- if g.panels.get(g.active) == Some(&self.ui.focused) {
- ui.painter().rect_stroke(r, t.radius, Stroke::new(1.0, t.focus), StrokeKind::Inside);
- }
- // Resize from the corner.
- let grip = Rect::from_min_max(r.max - vec2(14.0, 14.0), r.max);
- let rs = ui.interact(grip, id.with("resize"), Sense::click_and_drag());
- rs.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Splitter, rs.enabled(), crate::i18n::tr("Resize floating panel")));
- self.auto.add_response(&format!("panel.float.{i}.resize"), &rs, "Resize floating panel");
- for k in 0..3 {
- let o = 4.0 + k as f32 * 4.0;
- ui.painter().line_segment([pos2(r.max.x - o, r.max.y - 2.0), pos2(r.max.x - 2.0, r.max.y - o)], Stroke::new(1.0, t.text_faint));
- }
- if rs.hovered() || rs.dragged() {
- ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeNwSe);
- }
- let delta = floating_resize_delta(ui, &rs);
- if rs.has_focus() {
- ui.painter().rect_stroke(grip, 2.0, Stroke::new(1.5, t.focus), StrokeKind::Inside);
+ for event in output.events {
+ if let DockEvent::ToggleMaximize { panel } = event {
+ self.toggle_maximize(panel);
}
- if delta != egui::Vec2::ZERO {
- nr = Rect::from_min_size(nr.min, (nr.size() + delta).max(vec2(160.0, 100.0)));
- }
- if nr != r
- && let Some(panel) = f.panels.first().copied()
- {
- let _ = self.dock_command(ctx, Action::MoveFloating { panel, rect: [nr.min.x, nr.min.y, nr.width(), nr.height()] });
- }
- group = Some((g, c.tabs));
- });
- group
- }
-
- /// The native window a floating group (its `panels`) shows in, if any.
- pub(crate) fn panel_window_of(&self, panels: &[PanelKind]) -> Option<PanelWindow> {
- self.ui.panel_windows.iter().find(|w| panels.contains(&w.panel)).copied()
- }
-
- /// Whether panel `p` shows in its own native window.
- pub fn in_panel_window(&self, p: PanelKind) -> bool {
- self.ui.floating.iter().any(|group| group.panels.contains(&p) && self.panel_window_of(&group.panels).is_some())
- }
-
- /// The viewport panel `p` is drawn in: its native window's, or the main window's (also when
- /// the platform embeds viewports, as the browser build does).
- pub(crate) fn panel_viewport(&self, ctx: &egui::Context, p: PanelKind) -> egui::ViewportId {
- if ctx.embed_viewports() {
- return egui::ViewportId::ROOT;
}
- self.ui
- .floating
- .iter()
- .find(|group| group.panels.contains(&p))
- .and_then(|group| self.panel_window_of(&group.panels))
- .map_or(egui::ViewportId::ROOT, |w| panel_window_id(w.panel))
- }
-
- /// Move panel `p` (and the floating group it is in) into its own native window, which can be
- /// placed on another monitor, or back into the main window (`window` false; it floats there
- /// where it was before). `None` toggles. A docked panel is undocked first. The window opens
- /// over the place the panel had in the main window. Returns whether `p` is now in a window.
- pub fn set_panel_window(&mut self, ctx: &egui::Context, p: PanelKind, window: Option<bool>) -> Result<bool, String> {
- let group_of = |app: &Self| app.ui.floating.iter().find(|group| group.panels.contains(&p)).map(|group| (group.panels.clone(), group.rect));
- let current = self.in_panel_window(p);
- let window = window.unwrap_or(!current);
- if window == current {
- return Ok(current);
- }
- if !window {
- if let Some((panels, _)) = group_of(self) {
- self.ui.panel_windows.retain(|w| !panels.contains(&w.panel));
+ for action in output.actions {
+ if let Err(error) = self.dock_command(&ctx, action) {
+ self.ui.status = error;
}
- return Ok(false);
}
- if group_of(self).is_none() {
- if !self.ui.dock.contains(p) {
- return Err(format!("{} is not open", p.title()));
- }
- let rect = default_float_rect(ctx.input_for(egui::ViewportId::ROOT, |i| i.content_rect()));
- if !self.edit_layout(|layout| layout.float(p, rect)) {
- return Err(format!("can't undock {}", p.title()));
+ for p in locks {
+ if !self.ui.locked_tabs.remove(&p.id()) {
+ self.ui.locked_tabs.insert(p.id().to_string());
}
}
- let Some((_, [x, y, w, h])) = group_of(self) else { return Err(format!("can't undock {}", p.title())) };
- // Over the panel's place in the main window (its content's position on the desktop).
- let origin = ctx.input_for(egui::ViewportId::ROOT, |i| i.viewport().inner_rect.map(|r| r.min)).unwrap_or(pos2(0.0, 0.0));
- let rect = PanelWindow::sanitized([origin.x + x, origin.y + y, w, h]);
- ctx.data_mut(|d| d.remove::<[f32; 4]>(panel_window_spawn_id(p)));
- self.ui.panel_windows.push(PanelWindow { panel: p, rect });
- if self.ui.maximized == Some(p) {
- self.ui.maximized = None;
- }
- Ok(true)
- }
-
- /// One floating group in its own native window: the group's tab strip and active panel fill
- /// the window. Closing the window brings the group back into the main window.
- fn panel_window(&mut self, ctx: &egui::Context, i: usize, window: PanelWindow, info: &dock::TabInfo) {
- let t = self.tokens;
- let Some(f) = self.ui.floating.get(i).cloned() else { return };
- let active = f.active.min(f.panels.len().saturating_sub(1));
- let Some(shown) = f.panels.get(active).copied() else { return };
- // The window opens at its saved place; after that the window system owns its position and
- // size (handing them back every frame would fight the user dragging it).
- let spawn_id = panel_window_spawn_id(window.panel);
- let spawn = ctx.data_mut(|d| *d.get_temp_mut_or_insert_with(spawn_id, || PanelWindow::sanitized(window.rect)));
- let builder = egui::ViewportBuilder::default()
- .with_title((info.title)(shown))
- .with_position([spawn[0], spawn[1]])
- .with_inner_size([spawn[2], spawn[3]])
- .with_min_inner_size(dock::PANEL_WINDOW_MIN);
- let mut closed = false;
- let mut placed = None;
- let mut pass_viewport = None;
- let mut actions = Vec::new();
- ctx.show_viewport_immediate(panel_window_id(window.panel), builder, |ui, class| {
- pass_viewport = Some(ui.ctx().viewport_id());
- let native = matches!(class, egui::ViewportClass::Immediate | egui::ViewportClass::Deferred);
- if native {
- panels::viewer_text::begin_ui(ui.ctx());
- }
- egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.panel_bg)).show(ui, |ui| {
- let r = ui.max_rect();
- let g = Group {
- path: format!("w{i}"),
- rect: r,
- content: Rect::from_min_max(pos2(r.min.x, (r.min.y + t.tab_h).min(r.max.y)), r.max),
- panels: f.panels.clone(),
- active,
- stacked: None,
- };
- let c = dock::draw_group_chrome(ui, &g, &t, &mut self.auto, info);
- // Tabs can't be dragged between native windows yet.
- actions.extend(c.actions.into_iter().filter(|a| !matches!(a, DockAction::BeginDrag(_))));
- self.panel_body(ui, shown, g.content);
- if shown == self.ui.focused {
- ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, t.focus), StrokeKind::Inside);
- }
- if native {
- panels::panel_menu_popup(self, ui);
+ for action in doc_actions {
+ let result = match action {
+ // The Timeline's comp tabs: show that comp / close its Timeline.
+ DocAction::Activate(id) => {
+ let _ = self.apply_dock(Action::Activate { panel: PanelKind::Timeline });
+ self.focus_panel(&ctx, PanelKind::Timeline);
+ if self.session.state.active_comp.map(|c| c.0) == Some(id) {
+ Ok(Value::Null)
+ } else {
+ crate::menus::invoke(self, &ctx, "comp.open", json!({"comp": id}))
+ }
}
- });
- // Apply this window's panel/tab actions before publishing its IME descriptor: a
- // click-away or close in the floating panel must own the pass's final output.
- for action in actions.drain(..) {
- self.handle_dock_action(ui.ctx(), action);
- }
- panels::viewer_text::finish_ime(self, ui);
- // An embedded window (no native windows on this platform) reads the main window's
- // input: its close request and place aren't this window's.
- if native {
- closed = ui.input(|i| i.viewport().close_requested());
- placed = ui.input(|i| {
- let v = i.viewport();
- let inner = v.inner_rect?;
- let min = v.outer_rect.map_or(pos2(window.rect[0], window.rect[1]), |outer| outer.min);
- Some([min.x, min.y, inner.width(), inner.height()])
- });
- }
- });
- if closed {
- self.ui.panel_windows.retain(|w| !f.panels.contains(&w.panel));
- if let Some(viewport) = pass_viewport {
- panels::viewer_text::end_viewport(self, ctx, viewport);
+ DocAction::Close(id) => crate::menus::invoke(self, &ctx, "comp.close", json!({"comp": id})),
+ };
+ if let Err(error) = result {
+ self.ui.status = error;
}
- panels::viewer_text::end_viewport(self, ctx, panel_window_id(window.panel));
- ctx.data_mut(|d| d.remove::<[f32; 4]>(spawn_id));
- return;
}
- // Remember where the window is, so the workspace reopens it there.
- if let Some(rect) = placed.map(PanelWindow::sanitized)
- && rect != window.rect
- && let Some(w) = self.ui.panel_windows.iter_mut().find(|w| w.panel == window.panel)
- {
- w.rect = rect;
+ if let Some((panel, pos)) = menu {
- ctx.data_mut(|d| d.insert_temp(egui::Id::new("panel-menu"), (panel, pos)));
++ ctx.data_mut(|d| d.insert_temp(egui::Id::unique("panel-menu"), (panel, pos)));
}
+ let hits = DockArea::<PanelKind>::hit_rects(&ctx, area_id());
+ self.register_dock_hits(&hits);
+ panels::panel_menu_popup(self, ui);
}
- /// A tab being dragged. Over a tab strip (or the middle of a group) it shows where the tab
- /// will land: an insertion mark between two tabs (a drop there reorders a group's own tabs
- /// too); near a group's edge, the half it will split off. On release it lands there (or
- /// floats with Cmd/Ctrl or outside every group).
- fn tab_drag(&mut self, ctx: &egui::Context, groups: &[Group], floats: &[Group], tab_rects: &[(String, Vec<(PanelKind, Rect)>)]) {
- let Some(p) = ctx.data(|d| d.get_temp::<PanelKind>(drag_id())) else { return };
- let t = self.tokens;
- let canceled =
- ctx.input(|input| input.key_pressed(egui::Key::Escape) || !input.focused || (!input.pointer.primary_down() && !input.pointer.primary_released()));
- if canceled || (!self.ui.dock.contains(p) && !self.ui.floating.iter().any(|group| group.panels.contains(&p))) {
- ctx.data_mut(|data| data.remove::<PanelKind>(drag_id()));
- return;
- }
- let Some(pos) = ctx.pointer_latest_pos() else { return };
- // The shared resolver receives groups in paint order; a floating group occludes the dock.
- let targets: Vec<_> = groups
- .iter()
- .map(|g| (g, false))
- .chain(floats.iter().map(|g| (g, true)))
- .filter_map(|(g, floating)| {
- Some(DropTarget {
- anchor: *g.panels.get(g.active)?,
- rect: g.rect,
- tab_strip: Some(Rect::from_min_max(g.rect.min, pos2(g.rect.max.x, g.content.min.y))),
- tabs: {
- let mut tabs = tab_rects.iter().find(|(path, _)| *path == g.path).map(|(_, tabs)| tabs.clone()).unwrap_or_default();
- for panel in &g.panels {
- if !tabs.iter().any(|(candidate, _)| candidate == panel) {
- tabs.push((*panel, Rect::NOTHING));
- }
- }
- tabs
- },
- allow_splits: !floating,
- accepts_tabs: true,
- })
- })
- .collect();
- let over_group = targets.iter().any(|target| target.rect.contains(pos));
- let float_drop = ctx.input(|i| i.modifiers.command);
- let plan = (!float_drop).then(|| resolve_drop(&p, pos, &targets)).flatten();
- let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("dock-drop")));
- if let Some(proposal) = &plan {
- let preview = proposal.preview.shrink(2.0);
- painter.rect_filled(preview, t.radius, t.focus.gamma_multiply(0.18));
- painter.rect_stroke(preview, t.radius, Stroke::new(2.0, t.focus), StrokeKind::Inside);
- if let Some(mark) = proposal.insertion {
- insertion_mark(&painter, mark.center().x, mark, t.focus);
- }
+ /// Keys and dropped files that reach a floating panel's own OS window go to the main
+ /// window's next frame ([`crate::EffectcraftApp::raw_input_hook`]), so its shortcuts and
+ /// file import handle them. Text is not forwarded, and nothing is while a text field in
+ /// the main window has the keyboard.
+ fn forward_window_input(&mut self, ctx: &egui::Context, events: Vec<egui::Event>, files: Vec<craft_ui::docking::WindowFiles<PanelKind>>) {
+ let typing = ctx.egui_wants_keyboard_input();
+ let events = events.into_iter().filter(|event| !typing && !matches!(event, egui::Event::Text(_) | egui::Event::Ime(_)));
+ self.forwarded.events.extend(events);
+ self.forwarded.files.extend(files.into_iter().flat_map(|window| window.dropped));
+ if !self.forwarded.events.is_empty() || !self.forwarded.files.is_empty() {
+ ctx.request_repaint();
}
- // Ghost of the dragged tab.
- let g = painter.layout_no_wrap(crate::i18n::command_label("window.panel", p.title()).to_string(), crate::theme::Tokens::ui(12.0), Color32::WHITE);
- let gr = Rect::from_min_size(pos + vec2(12.0, 10.0), g.size() + vec2(16.0, 8.0));
- painter.rect_filled(gr, 4.0, t.focus.gamma_multiply(0.85));
- painter.galley(gr.min + vec2(8.0, 4.0), g, Color32::WHITE);
- ctx.set_cursor_icon(egui::CursorIcon::Grabbing);
- ctx.request_repaint();
- if ctx.input(|i| i.pointer.primary_released()) {
- ctx.data_mut(|d| d.remove::<PanelKind>(drag_id()));
- let ok = match plan {
- Some(proposal) => self.dock_command(ctx, Action::Move { panel: p, anchor: proposal.anchor, placement: proposal.placement }).is_ok(),
- None if float_drop || !over_group => {
- let r = [pos.x - 40.0, pos.y - 12.0, 420.0, 320.0];
- self.dock_command(ctx, Action::Float { panel: p, rect: r }).is_ok()
- }
- None => false,
+ }
+
+ /// Automation ids for craft-ui's gesture sources: `panel.tab.<Panel>`, `panel.drag.<Panel>`
+ /// (the group's drag bar), `panel.border.<Panel>` (the top border above its tabs),
+ /// `panel.tabs.more.<Panel>`, `panel.header.<Panel>` (a stacked panel's open/close button),
+ /// `panel.float.<n>.move`, `.close`, `.resize` (bottom-right
+ /// corner) and `.resize.<Edge>`, `dock.gutter.<path>` (`a`/`b` per split level; a stack's gap
+ /// below entry `i` adds `s<i>`), `dock.corner.<outer>.<inner>` where two dividers meet, and
+ /// the same inside floating window `n` as `panel.float.<n>.gutter.…` and `.corner.…`.
+ fn register_dock_hits(&mut self, hits: &[(Hit<PanelKind>, Rect)]) {
+ let window = |panel: &PanelKind| self.ui.dock.layout.floating.iter().position(|window| window.contains(panel));
+ // Tabs are labelled as drawn: "Composition Intro", not "Composition".
+ let titles = self.tab_titles();
+ let title = |panel: &PanelKind| titles.iter().find(|(p, _)| p == panel).map_or_else(|| panel.title().to_string(), |(_, t)| t.clone());
+ let mut found = Vec::new();
+ for (hit, rect) in hits {
+ let entry = match hit {
+ Hit::Tab(panel) => (format!("panel.tab.{}", panel.id()), title(panel)),
+ Hit::DragBar(panel) => (format!("panel.drag.{}", panel.id()), "Move panel group".into()),
+ Hit::Border(panel) => (format!("panel.border.{}", panel.id()), "Move panel group".into()),
+ Hit::Overflow(panel) => (format!("panel.tabs.more.{}", panel.id()), "More tabs".into()),
+ Hit::StackToggle(panel) => (format!("panel.header.{}", panel.id()), title(panel)),
+ Hit::Title(panel) => match window(panel) {
+ Some(index) => (format!("panel.float.{index}.move"), "Move floating panel".into()),
+ None => continue,
+ },
+ Hit::Close(panel) => match window(panel) {
+ Some(index) => (format!("panel.float.{index}.close"), "Close floating panel".into()),
+ None => continue,
+ },
+ Hit::Resize(panel, edge) => match window(panel) {
+ Some(index) if *edge == ResizeEdge::BottomRight => (format!("panel.float.{index}.resize"), "Resize floating panel".into()),
+ Some(index) => (format!("panel.float.{index}.resize.{edge:?}"), "Resize floating panel".into()),
+ None => continue,
+ },
+ Hit::Divider(Divider::Split(path)) => (format!("dock.gutter.{}", path_id(path)), "gutter".into()),
+ Hit::Divider(Divider::Stack(panel)) => match dock::stack_gutter_id(&self.ui.dock.layout, *panel) {
+ Some(id) => (id, "gutter".into()),
+ None => continue,
+ },
+ Hit::Divider(Divider::Intersection(outer, inner)) => (format!("dock.corner.{}.{}", path_id(outer), path_id(inner)), "gutter corner".into()),
+ Hit::Divider(Divider::WindowSplit(panel, path)) => match window(panel) {
+ Some(index) => (format!("panel.float.{index}.gutter.{}", path_id(path)), "gutter".into()),
+ None => continue,
+ },
+ Hit::Divider(Divider::WindowIntersection(panel, outer, inner)) => match window(panel) {
+ Some(index) => (format!("panel.float.{index}.corner.{}.{}", path_id(outer), path_id(inner)), "gutter corner".into()),
+ None => continue,
+ },
+ _ => continue,
};
- if ok {
- self.ui.focused = p;
- self.show_panel(p);
+ found.push((entry, *rect, DockArea::hit_id(area_id(), hit)));
+ }
+ // The widget id lets keyboard focus on a divider or grip map to its element.
+ for ((id, label), rect, widget) in found {
+ self.auto.add(&id, rect, &label);
+ if let Some(element) = self.auto.elements.last_mut() {
+ element.response_id = Some(widget);
}
}
}
}
-/// The insertion mark of a tab drag: a bar between two tabs at `x`, with caps.
-fn insertion_mark(painter: &egui::Painter, x: f32, strip: Rect, col: Color32) {
- let (y0, y1) = (strip.min.y + 3.0, strip.max.y - 2.0);
- painter.line_segment([pos2(x, y0), pos2(x, y1)], Stroke::new(2.5, col));
- for (y, d) in [(y0, 1.0), (y1, -1.0)] {
- painter.add(egui::Shape::convex_polygon(vec![pos2(x - 4.5, y), pos2(x + 4.5, y), pos2(x, y + 5.0 * d)], col, Stroke::NONE));
- }
+/// A split path as `a`/`b` per level (first/second child).
+fn path_id(path: &[bool]) -> String {
+ path.iter().map(|second| if *second { 'b' } else { 'a' }).collect()
}
-/// The native window of the floating group whose window entry names `panel`.
-pub fn panel_window_id(panel: PanelKind) -> egui::ViewportId {
- egui::ViewportId::from_hash_of(("effectcraft-panel-window", panel.id()))
+/// After Effects' window is all frames: drops on all four window edges, Ctrl/Cmd-drag undocks,
+/// a release over no target floats, and a floating window's title bar only moves it.
+fn dock_style(ui: &egui::Ui, t: &Tokens) -> DockStyle {
+ let mut style = DockStyle::from_ui(ui);
+ style.side_edge_zones = true;
+ style.new_dock_zones = false;
+ style.maximize_item = true;
+ style.close_others_item = true;
+ style.command_press_floats = true;
+ style.float_on_empty_drop = true;
+ style.title_bar_docks = false;
+ style.float_hint = true;
+ style.wheel_selects_tabs = true;
+ style.middle_click_closes_tabs = true;
+ style.float_label = "Undock Panel".into();
+ style.float_group_label = "Undock Frame".into();
+ style.close_group_label = "Close Frame".into();
+ style.tab_height = t.tab_h;
+ style.gap = t.gap;
+ style.background = t.panel_bg;
+ style.tab_background = t.panel_bg;
+ style.active_background = t.panel_bg;
+ style.floating_background = t.panel_bg;
+ style.text = t.tab_text_active;
+ style.inactive_text = t.tab_text;
+ style.accent = t.focus;
+ style.font = Tokens::ui(12.0);
+ style
}
-/// Where a native panel window was told to open (kept for as long as it stays open).
-fn panel_window_spawn_id(panel: PanelKind) -> egui::Id {
- egui::Id::unique(("panel-window-spawn", panel.id()))
+/// Panels with a viewer lock: the Composition viewers and the Timeline keep their comp while
+/// locked.
+fn has_lock(panel: PanelKind) -> bool {
+ matches!(panel, PanelKind::Composition | PanelKind::Viewer(_) | PanelKind::Timeline)
}
-/// A new floating group's default rect near the centre of `screen`.
-pub fn default_float_rect(screen: Rect) -> [f32; 4] {
- let c = screen.center();
- [c.x - 210.0, c.y - 160.0, 420.0, 320.0]
+/// EffectCraft's side of the dock area for one frame.
+struct EffectContent<'a> {
+ app: &'a mut EffectcraftApp,
+ tokens: Tokens,
+ titles: Vec<(PanelKind, String)>,
+ swatches: Vec<(PanelKind, egui::Color32)>,
+ docs: Vec<DocTab>,
+ /// The width the comp tabs take in the Timeline's tab strip.
+ doc_width: f32,
+ doc_actions: Vec<DocAction>,
+ /// Viewer locks clicked.
+ locks: Vec<PanelKind>,
+ /// The ≡ button clicked: its panel and where its menu opens.
+ menu: Option<(PanelKind, egui::Pos2)>,
+ /// Where each panel body was drawn, in drawing order (floating windows last).
+ bodies: Vec<(PanelKind, Rect)>,
++ /// The floating panels' OS windows whose pass has begun this frame.
++ viewports: Vec<egui::ViewportId>,
}
-/// A corner is a two-axis resize control; focused arrows belong to it and Tab moves on.
-fn floating_resize_delta(ui: &mut egui::Ui, response: &egui::Response) -> egui::Vec2 {
- if response.drag_started() {
- response.request_focus();
+impl EffectContent<'_> {
+ fn header_width(&self, active: PanelKind, strip_width: f32) -> f32 {
+ let lock = if has_lock(active) { LOCK_W } else { 0.0 };
+ let docs = if active == PanelKind::Timeline && !self.docs.is_empty() { self.doc_width } else { 0.0 };
+ (docs + lock + MENU_W).min(strip_width * 2.0 / 3.0).max(MENU_W)
}
- let mut delta = if response.dragged() { response.drag_delta() } else { egui::Vec2::ZERO };
- if response.has_focus() {
- ui.memory_mut(|memory| {
- memory.set_focus_lock_filter(response.id, egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() })
- });
- ui.input_mut(|input| {
- for (key, amount) in [
- (egui::Key::ArrowLeft, vec2(-8.0, 0.0)),
- (egui::Key::ArrowRight, vec2(8.0, 0.0)),
- (egui::Key::ArrowUp, vec2(0.0, -8.0)),
- (egui::Key::ArrowDown, vec2(0.0, 8.0)),
- ] {
- if input.consume_key(egui::Modifiers::NONE, key) {
- delta += amount;
- }
- }
- });
+}
+
+impl DockContent<PanelKind> for EffectContent<'_> {
+ fn body(&mut self, ui: &mut egui::Ui, panel: &PanelKind) {
+ let t = self.tokens;
+ let rect = ui.max_rect();
+ self.bodies.push((*panel, rect));
++ // A floating panel's OS window is a pass of its own: its text IME descriptor is set up
++ // before its body draws and published after (the main window does both in `draw`).
++ let viewport = ui.ctx().viewport_id();
++ let native = viewport != egui::ViewportId::ROOT && !ui.ctx().embed_viewports();
++ if native && !self.viewports.contains(&viewport) {
++ self.viewports.push(viewport);
++ panels::viewer_text::begin_ui(ui.ctx());
++ }
+ self.app.panel_body(ui, *panel, rect);
++ if native {
++ panels::viewer_text::finish_ime(self.app, ui);
++ }
+ // The body fills its frame; allocating it lets a floated panel keep its full size.
+ ui.allocate_rect(rect, Sense::hover());
+ // Painted after the body so child backgrounds cannot hide the focus outline.
+ if self.app.ui.focused == *panel {
+ ui.painter().rect_stroke(rect, 0.0, Stroke::new(1.0, t.focus), StrokeKind::Inside);
+ }
+ }
+
+ fn logical_label(&self, panel: &PanelKind) -> String {
+ crate::i18n::command_label("window.panel", panel.title()).to_string()
+ }
+
+ /// The tab names what the panel shows ("Composition Intro"), after the label swatch of its
+ /// comp or layer. With comps open, the Timeline's own tab is just "Timeline"; its comp tabs
+ /// are in the group header.
+ fn label(&mut self, _ui: &egui::Ui, panel: &PanelKind, logical: &str, font: &egui::FontId, color: egui::Color32) -> egui::WidgetText {
+ let title = self.titles.iter().find(|(p, _)| p == panel).map_or(logical, |(_, s)| s.as_str());
+ let Some((_, swatch)) = self.swatches.iter().find(|(p, _)| p == panel) else { return title.into() };
+ let mut job = egui::text::LayoutJob::default();
+ job.append("■ ", 0.0, egui::TextFormat::simple(font.clone(), *swatch));
+ job.append(title, 0.0, egui::TextFormat::simple(font.clone(), color));
+ job.into()
+ }
+
+ fn group_header_width(&self, _panels: &[PanelKind], active: &PanelKind, _floating: bool, strip_width: f32) -> f32 {
+ self.header_width(*active, strip_width)
+ }
+
+ /// The Timeline's comp tabs, the viewer lock and the ≡ panel menu of the shown panel.
+ fn group_header(&mut self, ui: &mut egui::Ui, _panels: &[PanelKind], active: &PanelKind, _floating: bool) {
+ let t = self.tokens;
+ let header = ui.max_rect();
+ let menu = Rect::from_min_max(pos2((header.max.x - MENU_W).max(header.min.x), header.min.y), header.max);
+ let mut end = menu.min.x;
+ if has_lock(*active) {
+ let lock = Rect::from_center_size(pos2(end - LOCK_W / 2.0, header.center().y), vec2(14.0, 14.0));
+ end -= LOCK_W;
+ let locked = self.app.ui.locked_tabs.contains(&active.id());
+ if dock::lock_button(ui, lock, *active, locked, &t, &mut self.app.auto) {
+ self.locks.push(*active);
+ }
+ }
+ if *active == PanelKind::Timeline && !self.docs.is_empty() {
+ let strip = Rect::from_min_max(header.min, pos2(end.max(header.min.x), header.max.y));
+ self.doc_actions.extend(dock::doc_tabs(ui, strip, &self.docs, &t, &mut self.app.auto));
+ }
+ let rect = Rect::from_center_size(menu.center(), vec2(18.0, 18.0));
- let response = ui.interact(rect, egui::Id::new(("panel-menu-button", active.id())), Sense::click());
- response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, response.enabled(), "panel menu"));
++ let response = ui.interact(rect, egui::Id::unique(("panel-menu-button", active.id())), Sense::click());
++ response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, response.enabled(), "panel menu"));
+ self.app.auto.add_response(&format!("panel.menu.{}", active.id()), &response, "panel menu");
+ let color = if response.hovered() { t.tab_text_active } else { t.tab_text };
+ icons::paint(ui.painter(), Rect::from_center_size(rect.center(), vec2(16.0, 16.0)), Icon::Hamburger, color);
+ crate::widgets::focus_outline(ui, &response, &t);
+ if response.clicked() {
+ self.app.ui.focused = *active;
+ self.menu = Some((*active, rect.left_bottom()));
+ }
}
- if response.enabled() { delta } else { egui::Vec2::ZERO }
}
diff --cc crates/ui-egui/src/lib.rs
index beb78622f,7f8e02683..e6b39d731
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@@ -346,8 -503,6 +506,11 @@@ pub struct EffectcraftApp
/// Docked groups laid out last frame: (active panel, group rect) — `~` maximizes the one
/// under the pointer.
pub(crate) dock_rects: Vec<(PanelKind, egui::Rect)>,
++ /// The floating panels' OS windows that drew a panel last frame; one that is gone releases
++ /// its IME state.
++ pub(crate) native_viewports: Vec<egui::ViewportId>,
+ /// A floating panel shown by a command: its window comes to the front next frame.
+ pub(crate) pending_panel_raise: Option<PanelKind>,
/// Home screen: recent-project thumbnail textures by path (None = no thumbnail).
pub(crate) home_thumbs: std::collections::HashMap<String, Option<egui::TextureHandle>>,
/// The (project path, saved revision) whose thumbnail was stored last.
@@@ -363,6 -518,42 +526,34 @@@
/// 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>>,
-}
-
+ /// The comp frames a playback pass covers (`first..=last`).
+ #[derive(Clone, Copy, Debug)]
+ struct FrameWindow {
+ first: i64,
+ last: i64,
+ }
+
+ /// The inputs of one playback pass: the viewer series it renders, the preview plan and
+ /// position, and the frame range and clock settings its steps share. `queued` is a snapshot of
+ /// the in-flight render count that each step copies. Built once in `advance_playback`.
+ #[derive(Clone, Copy)]
+ struct PlaybackPass<'a> {
+ ctx: &'a egui::Context,
+ comp: &'a effectcraft_engine::project::Comp,
+ cid: ItemId,
+ scale: f64,
+ now: f64,
+ frame_rate: effectcraft_engine::time::FrameRate,
+ series: FrameKey,
+ plan: Option<effectcraft_engine::preview::PreviewPlan>,
+ window: FrameWindow,
+ cur: i64,
+ video: bool,
+ looping: bool,
+ ahead: i64,
+ queued: usize,
+ }
+
impl EffectcraftApp {
pub fn new(session: Session) -> Self {
let mut ui = UiState::default();
@@@ -385,13 -589,10 +589,11 @@@
control_rx: None,
deferred: vec![],
synthetic: vec![],
+ forwarded: ForwardedInput::default(),
input_waiters: vec![],
job_waiters: vec![],
- queued_screenshots: vec![],
pending_screenshots: vec![],
- next_token: 1,
- last_ui_time: 0.0,
+ shot_bytes: 0,
last_activity: (0.0, 0),
last_edit: (0.0, 0),
toast: None,
@@@ -422,7 -622,6 +624,8 @@@
applied_prefs: None,
recovery: None,
dock_rects: vec![],
++ native_viewports: vec![],
+ pending_panel_raise: None,
home_thumbs: Default::default(),
home_thumb_saved: None,
window_title: String::new(),
@@@ -1703,6 -2255,175 +2278,175 @@@
}
self.command_inbox = Some(rx);
}
+ // A close request (the window's button, Quit, `app.quit`) must be answered while hidden.
+ panels::unsaved::on_close_requested(self, ctx);
+ let title = panels::unsaved::window_title(self);
+ if title != self.window_title {
+ ctx.send_viewport_cmd(egui::ViewportCommand::Title(title.clone()));
+ self.window_title = title;
+ }
+ self.tick_autosave(ctx);
+ self.tick_workspace_autosave(ctx);
+ let now = self.now;
+ prefs_live::tick(self, ctx, now);
+ // Playback advances without a paint (its frames and the audio clock are background work).
+ // Idle prefetch keeps its old condition: it only runs once a viewer has drawn.
+ if (self.playback.playing || self.last_viewer_scale.is_some())
+ && let Some(cid) = self.session.active_comp_id()
+ {
+ let (scale, active) = (self.last_viewer_scale.unwrap_or(1.0), self.input_active);
+ self.advance_playback(ctx, scale, now, active, cid);
+ }
+ self.drain_control(ctx, now);
+ // Screenshot completion, deadlines and issuance are app-side work: the callback only
+ // stores pixels and wakes this viewport.
+ self.tick_screenshots(ctx);
+ // Time-based FPS readout over UI passes (a hidden logic-only tick is not a frame).
+ let dt = (now - self.last_time) as f32;
+ if dt > 0.0 && dt < 2.0 {
+ self.fps = self.fps * 0.9 + (1.0 / dt).min(480.0) * 0.1;
+ }
+ self.last_time = now;
+ // A hidden window paints when work needs a UI pass: queued input and waits, a settled
+ // screenshot, or playback into a child viewport.
+ let focused = self.focused;
- let child_viewports = !self.ui.floating.is_empty() || prefs_live::video_preview_active(self, focused);
++ let child_viewports = !self.ui.dock.layout.floating.is_empty() || prefs_live::video_preview_active(self, focused);
+ let paint = self.want_paint
+ || !self.synthetic.is_empty()
+ || !self.input_waiters.is_empty()
+ || self.pending_screenshots.iter().any(|s| s.slot.is_none())
+ || (self.playback.playing && child_viewports);
+ if paint {
+ self.request_hidden_paint(ctx);
+ }
+ }
+
+ /// Ask the host for a UI pass even when the window is minimized or occluded.
+ ///
+ /// Native eframe honours `RequestPaintWhileHidden`; the shared web backend does not carry it
+ /// yet (a browser does not paint a hidden tab), so the web build only requests a normal
+ /// repaint and hidden web screenshots/input remain unqualified.
+ fn request_hidden_paint(&mut self, ctx: &egui::Context) {
+ self.want_paint = false;
+ #[cfg(not(target_arch = "wasm32"))]
+ ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaintWhileHidden);
+ ctx.request_repaint();
+ }
+
+ /// Install the theme and fonts for the current language. Fonts need a real pass: the pass
+ /// that installs them draws nothing, and the next pass draws with them (the two-pass warm-up
+ /// the app has always had). Never call this from a logic-only tick.
+ fn ui_setup(&mut self, ctx: &egui::Context) {
+ panels::viewer_text::install_hooks(ctx);
+ let language = crate::i18n::language(self);
+ crate::i18n::set_current(language);
+ if (!self.styled || self.styled_language != language) && self.synthetic_in_flight {
+ // The install needs a pass that draws nothing, but this pass has already applied a
+ // synthetic batch: defer the theme/font install by one pass instead of dropping the
+ // input (feeds are only put into a pass that can draw).
+ ctx.request_repaint();
+ return;
+ }
+ if !self.styled || self.styled_language != language {
+ theme::install(ctx, &self.tokens, language);
+ self.styled_language = language;
+ if !self.styled {
+ fit_window(ctx);
+ self.styled = true;
+ }
+ self.fonts_ready = false;
+ ctx.request_repaint();
+ } else if !self.fonts_ready {
+ // The pass after the install draws: egui has the new font definitions by now.
+ self.fonts_ready = true;
+ ctx.request_repaint();
+ }
+ }
+
+ /// One UI pass: setup, input-driven shortcuts, layout and painting. Called from
+ /// `eframe::App::ui` and by tests with the root `Ui`.
+ pub fn draw(&mut self, ui: &mut egui::Ui, frame: &eframe::Frame) {
+ panels::viewer_text::begin_ui(ui.ctx());
+ self.draw_inner(ui, frame);
+ // All exits, including fonts/device loss, observe this pass's real custom availability.
+ panels::viewer_text::finish_ime(self, ui);
+ }
+
+ /// Context creators install these hooks before the first full pass.
+ pub fn install_ime_reset_hooks(ctx: &egui::Context) {
+ panels::viewer_text::install_hooks(ctx);
+ }
+
+ /// Host wrappers call this after their last logic mutation, without replaying UI events.
+ pub fn finish_ime_logic(&self, ctx: &egui::Context) {
+ panels::viewer_text::finish_logic(self, ctx);
+ }
+
+ fn draw_inner(&mut self, ui: &mut egui::Ui, frame: &eframe::Frame) {
+ let ctx = ui.ctx().clone();
+ if self.gpu_failure_applied == Some(true) {
+ self.close_after_device_loss(&ctx);
+ return;
+ }
+ self.ui_setup(&ctx);
+ if !self.fonts_ready {
+ // A pass that installs fonts draws nothing. No synthetic batch is in flight here (the
+ // hook feeds input only to a ready app), and events egui already applied are never
+ // fed again: that would double the pointer/key state of one click.
+ ctx.request_repaint();
+ return;
+ }
+ self.frame(ui);
+ #[cfg(not(target_arch = "wasm32"))]
+ pointer_wrap::finish_native(&ctx, frame);
+ // wasm32: no frame threads; render queued frames now, between UI frames.
+ if cfg!(target_arch = "wasm32") && self.frames.pump(std::time::Duration::from_millis(if self.playback.playing { 24 } else { 40 })) {
+ ctx.request_repaint();
+ }
+ // Input belongs to this known UI phase: record it for the next tick.
+ let active = ctx.input(|i| !i.events.is_empty() || i.pointer.any_down() || i.pointer.is_moving());
+ self.input_active = active;
+ self.last_pointer_down = ctx.input(|i| i.pointer.any_down());
+ // Geometry of a completed pass (a discarded pass is laid out again; only the final one
+ // describes the surface the next capture will see). Window position is irrelevant.
+ if !ctx.will_discard() {
+ let rect = ctx.content_rect();
+ let ppp = ctx.pixels_per_point();
+ let changed = self.draw_geom.is_none_or(|g| g.rect.size() != rect.size() || g.ppp != ppp);
+ if changed {
+ self.geometry_epoch = self.geometry_epoch.wrapping_add(1);
+ }
+ self.draw_geom = Some(DrawGeometry { rect, ppp, epoch: self.geometry_epoch });
+ self.ui_pass_seq = self.ui_pass_seq.saturating_add(1);
+ }
+ // A batch is acknowledged once a UI pass applied it, even if layout was later discarded.
+ self.mark_synthetic_applied();
+ // `AfterInput` replies wait for the final (non-discarded) pass that applied the last
+ // synthetic event: a hidden request is answered only after its forced pass, and a pass
+ // egui throws away cannot produce an early success reply.
+ if !ctx.will_discard() && self.synthetic.is_empty() {
+ for w in self.input_waiters.drain(..) {
+ let _ = w.send(json!({"ok": true, "result": null}));
+ }
+ } else if !self.input_waiters.is_empty() {
+ self.want_paint = true;
+ ctx.request_repaint();
+ }
+ if self.frames.inflight() > 0 {
+ ctx.request_repaint_after(std::time::Duration::from_millis(30));
+ }
+ }
+
+ /// The panels, menus, dialogs and overlays of one pass.
+ fn frame(&mut self, ui: &mut egui::Ui) {
+ let ctx = ui.ctx().clone();
+ // Only a viewer that draws in *this* pass records a scale: a closed viewer, the Home
+ // screen or another comp must stop idle prefetch at a stale scale.
+ self.last_viewer_scale = None;
+ self.apply_prefs(&ctx);
+ // Video Preview is a second viewport: only a real pass can update it.
+ prefs_live::frame(self, &ctx);
+ self.auto.begin_frame();
let tab_had_widget_focus = ctx.egui_wants_keyboard_input();
menus::handle_shortcuts(self, &ctx);
if !ctx.input(|i| i.pointer.primary_down()) {
@@@ -1948,10 -2620,14 +2699,16 @@@ impl eframe::App for EffectcraftApp
}
fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
+ raw_input.events.append(&mut self.forwarded.events);
+ raw_input.dropped_files.append(&mut self.forwarded.files);
- let injected = !self.synthetic.is_empty();
- self.feed_synthetic(raw_input);
+ let injected = self.synthetic_in_flight || !self.synthetic.is_empty();
+ // Only a pass that can draw may receive synthetic input: `Context::run_ui` applies
+ // everything the hook feeds to its input state, so a pass that cannot draw (fonts still
+ // installing) would consume a batch it could not put back — putting it back would apply
+ // the click/key state twice. The queue waits here for the first pass that draws.
+ if self.fonts_ready {
+ self.feed_synthetic(raw_input);
+ }
if pointer_wrap::prepare_input(ctx, raw_input, injected) {
self.session.history.merge_key = None;
}
diff --cc crates/ui-egui/src/panels/dialogs.rs
index d224d1a0f,99496a218..fd7d43f26
--- a/crates/ui-egui/src/panels/dialogs.rs
+++ b/crates/ui-egui/src/panels/dialogs.rs
@@@ -170,18 -170,6 +170,18 @@@ pub(crate) fn modal_space(ctx: &egui::C
(ctx.content_rect().size() - vec2(48.0, 48.0)).max(vec2(120.0, 80.0))
}
+fn modal_pass_id() -> egui::Id {
- egui::Id::new("effectcraft-modal-pass")
++ egui::Id::unique("effectcraft-modal-pass")
+}
+
+/// Whether a modal dialog showed in this pass or the one before: egui's `Modal` blocks input
+/// only in its own window, so floating panels in OS windows of their own are blocked by the
+/// dock area while this holds. Dialogs draw after the dock, so the previous pass counts.
+pub(crate) fn modal_open(ctx: &egui::Context) -> bool {
+ let shown = ctx.data(|d| d.get_temp::<u64>(modal_pass_id()));
+ shown.is_some_and(|pass| pass.saturating_add(1) >= ctx.cumulative_pass_nr_for(egui::ViewportId::ROOT))
+}
+
pub(crate) fn modal(ctx: &egui::Context, title: &str, size: egui::Vec2, t: &Tokens, body: impl FnOnce(&mut egui::Ui)) {
modal_with_scroll(ctx, title, size, t, false, body);
}
@@@ -202,10 -190,8 +202,10 @@@ fn modal_with_scroll(ctx: &egui::Contex
/// only its content: `body` gets the height left under the title, with `size` kept within the
/// window.
pub(crate) fn modal_fit(ctx: &egui::Context, title: &str, size: egui::Vec2, t: &Tokens, body: impl FnOnce(&mut egui::Ui, f32)) {
+ let pass = ctx.cumulative_pass_nr_for(egui::ViewportId::ROOT);
+ ctx.data_mut(|d| d.insert_temp(modal_pass_id(), pass));
let size = size.min(modal_space(ctx));
- let id = egui::Id::new(("modal", title));
+ let id = egui::Id::unique(("modal", title));
// Dragging the title row moves the dialog off what it edits. The offset is kept within the
// window, so dragging back never has to undo a part the dialog could not follow.
let offset_id = id.with("offset");
diff --cc crates/ui-egui/src/panels/mod.rs
index 9ee05e619,5327ab170..9a8fd2a54
--- a/crates/ui-egui/src/panels/mod.rs
+++ b/crates/ui-egui/src/panels/mod.rs
@@@ -218,8 -218,12 +218,8 @@@ pub fn show(app: &mut EffectcraftApp, u
/// The ≡ panel menu (opened from a tab).
pub fn panel_menu_popup(app: &mut EffectcraftApp, ui: &mut egui::Ui) {
- let id = egui::Id::new("panel-menu");
+ let id = egui::Id::unique("panel-menu");
let Some((panel, pos)) = ui.ctx().data(|d| d.get_temp::<(PanelKind, egui::Pos2)>(id)) else { return };
- // The menu opens in the window that shows the panel (a panel can have its own window).
- if app.panel_viewport(ui.ctx(), panel) != ui.ctx().viewport_id() {
- return;
- }
let mut close = false;
let area = egui::Area::new(id.with("area")).order(egui::Order::Foreground).fixed_pos(pos).show(ui.ctx(), |ui| {
egui::Frame::popup(ui.style()).show(ui, |ui| {
diff --cc xtask/src/pdf_deps.rs
index b64f60029,d0efd830c..00b913bc8
--- a/xtask/src/pdf_deps.rs
+++ b/xtask/src/pdf_deps.rs
@@@ -5,7 -5,7 +5,7 @@@ use std::process::Command
use serde_json::Value;
- const REV: &str = "5bbe9f6254de3bb9f9707ae0740ab0db8170afd5";
-const REV: &str = "9f75d3dc19b4b514c4f3d4847ed1ec1b0e86b4ef";
++const REV: &str = "a0916808f7d78bed8c7b90cdf937176015454a7f";
const PACKAGES: &[(&str, &str)] = &[("craft-pdf", "0.1.0"), ("hayro-syntax", "0.7.2"), ("hayro-jbig2", "0.3.0")];
pub fn run(root: &Path) -> Result<(), String> {