diff --git a/crates/engine/src/cmds_actions.rs b/crates/engine/src/cmds_actions.rs index f8f1db60..ce9540f1 100644 --- a/crates/engine/src/cmds_actions.rs +++ b/crates/engine/src/cmds_actions.rs @@ -85,19 +85,20 @@ fn parse_actions(p: &Value) -> Result> { Ok(list) } -/// The symbol instance `element` (or the selected one) on the active layer's keyframe at the -/// playhead, for editing. +/// The symbol instance `element` on the active layer's keyframe at the playhead (or the selected +/// one, on its layer), for editing. fn instance_mut<'a>(s: &'a mut Session, p: &Value) -> Result<&'a mut Element> { - let id = match opt_u64(p, "element")? { - Some(id) => ElementId(id), - None => match s.selection.as_slice() { - [one] => *one, - [] => return Err(EngineError::State("select a movie clip or button instance, or pass 'element'".into())), + let (layer, id) = match opt_u64(p, "element")? { + // A selected element is looked for on its own layer. + Some(id) => (s.selection.iter().find(|(_, e)| e.0 == id).map_or(s.layer, |(l, _)| l), ElementId(id)), + None => match (s.selection.first(), s.selection.len()) { + (Some(one), 1) => one, + (None, _) => return Err(EngineError::State("select a movie clip or button instance, or pass 'element'".into())), _ => return Err(EngineError::State("select one instance".into())), }, }; let frame = s.frame; - let layer = s.layer_mut(None)?; + let layer = s.layer_mut(Some(layer))?; let i = layer.keyframe_index_at(frame).ok_or_else(|| EngineError::State(format!("frame {} is empty on this layer", frame + 1)))?; let k = layer.keyframe_mut(i).ok_or_else(|| EngineError::State("keyframe vanished".into()))?; let e = k.elements.iter_mut().find(|e| e.id == id).ok_or_else(|| EngineError::State(format!("no element {} on the active layer at frame {}", id.0, frame + 1)))?; diff --git a/crates/engine/src/cmds_brush.rs b/crates/engine/src/cmds_brush.rs index 8afb5555..df6e1423 100644 --- a/crates/engine/src/cmds_brush.rs +++ b/crates/engine/src/cmds_brush.rs @@ -170,10 +170,11 @@ fn draw_brush(s: &mut Session, p: &Value) -> Result { PaintMode::Behind => kf.elements.insert(0, Arc::new(el)), PaintMode::Normal | PaintMode::Fills => kf.elements.push(Arc::new(el)), } - s.selection = vec![id]; + s.select_only([id]); return Ok(json!({"element": id.0, "elements": [id.0], "mode": mode.key(), "merged": false})); } - s.selection = merge::merge_in_order(s, vec![el], mode.order())?; - let ids: Vec = s.selection.iter().map(|e| e.0).collect(); + let merged = merge::merge_in_order(s, vec![el], mode.order())?; + s.select_only(merged); + let ids: Vec = s.selection.id_list(); Ok(json!({"element": ids.first(), "elements": ids, "mode": mode.key(), "merged": true})) } diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index 913cf7ce..79a902f1 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -1,7 +1,7 @@ //! Drawing, selection, element and symbol commands. use crate::params::*; -use crate::{CommandSpec, EngineError, Result, Session}; +use crate::{CommandSpec, EngineError, Result, Selection, Session}; use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, Layer, LayerId, LoopMode, Paint, Shape, Stroke, Symbol, SymbolId, SymbolKind, Timeline}; use anicraft_geom::{Affine, Decomposed, Path, Vec2}; use serde_json::{Value, json}; @@ -21,26 +21,26 @@ pub fn specs() -> Vec { s.selection.clear(); Ok(json!({"selected": 0})) }), - c("edit.delete", "Clear", "Edit", Some("Delete"), "{}", true, delete), - c("edit.duplicate", "Duplicate", "Edit", Some("Ctrl+D"), "{dx?, dy?}", true, duplicate), - c("element.select", "Select Elements", "", None, "{ids: [..], add?: bool}", false, select), - c("element.pick", "Select at Point", "", None, "{x, y, add?: bool}", false, pick), - c("element.translate", "Move", "", None, "{dx, dy, snap?, from?: [x, y]} moves the selection; with `snap` (a distance) one of its corners or ends (the nearest to `from`) then snaps onto a point, line or fill edge of the rest within that distance", true, translate), - c("element.set_transform", "Transform", "", None, "{x?, y?, sx?, sy?, rotation? (degrees)}", true, set_transform), - c("element.set_fill", "Fill Colour", "", None, "{color: \"#rrggbb\" | null}", true, set_fill), - c("element.set_stroke", "Stroke", "", None, "{color?: \"#rrggbb\" | null, width?, profile?: uniform|taper_both|taper_start|taper_end|bulge|pinch | [[t, left, right], ..]}", true, set_stroke), - c("element.set_alpha", "Alpha", "", None, "{alpha: 0..1}", true, set_alpha), - c("element.set_blend", "Blending", "", None, "{mode: normal|layer|darken|multiply|lighten|screen|overlay|hardlight|add|subtract|difference|invert|alpha|erase} on the selected movie clip and button instances", true, set_blend), - c("element.set_filters", "Filters", "", None, "{filters: [{type: blur|drop_shadow|glow|bevel|gradient_glow|gradient_bevel|adjust_color, …values}]} replaces the selected movie clip and button instances' filters (in order; [] removes them). Bevel: shadow_color, highlight_color, side: inner|outer|full, knockout; gradient filters: stops: [{offset 0..1, color \"#rrggbbaa\"}] (Gradient Glow's start and Gradient Bevel's middle stay transparent)", true, set_filters), - c("element.set_loop", "Looping", "", None, "{loop?: loop|play_once|single_frame, first_frame?}", true, set_loop), + c("edit.delete", "Clear", "Edit", Some("Delete"), "{} (on every layer with selected items)", true, delete_selection), + c("edit.duplicate", "Duplicate", "Edit", Some("Ctrl+D"), "{dx?, dy?} (each copy on its original's layer)", true, |s, p| s.each_layer(true, |s| duplicate(s, p))), + c("element.select", "Select Elements", "", None, "{ids: [..], add?: bool, layer?} selects elements on any visible, unlocked layer at the playhead (ids are unique; `layer` looks only there); the active layer becomes the first one's unless it has some of them", false, select), + c("element.pick", "Select at Point", "", None, "{x, y, add?: bool} the topmost element there on a visible, unlocked layer; `add` (Shift) adds it to the selection, or lets go of it, on any layer", false, pick), + c("element.translate", "Move", "", None, "{dx, dy, snap?, from?: [x, y]} moves the selection, on every layer; with `snap` (a distance) one of its corners or ends (the nearest to `from`) then snaps onto a point, line or fill edge of the rest within that distance", true, translate), + c("element.set_transform", "Transform", "", None, "{x?, y?, sx?, sy?, rotation? (degrees)}", true, |s, p| s.each_layer(true, |s| set_transform(s, p))), + c("element.set_fill", "Fill Colour", "", None, "{color: \"#rrggbb\" | null}", true, |s, p| s.each_layer(false, |s| set_fill(s, p))), + c("element.set_stroke", "Stroke", "", None, "{color?: \"#rrggbb\" | null, width?, profile?: uniform|taper_both|taper_start|taper_end|bulge|pinch | [[t, left, right], ..]}", true, |s, p| s.each_layer(false, |s| set_stroke(s, p))), + c("element.set_alpha", "Alpha", "", None, "{alpha: 0..1}", true, |s, p| s.each_layer(true, |s| set_alpha(s, p))), + c("element.set_blend", "Blending", "", None, "{mode: normal|layer|darken|multiply|lighten|screen|overlay|hardlight|add|subtract|difference|invert|alpha|erase} on the selected movie clip and button instances", true, |s, p| s.each_layer(false, |s| set_blend(s, p))), + c("element.set_filters", "Filters", "", None, "{filters: [{type: blur|drop_shadow|glow|bevel|gradient_glow|gradient_bevel|adjust_color, …values}]} replaces the selected movie clip and button instances' filters (in order; [] removes them). Bevel: shadow_color, highlight_color, side: inner|outer|full, knockout; gradient filters: stops: [{offset 0..1, color \"#rrggbbaa\"}] (Gradient Glow's start and Gradient Bevel's middle stay transparent)", true, |s, p| s.each_layer(false, |s| set_filters(s, p))), + c("element.set_loop", "Looping", "", None, "{loop?: loop|play_once|single_frame, first_frame?}", true, |s, p| s.each_layer(false, |s| set_loop(s, p))), c("symbol.set_kind", "Symbol Type", "", None, "{kind: graphic|movie_clip|button, symbol?: id (default: the selected instance's)}", true, set_symbol_kind), - c("element.rename", "Instance Name", "", None, "{name}", true, rename), - c("arrange.bring_to_front", "Bring to Front", "Modify/Arrange", Some("Ctrl+Shift+Up"), "{}", true, |s, _| arrange(s, true)), - c("arrange.bring_forward", "Bring Forward", "Modify/Arrange", Some("Ctrl+Up"), "{}", true, |s, _| arrange_step(s, true)), - c("arrange.send_backward", "Send Backward", "Modify/Arrange", Some("Ctrl+Down"), "{}", true, |s, _| arrange_step(s, false)), - c("arrange.send_to_back", "Send to Back", "Modify/Arrange", Some("Ctrl+Shift+Down"), "{}", true, |s, _| arrange(s, false)), - c("modify.convert_to_symbol", "Convert to Symbol…", "Modify", Some("F8"), "{name?}", true, convert_to_symbol), - c("modify.break_apart", "Break Apart", "Modify", Some("Ctrl+B"), "{}", true, break_apart), + c("element.rename", "Instance Name", "", None, "{name}", true, |s, p| s.each_layer(true, |s| rename(s, p))), + c("arrange.bring_to_front", "Bring to Front", "Modify/Arrange", Some("Ctrl+Shift+Up"), "{} (within each layer)", true, |s, _| s.each_layer(true, |s| arrange(s, true))), + c("arrange.bring_forward", "Bring Forward", "Modify/Arrange", Some("Ctrl+Up"), "{} (within each layer)", true, |s, _| s.each_layer(true, |s| arrange_step(s, true))), + c("arrange.send_backward", "Send Backward", "Modify/Arrange", Some("Ctrl+Down"), "{} (within each layer)", true, |s, _| s.each_layer(true, |s| arrange_step(s, false))), + c("arrange.send_to_back", "Send to Back", "Modify/Arrange", Some("Ctrl+Shift+Down"), "{} (within each layer)", true, |s, _| s.each_layer(true, |s| arrange(s, false))), + c("modify.convert_to_symbol", "Convert to Symbol…", "Modify", Some("F8"), "{name?} (a selection on several layers becomes one symbol with those layers inside; the instance lands on the topmost)", true, convert_to_symbol), + c("modify.break_apart", "Break Apart", "Modify", Some("Ctrl+B"), "{}", true, |s, p| s.each_layer(false, |s| break_apart(s, p))), c("library.place", "Place Instance", "", None, "{symbol | bitmap, x?, y?}", true, place), ] } @@ -110,8 +110,9 @@ pub(crate) fn add_shape(s: &mut Session, name: &str, local: Path, origin: Vec2, kind: ElementKind::Shape(Shape { path: Arc::new(local), fill, stroke, fill_rule: Default::default(), merge }), }; if merge { - s.selection = crate::merge::merge_in(s, vec![el])?; - let ids: Vec = s.selection.iter().map(|e| e.0).collect(); + let merged = crate::merge::merge_in(s, vec![el])?; + s.select_only(merged); + let ids: Vec = s.selection.id_list(); return Ok(json!({"element": ids.first(), "elements": ids, "kind": name, "merged": true})); } let kf = s.editable_keyframe()?; @@ -119,7 +120,7 @@ pub(crate) fn add_shape(s: &mut Session, name: &str, local: Path, origin: Vec2, return Err(EngineError::State("too many elements on this keyframe".into())); } kf.elements.push(Arc::new(el)); - s.selection = vec![id]; + s.select_only([id]); Ok(json!({"element": id.0, "kind": name})) } @@ -178,27 +179,63 @@ fn object_drawing(s: &mut Session, p: &Value) -> Result { // ----- selection -------------------------------------------------------------------------- +/// Everything on every visible, unlocked layer at the playhead, as Animate's Select All. fn select_all(s: &mut Session, _: &Value) -> Result { - s.selection = s.visible_elements().iter().map(|e| e.id).collect(); + let layers: Vec = s.doc.timeline(s.scene).layers.iter().map(|l| l.id).collect(); + let mut sel = Selection::default(); + for l in layers.into_iter().filter(|l| s.gathers(*l)) { + sel.extend_on(l, s.elements_on(l).iter().map(|e| e.id)); + } + s.selection = sel; Ok(json!({"selected": s.selection.len()})) } +/// Most ids `element.select` takes. +const MAX_SELECT: usize = 100_000; + fn select(s: &mut Session, p: &Value) -> Result { let ids = opt_u64_list(p, "ids")?.ok_or_else(|| EngineError::Param("param 'ids' is required".into()))?; + if ids.len() > MAX_SELECT { + return Err(EngineError::Param(format!("param 'ids' has more than {MAX_SELECT} ids"))); + } let add = opt_bool(p, "add")?.unwrap_or(false); - let present: Vec = s.visible_elements().iter().map(|e| e.id).collect(); + // Where each element is at the playhead: on `layer`, else the active layer first, then the + // others top to bottom. + let order: Vec = match opt_u64(p, "layer")?.map(LayerId) { + Some(l) if s.doc.timeline(s.scene).layer(l).is_none() => return Err(EngineError::State(format!("no layer with id {}", l.0))), + Some(l) => vec![l], + None => std::iter::once(s.layer).chain(s.doc.timeline(s.scene).layers.iter().map(|l| l.id).filter(|l| *l != s.layer)).collect(), + }; + let mut at: std::collections::HashMap = std::collections::HashMap::new(); + for l in order { + for e in s.elements_on(l) { + at.entry(e.id).or_insert(l); + } + } + let mut picked: Vec<(LayerId, ElementId)> = Vec::with_capacity(ids.len()); + for id in ids.into_iter().map(ElementId) { + let Some(&l) = at.get(&id) else { + return Err(EngineError::State(format!("element {} is not on the active layer, or any layer, at this frame", id.0))); + }; + if !s.selectable(l) { + let name = s.doc.timeline(s.scene).layer(l).map(|x| x.name.clone()).unwrap_or_default(); + return Err(EngineError::State(format!("element {} is on layer '{name}', which is locked or hidden", id.0))); + } + picked.push((l, id)); + } if !add { s.selection.clear(); } - for id in ids.into_iter().map(ElementId) { - if !present.contains(&id) { - return Err(EngineError::State(format!("element {} is not on the active layer at this frame", id.0))); - } - if !s.selection.contains(&id) { - s.selection.push(id); - } + for &(l, id) in &picked { + s.selection.insert(l, id); } - Ok(json!({"selected": s.selection.iter().map(|e| e.0).collect::>()})) + // As a click does: the active layer is where the artwork is. + if let Some(&(l, _)) = picked.first() + && !picked.iter().any(|(x, _)| *x == s.layer) + { + s.layer = l; + } + Ok(json!({"selected": s.selection.id_list()})) } fn pick(s: &mut Session, p: &Value) -> Result { @@ -206,19 +243,13 @@ fn pick(s: &mut Session, p: &Value) -> Result { let add = opt_bool(p, "add")?.unwrap_or(false); match s.hit_test(pt, 2.0) { Some((layer, el)) => { - if layer != s.layer { - s.layer = layer; - s.selection.clear(); - } + // Shift adds it to (or takes it from) the selection, whichever layers that is on. if add { - if let Some(i) = s.selection.iter().position(|e| *e == el) { - s.selection.remove(i); - } else { - s.selection.push(el); - } - } else if !s.selection.contains(&el) { - s.selection = vec![el]; + s.selection.toggle(layer, el); + } else if !s.selection.contains(layer, el) { + s.selection = Selection::only(layer, [el]); } + s.layer = layer; Ok(json!({"layer": layer.0, "element": el.0})) } None => { @@ -242,25 +273,32 @@ fn translate(s: &mut Session, p: &Value) -> Result { Some(xy.filter(|q| q.is_finite()).ok_or_else(|| EngineError::Param("param 'from' must be [x, y]".into()))?) } }; - let els = s.selected_elements_mut()?; - let n = els.len(); - for e in els { - e.transform = Affine::translate(dx, dy).mul(&e.transform); - } + let n = move_by(s, Vec2::new(dx, dy))?; // Snapping while dragging (ADR 0041): a little more, onto what is near. let mut snapped = Value::Null; if snap > 0.0 && let Some((extra, at, kind)) = crate::cmds_raw::snap_selection(s, snap, from) { - for e in s.selected_elements_mut()? { - e.transform = Affine::translate(extra.x, extra.y).mul(&e.transform); - } + move_by(s, extra)?; (dx, dy) = (dx + extra.x, dy + extra.y); snapped = json!({"x": at.x, "y": at.y, "to": kind.key()}); } Ok(json!({"moved": n, "dx": dx, "dy": dy, "snapped": snapped})) } +/// Moves the selection by `d` on every layer it is on; how many elements moved. +fn move_by(s: &mut Session, d: Vec2) -> Result { + let v = s.each_layer(true, |s| { + let els = s.selected_elements_mut()?; + let n = els.len(); + for e in els { + e.transform = Affine::translate(d.x, d.y).mul(&e.transform); + } + Ok(json!({"moved": n})) + })?; + Ok(v["moved"].as_u64().unwrap_or(0)) +} + fn set_transform(s: &mut Session, p: &Value) -> Result { let x = opt_f32(p, "x")?; let y = opt_f32(p, "y")?; @@ -492,8 +530,8 @@ fn set_symbol_kind(s: &mut Session, p: &Value) -> Result { Some(id) => SymbolId(id), None => { // The symbol of the selected instance. - let sel = s.selection.first().copied().ok_or_else(|| EngineError::State("select a symbol instance, or pass 'symbol'".into()))?; - s.visible_elements() + let (layer, sel) = s.selection.first().ok_or_else(|| EngineError::State("select a symbol instance, or pass 'symbol'".into()))?; + s.elements_on(layer) .iter() .find(|e| e.id == sel) .and_then(|e| match e.kind { @@ -516,8 +554,13 @@ fn rename(s: &mut Session, p: &Value) -> Result { Ok(json!({"name": name})) } -pub(crate) fn delete(s: &mut Session, _: &Value) -> Result { - let sel = s.selection.clone(); +/// Clear: the selection goes, on every layer it is on. +pub(crate) fn delete_selection(s: &mut Session, p: &Value) -> Result { + s.each_layer(true, |s| delete(s, p)) +} + +fn delete(s: &mut Session, _: &Value) -> Result { + let sel = s.selection.on(s.layer); if sel.is_empty() { return Err(EngineError::State("nothing is selected".into())); } @@ -532,7 +575,7 @@ pub(crate) fn delete(s: &mut Session, _: &Value) -> Result { fn duplicate(s: &mut Session, p: &Value) -> Result { let dx = opt_f32(p, "dx")?.unwrap_or(10.0); let dy = opt_f32(p, "dy")?.unwrap_or(10.0); - let sel = s.selection.clone(); + let sel = s.selection.on(s.layer); if sel.is_empty() { return Err(EngineError::State("nothing is selected".into())); } @@ -546,12 +589,12 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { out.push(Arc::new(e)); } s.editable_keyframe()?.elements.extend(out); - s.selection = new_ids.clone(); + s.select_only(new_ids.iter().copied()); Ok(json!({"created": new_ids.iter().map(|e| e.0).collect::>()})) } fn arrange(s: &mut Session, front: bool) -> Result { - let sel = s.selection.clone(); + let sel = s.selection.on(s.layer); if sel.is_empty() { return Err(EngineError::State("nothing is selected".into())); } @@ -564,7 +607,7 @@ fn arrange(s: &mut Session, front: bool) -> Result { /// Bring Forward / Send Backward: each selected element swaps with the unselected neighbour /// above (or below) it; a selected block moves as one, keeping its order. fn arrange_step(s: &mut Session, forward: bool) -> Result { - let sel = s.selection.clone(); + let sel = s.selection.on(s.layer); if sel.is_empty() { return Err(EngineError::State("nothing is selected".into())); } @@ -590,31 +633,22 @@ fn arrange_step(s: &mut Session, forward: bool) -> Result { // ----- symbols ---------------------------------------------------------------------------- +/// Convert to Symbol. The registration point is the centre of the selection's bounds. A +/// selection on several layers becomes one symbol with those layers inside it (named and +/// stacked as they are), and its instance lands on the topmost of them, where its first +/// selected element was; the other layers lose what was selected (ADR 0044). pub(crate) fn convert_to_symbol(s: &mut Session, p: &Value) -> Result { - let sel = s.selection.clone(); - if sel.is_empty() { + let layers = s.selected_layers(); + let Some(&top) = layers.first() else { return Err(EngineError::State("select something to convert".into())); - } + }; let n = s.doc.library.len() + 1; let name: String = opt_str(p, "name")?.map(|x| x.chars().take(128).collect()).unwrap_or_else(|| format!("Symbol {n}")); let bounds = s.selection_bounds(); let center = if bounds.is_empty() { Vec2::ZERO } else { bounds.center() }; let sym_id = SymbolId(s.doc.alloc_id()); - let layer_id = LayerId(s.doc.alloc_id()); + let first_layer = LayerId(s.doc.alloc_id()); let inst_id = ElementId(s.doc.alloc_id()); - let kf = s.editable_keyframe()?; - let first_pos = kf.elements.iter().position(|e| sel.contains(&e.id)).unwrap_or(kf.elements.len()); - let (picked, rest): (Vec>, Vec>) = kf.elements.drain(..).partition(|e| sel.contains(&e.id)); - // Children are stored relative to the registration point (the selection centre). - let to_local = Affine::translate(-center.x, -center.y); - let children: Vec> = picked - .into_iter() - .map(|e| { - let mut e = Arc::unwrap_or_clone(e); - e.transform = to_local.mul(&e.transform); - Arc::new(e) - }) - .collect(); let instance = Element { id: inst_id, name: String::new(), @@ -622,20 +656,46 @@ pub(crate) fn convert_to_symbol(s: &mut Session, p: &Value) -> Result { color: ColorEffect::default(), kind: ElementKind::Symbol { symbol: sym_id, loop_mode: LoopMode::Loop, first_frame: 0, blend: anicraft_doc::BlendMode::Normal, filters: Vec::new(), events: Vec::new() }, }; - let mut elements = rest; - elements.insert(first_pos.min(elements.len()), Arc::new(instance)); - kf.elements = elements; - let mut layer = Layer::new(layer_id, "Layer 1"); - if let Some(k) = layer.keyframe_mut(0) { - k.elements = children; + // Children are stored relative to the registration point (the selection centre). + let to_local = Affine::translate(-center.x, -center.y); + let single = layers.len() == 1; + let mut inner: Vec> = Vec::with_capacity(layers.len()); + for l in layers { + let sel = s.selection.on(l); + let source = s.doc.timeline(s.scene).layer(l).map(|x| x.name.clone()).unwrap_or_default(); + let picked = s.with_layer(l, |s| -> Result>> { + let kf = s.editable_keyframe()?; + let first_pos = kf.elements.iter().position(|e| sel.contains(&e.id)).unwrap_or(kf.elements.len()); + let (picked, mut rest): (Vec>, Vec>) = kf.elements.drain(..).partition(|e| sel.contains(&e.id)); + if l == top { + rest.insert(first_pos.min(rest.len()), Arc::new(instance.clone())); + } + kf.elements = rest; + Ok(picked) + })?; + let children: Vec> = picked + .into_iter() + .map(|e| { + let mut e = Arc::unwrap_or_clone(e); + e.transform = to_local.mul(&e.transform); + Arc::new(e) + }) + .collect(); + let id = if inner.is_empty() { first_layer } else { LayerId(s.doc.alloc_id()) }; + let mut layer = Layer::new(id, if single { "Layer 1".to_string() } else { source }); + if let Some(k) = layer.keyframe_mut(0) { + k.elements = children; + } + inner.push(Arc::new(layer)); } - s.doc.library.push(Arc::new(Symbol { id: sym_id, name: name.clone(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: vec![Arc::new(layer)] } })); - s.selection = vec![inst_id]; - Ok(json!({"symbol": sym_id.0, "instance": inst_id.0, "name": name})) + s.doc.library.push(Arc::new(Symbol { id: sym_id, name: name.clone(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: inner } })); + s.layer = top; + s.select_only([inst_id]); + Ok(json!({"symbol": sym_id.0, "instance": inst_id.0, "name": name, "layer": top.0})) } fn break_apart(s: &mut Session, _: &Value) -> Result { - let sel = s.selection.clone(); + let sel = s.selection.on(s.layer); if sel.is_empty() { return Err(EngineError::State("nothing is selected".into())); } @@ -682,7 +742,7 @@ fn break_apart(s: &mut Session, _: &Value) -> Result { return Err(EngineError::State("the selection has no symbol instances or text to break apart".into())); } s.editable_keyframe()?.elements = out; - s.selection = fresh_ids.clone(); + s.select_only(fresh_ids.iter().copied()); Ok(json!({"created": fresh_ids.len()})) } @@ -707,7 +767,7 @@ fn place(s: &mut Session, p: &Value) -> Result { kind: ElementKind::Symbol { symbol: sym, loop_mode: LoopMode::Loop, first_frame: 0, blend: anicraft_doc::BlendMode::Normal, filters: Vec::new(), events: Vec::new() }, }; s.editable_keyframe()?.elements.push(Arc::new(el)); - s.selection = vec![id]; + s.select_only([id]); Ok(json!({"element": id.0})) } @@ -733,6 +793,6 @@ fn place_bitmap(s: &mut Session, p: &Value, bitmap: anicraft_doc::BitmapId) -> R }), }; s.editable_keyframe()?.elements.push(Arc::new(el)); - s.selection = vec![id]; + s.select_only([id]); Ok(json!({"element": id.0})) } diff --git a/crates/engine/src/cmds_erase.rs b/crates/engine/src/cmds_erase.rs index bf532ff2..3f3d22f9 100644 --- a/crates/engine/src/cmds_erase.rs +++ b/crates/engine/src/cmds_erase.rs @@ -101,7 +101,7 @@ pub(crate) fn erase_with(s: &mut Session, eraser: &Path, mode: EraseMode, start: EraseMode::Fills => (fills.clone(), touching.clone()), // Only the lines take part, so the fills stay exactly as they are. EraseMode::Lines => (lines.clone(), lines.clone()), - EraseMode::SelectedFills => (fills.iter().copied().filter(|i| el(i).is_some_and(|e| s.selection.contains(&e.id))).collect(), touching.clone()), + EraseMode::SelectedFills => (fills.iter().copied().filter(|i| el(i).is_some_and(|e| s.selection.contains(s.layer, e.id))).collect(), touching.clone()), EraseMode::Inside => { // The topmost raw fill under the start of the stroke. let at = fills.iter().rev().copied().find(|i| el(i).is_some_and(|e| mergeable(e).is_some_and(|sh| sh.path.contains(start, &e.transform, sh.fill_rule)))); @@ -111,7 +111,7 @@ pub(crate) fn erase_with(s: &mut Session, eraser: &Path, mode: EraseMode, start: if targets.is_empty() { s.doc = before; return nothing(match mode { - EraseMode::SelectedFills if s.selection.is_empty() => "select the fills to erase first", + EraseMode::SelectedFills if s.selection.on(s.layer).is_empty() => "select the fills to erase first", EraseMode::Inside => "start the stroke on a fill to erase inside it", _ => "nothing raw to erase there", }); @@ -120,8 +120,9 @@ pub(crate) fn erase_with(s: &mut Session, eraser: &Path, mode: EraseMode, start: // cut the fills they cross and nothing hides them). let rest: Vec = members.iter().copied().filter(|i| !targets.contains(i)).collect(); let (rest_fills, rest_lines): (Vec, Vec) = rest.into_iter().partition(is_fill); + let here = s.layer; let selected = s.selection.clone(); - let shape = |i: &usize| el(i).map(|e| Part::Shape(e, selected.contains(&e.id))); + let shape = |i: &usize| el(i).map(|e| Part::Shape(e, selected.contains(here, e.id))); let parts: Vec = targets.iter().filter_map(shape).chain(std::iter::once(Part::Eraser(eraser))).chain(rest_fills.iter().filter_map(shape)).chain(rest_lines.iter().filter_map(shape)).collect(); let Some((out, picked)) = merge::remerge(s, &parts) else { s.doc = before; @@ -139,8 +140,8 @@ pub(crate) fn erase_with(s: &mut Session, eraser: &Path, mode: EraseMode, start: let gone: Vec = members.iter().filter_map(el).map(|e| e.id).collect(); merge::replace(s, &members, out, false)?; // What stays selected: the rest of the selection, and what is left of selected shapes. - s.selection.retain(|id| !gone.contains(id)); - s.selection.extend(picked); + s.selection.retain(|l, id| l != here || !gone.contains(&id)); + s.selection.extend_on(here, picked); Ok(json!({"erased": true, "mode": mode.key(), "elements": ids, "area_erased": (was.0 - now.0).max(0.0), "length_erased": (was.1 - now.1).max(0.0)})) } @@ -258,7 +259,8 @@ fn faucet(s: &mut Session, p: &Value) -> Result { let (id, line) = (hit.id, matches!(&hit.kind, ElementKind::Shape(sh) if sh.fill.is_none())); let kf = s.editable_keyframe()?; kf.elements.retain(|e| e.id != id); - s.selection.retain(|x| *x != id); + let here = s.layer; + s.selection.remove(here, id); Ok(json!({"deleted": id.0, "kind": if line { "line" } else { "fill" }})) } diff --git a/crates/engine/src/cmds_file.rs b/crates/engine/src/cmds_file.rs index 32edb7b9..9b29f266 100644 --- a/crates/engine/src/cmds_file.rs +++ b/crates/engine/src/cmds_file.rs @@ -351,7 +351,7 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result { s.layer = lid; (lid, ids, made, Some(fid.0)) }; - s.selection = ids.clone(); + s.select_only(ids.iter().copied()); Ok(json!({ "layer": layer_id.0, "folder": folder, diff --git a/crates/engine/src/cmds_modify.rs b/crates/engine/src/cmds_modify.rs index f5dabffc..209bf9f7 100644 --- a/crates/engine/src/cmds_modify.rs +++ b/crates/engine/src/cmds_modify.rs @@ -2,7 +2,7 @@ use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; -use anicraft_doc::{Element, ElementId, ElementKind, Symbol, SymbolId}; +use anicraft_doc::{Element, ElementId, ElementKind, Layer, LayerId, LayerKind, Symbol, SymbolId}; use anicraft_geom::{Affine, Rect, Vec2}; use serde_json::{Value, json}; use std::collections::HashSet; @@ -12,15 +12,15 @@ pub fn specs() -> Vec { let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; vec![ c("edit.cut", "Cut", "Edit", Some("Ctrl+X"), "{}", true, cut as crate::RunFn), - c("edit.copy", "Copy", "Edit", Some("Ctrl+C"), "{}", false, copy), - c("edit.paste", "Paste in Center", "Edit", Some("Ctrl+V"), "{x?, y?} (centre of the pasted artwork; default: offset 10 px)", true, paste), - c("edit.paste_in_place", "Paste in Place", "Edit", Some("Ctrl+Shift+V"), "{}", true, paste_in_place), - c("modify.transform", "Transform", "", None, "{a, b, c, d, e, f} affine applied in stage space (free transform)", true, transform), + c("edit.copy", "Copy", "Edit", Some("Ctrl+C"), "{} (the selection on every layer, each layer's artwork kept apart)", false, copy), + c("edit.paste", "Paste in Center", "Edit", Some("Ctrl+V"), "{x?, y?} (centre of the pasted artwork; default: offset 10 px). Artwork copied from one layer lands on the active layer; from several, back on those layers when they are all here, else on the active layer and the ones below it, creating missing ones", true, paste), + c("edit.paste_in_place", "Paste in Place", "Edit", Some("Ctrl+Shift+V"), "{} (layers as edit.paste)", true, paste_in_place), + c("modify.transform", "Transform", "", None, "{a, b, c, d, e, f} affine applied in stage space (free transform), to the selection on every layer", true, |s, p| s.each_layer(true, |s| transform(s, p))), c("modify.rotate_cw", "Rotate 90° CW", "Modify/Transform", Some("Ctrl+Shift+9"), "{}", true, |s, _| about_center(s, Affine::rotate(std::f32::consts::FRAC_PI_2))), c("modify.rotate_ccw", "Rotate 90° CCW", "Modify/Transform", Some("Ctrl+Shift+7"), "{}", true, |s, _| about_center(s, Affine::rotate(-std::f32::consts::FRAC_PI_2))), c("modify.flip_h", "Flip Horizontal", "Modify/Transform", None, "{}", true, |s, _| about_center(s, Affine::scale(-1.0, 1.0))), c("modify.flip_v", "Flip Vertical", "Modify/Transform", None, "{}", true, |s, _| about_center(s, Affine::scale(1.0, -1.0))), - c("modify.remove_transform", "Remove Transform", "Modify/Transform", Some("Ctrl+Shift+Z"), "{}", true, remove_transform), + c("modify.remove_transform", "Remove Transform", "Modify/Transform", Some("Ctrl+Shift+Z"), "{}", true, |s, p| s.each_layer(true, |s| remove_transform(s, p))), c("align.left", "Left", "Modify/Align", Some("Ctrl+Alt+1"), "{to_stage?}", true, |s, p| align(s, p, Edge::Left)), c("align.hcenter", "Horizontal Center", "Modify/Align", Some("Ctrl+Alt+2"), "{to_stage?}", true, |s, p| align(s, p, Edge::HCenter)), c("align.right", "Right", "Modify/Align", Some("Ctrl+Alt+3"), "{to_stage?}", true, |s, p| align(s, p, Edge::Right)), @@ -34,17 +34,34 @@ pub fn specs() -> Vec { // ----- clipboard -------------------------------------------------------------------------------- -/// Copied artwork: elements as they look at the playhead, plus every symbol they need, so a -/// paste into another document is complete. +/// Copied artwork: elements as they look at the playhead, kept apart by the layer they came from, +/// plus every symbol they need, so a paste into another document is complete. #[derive(Clone, Default)] pub struct Clipboard { - pub elements: Vec, + /// One entry per layer the selection was on, top to bottom. + pub layers: Vec, pub symbols: Vec>, } +/// One layer's copied artwork. +#[derive(Clone)] +pub struct ClipLayer { + /// The layer it came from, and its name (for a layer a paste has to create). + pub layer: LayerId, + pub name: String, + pub elements: Vec, +} + impl Clipboard { pub fn is_empty(&self) -> bool { - self.elements.is_empty() + self.layers.iter().all(|l| l.elements.is_empty()) + } + /// Every copied element, layer by layer. + pub fn elements(&self) -> impl Iterator { + self.layers.iter().flat_map(|l| l.elements.iter()) + } + pub fn len(&self) -> usize { + self.layers.iter().map(|l| l.elements.len()).sum() } } @@ -76,26 +93,35 @@ pub(crate) fn collect_symbols(s: &Session, roots: &[Element]) -> Vec } fn copy(s: &mut Session, _: &Value) -> Result { - let sel = s.selection.clone(); - if sel.is_empty() { + let layers = s.selected_layers(); + if layers.is_empty() { return Err(EngineError::State("nothing is selected".into())); } // What you see is what you copy: the evaluated state at the playhead (tweens applied). - let elements: Vec = s.visible_elements().iter().filter(|e| sel.contains(&e.id)).map(|e| (**e).clone()).collect(); - let symbols = collect_symbols(s, &elements); - let n = elements.len(); - s.clipboard = Clipboard { elements, symbols }; - Ok(json!({"copied": n})) + let mut copied = Vec::with_capacity(layers.len()); + for l in layers { + let elements: Vec = s.elements_on(l).iter().filter(|e| s.selection.contains(l, e.id)).map(|e| (**e).clone()).collect(); + let name = s.doc.timeline(s.scene).layer(l).map(|x| x.name.clone()).unwrap_or_default(); + if !elements.is_empty() { + copied.push(ClipLayer { layer: l, name, elements }); + } + } + let all: Vec = copied.iter().flat_map(|c| c.elements.iter().cloned()).collect(); + let symbols = collect_symbols(s, &all); + let n = all.len(); + let layers = copied.len(); + s.clipboard = Clipboard { layers: copied, symbols }; + Ok(json!({"copied": n, "layers": layers})) } fn cut(s: &mut Session, p: &Value) -> Result { copy(s, p)?; - crate::cmds_draw::delete(s, p)?; - Ok(json!({"cut": s.clipboard.elements.len()})) + crate::cmds_draw::delete_selection(s, p)?; + Ok(json!({"cut": s.clipboard.len()})) } fn clipboard_bounds(s: &Session) -> Rect { - s.clipboard.elements.iter().fold(Rect::EMPTY, |r, e| r.union(&clip_element_bounds(s, e))) + s.clipboard.elements().fold(Rect::EMPTY, |r, e| r.union(&clip_element_bounds(s, e))) } fn clip_element_bounds(s: &Session, e: &Element) -> Rect { @@ -109,15 +135,81 @@ fn clip_element_bounds(s: &Session, e: &Element) -> Rect { e.bounds(&doc) } +/// The layers a paste puts each copied layer's artwork on (ADR 0044). One copied layer goes on +/// the active layer. Several go back on the layers they came from when every one of them is in +/// this scene (same id and name) and can be drawn on; else on the active layer and the drawable +/// layers below it, in order, with missing layers created at the bottom named after the copied +/// ones, as Paste Frames does. +fn paste_targets(s: &mut Session) -> Result> { + let n = s.clipboard.layers.len(); + if n <= 1 { + return Ok(vec![s.layer]); + } + let tl = s.doc.timeline(s.scene); + let drawable = |s: &Session, l: &Layer| s.selectable(l.id) && !matches!(l.kind, LayerKind::Folder | LayerKind::Camera | LayerKind::Armature); + let home: Vec = s.clipboard.layers.iter().filter_map(|c| tl.layer(c.layer).filter(|l| l.name == c.name && drawable(s, l)).map(|l| l.id)).collect(); + if home.len() == n { + return Ok(home); + } + let at = s.active_layer_index().unwrap_or(0); + let mut out = vec![s.layer]; + out.extend(tl.layers.iter().skip(at + 1).filter(|l| drawable(s, l)).map(|l| l.id).take(n - 1)); + let names: Vec = s.clipboard.layers.iter().skip(out.len()).map(|c| c.name.clone()).collect(); + for name in names { + if s.doc.timeline(s.scene).layers.len() >= 1000 { + return Err(EngineError::State("too many layers (limit 1000)".into())); + } + let id = LayerId(s.doc.alloc_id()); + let count = s.doc.timeline(s.scene).layers.len(); + let mut layer = Layer::new(id, name); + if let Some(k) = layer.keyframe_mut(0) { + k.duration = s.frame_count().max(1); + } + layer.color = crate::cmds_timeline::layer_color(count + 1); + let tl = s.doc.timeline_mut(s.scene); + tl.layers.push(Arc::new(layer)); + tl.repair_masks(); + out.push(id); + } + Ok(out) +} + fn paste_with(s: &mut Session, offset: Vec2) -> Result { if s.clipboard.is_empty() { return Err(EngineError::State("the clipboard is empty".into())); } import_symbols(s, &s.clipboard.symbols.clone()); + let targets = paste_targets(s)?; + let copied = s.clipboard.layers.clone(); + let mut sel = crate::Selection::default(); + let mut all = Vec::new(); + let mut merged = false; + for (c, &layer) in copied.iter().zip(&targets) { + let (fresh, m) = s.with_layer(layer, |s| paste_layer(s, &c.elements, offset))?; + merged |= m; + all.extend(fresh.iter().map(|e| e.0)); + sel.extend_on(layer, fresh); + } + s.selection = sel; + if let Some(&first) = targets.first() + && targets.len() > 1 + { + s.layer = first; + } + let mut v = json!({"pasted": all, "merged": merged}); + if targets.len() > 1 { + v["layers"] = json!(targets.iter().map(|l| l.0).collect::>()); + } + Ok(v) +} + +/// Pastes `elements` moved by `offset` into the active layer's keyframe at the playhead; their +/// new ids, and whether raw shapes merged. +fn paste_layer(s: &mut Session, elements: &[Element], offset: Vec2) -> Result<(Vec, bool)> { let mut fresh = Vec::new(); let mut out = Vec::new(); let mut raw = Vec::new(); - for e in s.clipboard.elements.clone() { + for e in elements.iter().cloned() { let mut e = e; e.id = ElementId(s.doc.alloc_id()); e.transform = Affine::translate(offset.x, offset.y).mul(&e.transform); @@ -139,8 +231,7 @@ fn paste_with(s: &mut Session, offset: Vec2) -> Result { if merged { fresh.extend(crate::merge::merge_in(s, raw)?); } - s.selection = fresh.clone(); - Ok(json!({"pasted": fresh.iter().map(|e| e.0).collect::>(), "merged": merged})) + Ok((fresh, merged)) } /// Adds the symbols this document lacks (from a clipboard, maybe another document's) and @@ -218,6 +309,7 @@ fn remove_transform(s: &mut Session, _: &Value) -> Result { Ok(json!({"reset": n})) } +/// `m` about the centre of the whole selection's bounds, on every layer it is on. fn about_center(s: &mut Session, m: Affine) -> Result { let b = s.selection_bounds(); if b.is_empty() { @@ -225,8 +317,7 @@ fn about_center(s: &mut Session, m: Affine) -> Result { } let c = b.center(); let full = Affine::translate(c.x, c.y).mul(&m).mul(&Affine::translate(-c.x, -c.y)); - let n = apply(s, &full)?; - Ok(json!({"transformed": n})) + s.each_layer(true, |s| Ok(json!({"transformed": apply(s, &full)?}))) } // ----- align ------------------------------------------------------------------------------------ @@ -241,7 +332,10 @@ enum Edge { Bottom, } -fn moves_for(bounds: &[(ElementId, Rect)], target: Rect, edge: Edge) -> Vec<(ElementId, Vec2)> { +/// A selected element: its layer and id. +type Item = (LayerId, ElementId); + +fn moves_for(bounds: &[(Item, Rect)], target: Rect, edge: Edge) -> Vec<(Item, Vec2)> { bounds .iter() .map(|(id, b)| { @@ -258,23 +352,38 @@ fn moves_for(bounds: &[(ElementId, Rect)], target: Rect, edge: Edge) -> Vec<(Ele .collect() } -fn translate_each(s: &mut Session, moves: &[(ElementId, Vec2)]) -> Result { - let kf = s.editable_keyframe()?; +/// Moves each element by its own amount, on its own layer. +fn translate_each(s: &mut Session, moves: &[(Item, Vec2)]) -> Result { + let mut layers: Vec = Vec::new(); + for ((l, _), _) in moves { + if !layers.contains(l) { + layers.push(*l); + } + } let mut n = 0; - for (id, d) in moves { - if d.x == 0.0 && d.y == 0.0 { - continue; // untouched elements stay shared with the undo snapshot - } - for e in kf.elements_mut_where(|e| e == *id) { - e.transform = Affine::translate(d.x, d.y).mul(&e.transform); - n += 1; + for layer in layers { + let mine: Vec<(ElementId, Vec2)> = moves.iter().filter(|((l, _), d)| *l == layer && (d.x != 0.0 || d.y != 0.0)).map(|((_, id), d)| (*id, *d)).collect(); + if mine.is_empty() { + continue; // untouched layers stay shared with the undo snapshot } + n += s.with_layer(layer, |s| -> Result { + let kf = s.editable_keyframe()?; + let mut n = 0; + for (id, d) in &mine { + for e in kf.elements_mut_where(|e| e == *id) { + e.transform = Affine::translate(d.x, d.y).mul(&e.transform); + n += 1; + } + } + Ok(n) + })?; } Ok(n) } -fn selected_bounds(s: &Session) -> Vec<(ElementId, Rect)> { - s.selection.iter().map(|id| (*id, s.element_bounds(*id))).filter(|(_, b)| !b.is_empty()).collect() +/// Each selected element's bounds, over every layer: alignment works across layers. +fn selected_bounds(s: &Session) -> Vec<(Item, Rect)> { + s.selected_elements().iter().map(|(l, e)| ((*l, e.id), s.element_bounds_on(*l, e.id))).filter(|(_, b)| !b.is_empty()).collect() } fn align(s: &mut Session, p: &Value, edge: Edge) -> Result { @@ -304,7 +413,7 @@ fn distribute(s: &mut Session, horizontal: bool) -> Result { let (Some(first), Some(last)) = (bounds.first(), bounds.last()) else { return Ok(json!({"moved": 0})) }; let (a, z) = (key(&first.1), key(&last.1)); let step = (z - a) / (bounds.len() - 1) as f32; - let moves: Vec<(ElementId, Vec2)> = bounds + let moves: Vec<(Item, Vec2)> = bounds .iter() .enumerate() .map(|(i, (id, b))| { diff --git a/crates/engine/src/cmds_motion.rs b/crates/engine/src/cmds_motion.rs index 46c941ad..2f7f6cc2 100644 --- a/crates/engine/src/cmds_motion.rs +++ b/crates/engine/src/cmds_motion.rs @@ -443,7 +443,7 @@ pub(crate) fn create(s: &mut Session, p: &Value) -> Result { let name = format!("Tween {}", s.doc.library.len() + 1); s.layer = lid; s.frame = start; - s.selection = ids; + s.selection = crate::Selection::only(lid, ids); let r = crate::cmds_draw::convert_to_symbol(s, &json!({"name": name})); s.frame = frame; if layer != lid { diff --git a/crates/engine/src/cmds_paint.rs b/crates/engine/src/cmds_paint.rs index 7cacb8af..f99fa87a 100644 --- a/crates/engine/src/cmds_paint.rs +++ b/crates/engine/src/cmds_paint.rs @@ -41,7 +41,7 @@ pub fn specs() -> Vec { ), c("paint.ink", "Ink Bottle", "", None, "{x, y, color?, width?, profile?}", true, ink), c("paint.pick", "Eyedropper", "", None, "{x, y, other?: bool (into the other swatch only: a fill's colour into the stroke, a line's into the fill), slop?} picks the style under the point on any visible layer into the tool settings: a fill's paint (solid, gradient or bitmap, kept where it is on the stage) into the fill swatch, a line's colour, width and profile into the stroke settings", false, pick_style), - c("paint.apply_style", "Apply Style", "", None, "{fill?: bool, stroke?: bool} (default both) gives the selected shapes the fill swatch's paint (shapes with a fill) and the stroke settings (shapes with a line, and drawing objects without one)", true, apply_style), + c("paint.apply_style", "Apply Style", "", None, "{fill?: bool, stroke?: bool} (default both) gives the selected shapes the fill swatch's paint (shapes with a fill) and the stroke settings (shapes with a line, and drawing objects without one)", true, |s, p| s.each_layer(false, |s| apply_style(s, p))), ] } diff --git a/crates/engine/src/cmds_plugin.rs b/crates/engine/src/cmds_plugin.rs index 659f7dbb..9dd37206 100644 --- a/crates/engine/src/cmds_plugin.rs +++ b/crates/engine/src/cmds_plugin.rs @@ -90,7 +90,7 @@ fn document_view(s: &Session) -> Value { "frames": s.frame_count(), "layer": s.layer.0, "layers": layers, - "selection": s.selection.iter().map(|e| e.0).collect::>(), + "selection": s.selection.id_list(), }) } @@ -116,7 +116,7 @@ fn elements_view(s: &Session, req: &Value) -> std::result::Result *e = e.union(&r); } let mut out = Vec::new(); - for e in s.visible_elements().iter().filter(|e| !only_selected || s.selection.contains(&e.id)) { + for e in s.visible_elements().iter().filter(|e| !only_selected || s.selection.contains(s.layer, e.id)) { if out.len() >= MAX_ELEMENTS { break; } @@ -124,7 +124,7 @@ fn elements_view(s: &Session, req: &Value) -> std::result::Result let mut v = json!({ "id": e.id.0, "name": e.name, - "selected": s.selection.contains(&e.id), + "selected": s.selection.contains(s.layer, e.id), "transform": e.transform.m, "bounds": if b.is_empty() { Value::Null } else { json!([b.min.x, b.min.y, b.max.x - b.min.x, b.max.y - b.min.y]) }, "alpha": e.color.alpha, diff --git a/crates/engine/src/cmds_raw.rs b/crates/engine/src/cmds_raw.rs index f68fcedc..7b122f1b 100644 --- a/crates/engine/src/cmds_raw.rs +++ b/crates/engine/src/cmds_raw.rs @@ -10,8 +10,8 @@ use crate::cmds_draw::MAX_EXTENT; use crate::merge::{self, Part, mergeable, reach}; use crate::params::*; -use crate::{CommandSpec, EngineError, Result, Session}; -use anicraft_doc::{Element, ElementId, ElementKind, LayerId, evaluate_layer_elements}; +use crate::{CommandSpec, CutOrigin, EngineError, Result, Session}; +use anicraft_doc::{Element, ElementId, ElementKind, LayerId}; use anicraft_geom::planar::SNAP; use anicraft_geom::raw::{self as rawgeom, Cubic}; use anicraft_geom::walk::cubic_point; @@ -46,7 +46,7 @@ pub fn specs() -> Vec { "Select Parts", "", None, - "{x0, y0, x1, y1, add?: bool} the marquee: the parts of raw fills and strokes under the rectangle (cut at its edges) and the objects wholly inside it", + "{x0, y0, x1, y1, add?: bool} the marquee, on every visible, unlocked layer: the parts of raw fills and strokes under the rectangle (cut at its edges, per layer) and the objects wholly inside it", true, select_rect, ), @@ -86,11 +86,6 @@ impl Grab { } } -/// The elements on `layer` at the playhead. -fn layer_elements(s: &Session, layer: LayerId) -> Vec> { - s.doc.timeline(s.scene).layer(layer).and_then(|l| evaluate_layer_elements(l, s.frame)).map(|(_, e)| e.into_owned()).unwrap_or_default() -} - /// A raw shape's anchors in stage space. fn stage_anchors(e: &Element) -> Vec<(usize, Vec2)> { match mergeable(e) { @@ -106,10 +101,10 @@ impl Session { pub fn raw_grab(&self, p: Vec2, slop: f32, point_slop: f32) -> Option<(LayerId, Grab)> { let (layer, id) = self.hit_test(p, slop)?; let object = Some((layer, Grab::Object { id })); - if layer == self.layer && self.selection.contains(&id) { + if self.selection.contains(layer, id) { return object; } - let els = layer_elements(self, layer); + let els = self.elements_on(layer); let el = els.iter().find(|e| e.id == id)?; let Some(sh) = mergeable(el) else { return object }; // A corner or end there, of any raw shape on the layer. @@ -506,10 +501,8 @@ fn snap_point(els: &[Arc], to: Vec2, radius: f32, moving: &[(ElementId, /// `from` when given, else whichever comes closest) onto an anchor or line of the shapes that /// did not move, within `radius`. pub(crate) fn snap_selection(s: &Session, radius: f32, from: Option) -> Option<(Vec2, Vec2, SnapTo)> { - let els = s.visible_elements(); - let sel = &s.selection; let mut own: Vec = Vec::new(); - for e in els.iter().filter(|e| sel.contains(&e.id)) { + for (_, e) in s.selected_elements() { if let ElementKind::Shape(sh) = &e.kind { own.extend(sh.path.editable_anchors().into_iter().map(|(_, q)| e.transform.apply(q))); } @@ -524,7 +517,9 @@ pub(crate) fn snap_selection(s: &Session, radius: f32, from: Option) -> Op if candidates.is_empty() { return None; } - let t = targets(&els, |id| sel.contains(&id), |_, _| false, |_, _| false); + // What stays put on the layers the selection is on (ADR 0044). + let rest: Vec> = s.selected_layers().into_iter().flat_map(|l| s.elements_on(l).into_iter().filter(move |e| !s.selection.contains(l, e.id))).collect(); + let t = targets(&rest, |_| false, |_, _| false, |_, _| false); candidates .into_iter() .filter_map(|c| snap_to(&t, c, radius).map(|(q, k, d)| (c, q, k, d))) @@ -534,26 +529,6 @@ pub(crate) fn snap_selection(s: &Session, radius: f32, from: Option) -> Op // ----- the marquee ------------------------------------------------------------------------------ -/// The layer a marquee over `r` selects on: the active layer when it has something there, else -/// the topmost visible, unlocked layer that does (a selection lives on one layer). -fn marquee_layer(s: &Session, r: &Rect) -> LayerId { - let dl = s.display_list(); - let tl = s.doc.timeline(s.scene); - let usable = |l: LayerId| tl.layer(l).is_some_and(|x| !x.locked && !tl.locked_by_folder(x.id)); - let touched: Vec = dl - .items - .iter() - .rev() - .filter(|i| { - let hw = i.stroke.as_ref().map_or(0.0, |st| st.reach() * i.transform.mean_scale()); - !i.path.bounds().transformed(&i.transform).inflate(hw).intersect(r).is_empty() - }) - .map(|i| i.layer) - .filter(|l| usable(*l)) - .collect(); - if touched.contains(&s.layer) { s.layer } else { touched.first().copied().unwrap_or(s.layer) } -} - fn contains(outer: &Rect, inner: &Rect) -> bool { inner.min.x >= outer.min.x && inner.min.y >= outer.min.y && inner.max.x <= outer.max.x && inner.max.y <= outer.max.y } @@ -564,57 +539,88 @@ fn on_editable_key(s: &Session) -> bool { s.active_layer().and_then(|l| l.keyframe_at(s.frame)).is_some_and(|k| k.motion.is_none() && (k.tween.is_none() || k.start == s.frame)) } +/// The marquee (ADR 0041, 0044): on every visible, unlocked layer, the parts of raw shapes under +/// the rectangle (cut at its edges) and the objects wholly inside it. fn select_rect(s: &mut Session, p: &Value) -> Result { let a = Vec2::new(f32_req(p, "x0")?, f32_req(p, "y0")?); let b = Vec2::new(f32_req(p, "x1")?, f32_req(p, "y1")?); let add = opt_bool(p, "add")?.unwrap_or(false); let r = Rect::from_points(a, b); - let layer = marquee_layer(s, &r); - if layer != s.layer { - s.layer = layer; - s.selection.clear(); - } if !add { s.selection.clear(); } - let usable = s.active_layer().is_some_and(|l| l.visible && !l.locked) && !s.doc.timeline(s.scene).locked_by_folder(s.layer); - if !usable || r.width() <= 0.0 || r.height() <= 0.0 { - return Ok(json!({"selected": s.selection.iter().map(|e| e.0).collect::>(), "cut": 0})); + if r.width() <= 0.0 || r.height() <= 0.0 { + return Ok(json!({"selected": s.selection.id_list(), "cut": 0})); } - let mut picked: Vec = Vec::new(); - let mut partial: Vec = Vec::new(); - for e in s.visible_elements() { - let bounds = s.element_bounds(e.id); - if bounds.is_empty() || bounds.intersect(&r).is_empty() { - continue; + // What each layer has under the marquee, from one display list: wholly inside, or (raw + // shapes) partly. + let mut found: Vec<(LayerId, Vec, Vec)> = Vec::new(); + let layers: Vec = s.doc.timeline(s.scene).layers.iter().map(|l| l.id).filter(|l| s.gathers(*l)).collect(); + for l in layers { + let (mut picked, mut partial) = (Vec::new(), Vec::new()); + for e in s.elements_on(l) { + let bounds = s.element_bounds_on(l, e.id); + if bounds.is_empty() || bounds.intersect(&r).is_empty() { + continue; + } + if contains(&r, &bounds) { + picked.push(e.id); + } else if mergeable(&e).is_some() { + partial.push(e.id); + } } - if contains(&r, &bounds) { - picked.push(e.id); - } else if mergeable(&e).is_some() { - partial.push(e.id); + if !picked.is_empty() || !partial.is_empty() { + found.push((l, picked, partial)); } } - // Raw shapes partly under the marquee are cut at its edges: the parts inside are selected, - // the rest stay as they are. let mut cut = 0; + let (mut origin, mut inside): (CutOrigin, Vec) = (Vec::new(), Vec::new()); + let mut hit: Vec = Vec::new(); + for (l, picked, partial) in found { + let (n, o, i) = s.with_layer(l, |s| marquee_layer(s, &r, picked, &partial))?; + cut += n; + origin.extend(o); + inside.extend(i); + hit.push(l); + } + if !inside.is_empty() { + s.pending_cut = Some((origin, inside)); + } + // The active layer stays when the marquee took something there, else the topmost that it + // did becomes active, as a click would make it. + if !hit.contains(&s.layer) + && let Some(&top) = hit.first() + { + s.layer = top; + } + Ok(json!({"selected": s.selection.id_list(), "cut": cut})) +} + +/// The marquee on the active layer: raw shapes partly under `r` are cut at its edges and the +/// parts inside are selected, the rest stay as they are; `picked` (wholly inside) are selected. +/// How many pieces it cut, each piece with the shape it came from, and the pieces inside. +fn marquee_layer(s: &mut Session, r: &Rect, mut picked: Vec, partial: &[ElementId]) -> Result<(usize, CutOrigin, Vec)> { + let here = s.layer; + let mut cut = 0; + let (mut origin, mut inside_all) = (Vec::new(), Vec::new()); if !partial.is_empty() && on_editable_key(s) { let kf = s.editable_keyframe()?; let existing = kf.elements.clone(); let idx: Vec = existing.iter().enumerate().filter(|(_, e)| partial.contains(&e.id)).map(|(i, _)| i).collect(); // Parts already selected (an earlier marquee, with Shift) stay selected, cut or not. - let parts: Vec = idx.iter().filter_map(|&i| existing.get(i)).map(|e| Part::Shape(e.as_ref(), s.selection.contains(&e.id))).collect(); + let parts: Vec = idx.iter().filter_map(|&i| existing.get(i)).map(|e| Part::Shape(e.as_ref(), s.selection.contains(here, e.id))).collect(); let cutter = Path::rect(r.min.x, r.min.y, r.width(), r.height()); match merge::remerge_with(s, &parts, Some(&cutter)) { Some(rm) if !rm.inside.is_empty() => { - let origin: Vec<(ElementId, ElementId)> = rm.from.iter().filter_map(|&(piece, part)| idx.get(part).and_then(|&i| existing.get(i)).map(|e| (piece, e.id))).collect(); + origin = rm.from.iter().filter_map(|&(piece, part)| idx.get(part).and_then(|&i| existing.get(i)).map(|e| (piece, e.id))).collect(); cut = rm.inside.len(); let gone: Vec = idx.iter().filter_map(|&i| existing.get(i)).map(|e| e.id).collect(); - s.selection.retain(|id| !gone.contains(id)); + s.selection.retain(|l, id| l != here || !gone.contains(&id)); let mut inside = rm.inside; inside.extend(rm.picked.iter().filter(|id| !inside.contains(id)).copied().collect::>()); picked.extend(inside.iter().copied()); merge::replace(s, &idx, rm.out, false)?; - s.pending_cut = Some((origin, inside)); + inside_all = inside; } // Only their bounds reached in: nothing of them is under the marquee. Some(_) => {} @@ -624,23 +630,25 @@ fn select_rect(s: &mut Session, p: &Value) -> Result { } else { picked.extend(partial.iter().copied()); } - for id in picked { - if !s.selection.contains(&id) { - s.selection.push(id); - } - } - Ok(json!({"selected": s.selection.iter().map(|e| e.0).collect::>(), "cut": cut})) + s.selection.extend_on(here, picked); + Ok((cut, origin, inside_all)) } // ----- merging again ---------------------------------------------------------------------------- fn merge_cmd(s: &mut Session, p: &Value) -> Result { - let ids: Vec = match opt_u64_list(p, "ids")? { - Some(v) => v.into_iter().map(ElementId).collect(), - None => s.selection.clone(), - }; - remerge_in_place(s, &ids)?; - Ok(json!({"selected": s.selection.iter().map(|e| e.0).collect::>()})) + match opt_u64_list(p, "ids")? { + Some(v) => remerge_in_place(s, &v.into_iter().map(ElementId).collect::>())?, + // The selection's shapes, on each layer they are on. + None => { + s.each_layer(true, |s| { + let ids = s.selection.on(s.layer); + remerge_in_place(s, &ids)?; + Ok(json!({})) + })?; + } + } + Ok(json!({"selected": s.selection.id_list()})) } /// Merges the raw shapes `ids` again with the raw shapes they touch, keeping their stacking (an @@ -656,13 +664,13 @@ pub(crate) fn remerge_in_place(s: &mut Session, ids: &[ElementId]) -> Result<()> return Ok(()); } let touching: Vec = existing.iter().enumerate().filter(|(_, e)| mergeable(e).is_some_and(|sh| !reach(sh, &e.transform).intersect(&area).is_empty())).map(|(i, _)| i).collect(); - let sel = s.selection.clone(); - let parts: Vec = touching.iter().filter_map(|&i| existing.get(i)).map(|e| Part::Shape(e.as_ref(), sel.contains(&e.id))).collect(); + let here = s.layer; + let parts: Vec = touching.iter().filter_map(|&i| existing.get(i)).map(|e| Part::Shape(e.as_ref(), s.selection.contains(here, e.id))).collect(); // Too much to merge at once: the shapes stay as edited. let Some((out, picked)) = merge::remerge(s, &parts) else { return Ok(()) }; let gone: Vec = touching.iter().filter_map(|&i| existing.get(i)).map(|e| e.id).collect(); merge::replace(s, &touching, out, false)?; - s.selection.retain(|id| !gone.contains(id)); - s.selection.extend(picked); + s.selection.retain(|l, id| l != here || !gone.contains(&id)); + s.selection.extend_on(here, picked); Ok(()) } diff --git a/crates/engine/src/cmds_rawsub.rs b/crates/engine/src/cmds_rawsub.rs index a98a8fe6..7187da73 100644 --- a/crates/engine/src/cmds_rawsub.rs +++ b/crates/engine/src/cmds_rawsub.rs @@ -289,7 +289,7 @@ fn points_json(pts: &RawPoints) -> Value { fn points_cmd(s: &mut Session, p: &Value) -> Result { let ids: Vec = match opt_u64_list(p, "ids")? { Some(v) => v.into_iter().map(ElementId).collect(), - None => s.selection.clone(), + None => s.selection.on(s.layer), }; Ok(points_json(&s.raw_points(&ids))) } @@ -304,7 +304,7 @@ fn subselect(s: &mut Session, p: &Value) -> Result { if !add { s.selection.clear(); } - return Ok(json!({"selected": s.selection.iter().map(|e| e.0).collect::>(), "raw": false, "ends": []})); + return Ok(json!({"selected": s.selection.id_list(), "raw": false, "ends": []})); }; if layer != s.layer { s.layer = layer; @@ -330,13 +330,9 @@ fn subselect(s: &mut Session, p: &Value) -> Result { if !add { s.selection.clear(); } - for id in picked { - if !s.selection.contains(&id) { - s.selection.push(id); - } - } - let mut v = if raw { points_json(&s.raw_points(&s.selection.clone())) } else { json!({}) }; - v["selected"] = json!(s.selection.iter().map(|e| e.0).collect::>()); + s.selection.extend_on(s.layer, picked); + let mut v = if raw { points_json(&s.raw_points(&s.selection.on(s.layer))) } else { json!({}) }; + v["selected"] = json!(s.selection.id_list()); v["raw"] = json!(raw); v["ends"] = json!(ends.iter().map(|q| [q.x, q.y]).collect::>()); Ok(v) @@ -383,7 +379,7 @@ fn subselect_rect(s: &mut Session, p: &Value) -> Result { s.selection.clear(); } let usable = s.active_layer().is_some_and(|l| l.visible && !l.locked) && !s.doc.timeline(s.scene).locked_by_folder(s.layer); - let empty = json!({"selected": s.selection.iter().map(|e| e.0).collect::>(), "anchors": []}); + let empty = json!({"selected": s.selection.id_list(), "anchors": []}); if !usable || !(r.width() > 0.0 || r.height() > 0.0) { return Ok(empty); } @@ -396,13 +392,10 @@ fn subselect_rect(s: &mut Session, p: &Value) -> Result { if mergeable(e).is_some() { seeds.push(e.id) } else { objects.push(e.id) } } let raw = connected(&els, &seeds); - for id in raw.iter().chain(&objects) { - if !s.selection.contains(id) { - s.selection.push(*id); - } - } + // Subselection's marquee stays on the active layer, as in Animate (ADR 0042, 0044). + s.selection.extend_on(s.layer, raw.iter().chain(&objects).copied()); let inside: Vec<[f32; 2]> = s.raw_points(&raw).anchors.into_iter().filter(|q| r.contains(*q)).map(|q| [q.x, q.y]).collect(); - Ok(json!({"selected": s.selection.iter().map(|e| e.0).collect::>(), "anchors": inside})) + Ok(json!({"selected": s.selection.id_list(), "anchors": inside})) } // ----- handles ----------------------------------------------------------------------------------- diff --git a/crates/engine/src/cmds_text.rs b/crates/engine/src/cmds_text.rs index 45be9892..a69844b7 100644 --- a/crates/engine/src/cmds_text.rs +++ b/crates/engine/src/cmds_text.rs @@ -33,7 +33,7 @@ pub fn specs() -> Vec { let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; vec![ c("text.create", "New Text", "", None, "{text, x?, y? (top-left; default: centred), font?, size?, bold?, italic?, color?, align?, letter_spacing?, line_spacing?, width?}", true, create as crate::RunFn), - c("text.edit", "Edit Text", "", None, "{text?, font?, size? (px), bold?, italic?, color?, align?: left|center|right, letter_spacing?, line_spacing?, width? (px, wraps; null: one line per paragraph)} on the selected text", true, edit), + c("text.edit", "Edit Text", "", None, "{text?, font?, size? (px), bold?, italic?, color?, align?: left|center|right, letter_spacing?, line_spacing?, width? (px, wraps; null: one line per paragraph)} on the selected text", true, |s, p| s.each_layer(false, |s| edit(s, p))), c("text.fonts", "Fonts", "", None, "{}", false, fonts), ] } @@ -143,7 +143,7 @@ fn create(s: &mut Session, p: &Value) -> Result { s.text_style = TextStyle { font: block.font.clone(), ..style }; let el = Element { id, name: String::new(), transform: Affine::translate(x, y), color: ColorEffect::default(), kind: ElementKind::Text(Arc::new(block)) }; s.editable_keyframe()?.elements.push(Arc::new(el)); - s.selection = vec![id]; + s.select_only([id]); Ok(out) } diff --git a/crates/engine/src/cmds_timeline.rs b/crates/engine/src/cmds_timeline.rs index 59e0ac94..7674229b 100644 --- a/crates/engine/src/cmds_timeline.rs +++ b/crates/engine/src/cmds_timeline.rs @@ -654,6 +654,12 @@ fn new_folder(s: &mut Session, p: &Value) -> Result { add_layer(s, p, LayerKind::Folder) } +/// The colour the `n`th layer gets (its outline and timeline bar). +pub(crate) fn layer_color(n: usize) -> anicraft_doc::Rgba { + const PALETTE: [u32; 7] = [0x4fa3ff, 0xff6b4a, 0x66bb6a, 0xffd54a, 0xba68c8, 0x4dd0e1, 0xff8a65]; + anicraft_doc::Rgba::hex(PALETTE.get(n % PALETTE.len()).copied().unwrap_or(0x4fa3ff)) +} + fn add_layer(s: &mut Session, p: &Value, kind: LayerKind) -> Result { let tl = s.doc.timeline(s.scene); if tl.layers.len() >= 1000 { @@ -681,8 +687,7 @@ fn add_layer(s: &mut Session, p: &Value, kind: LayerKind) -> Result { // Match the timeline length so the new layer spans the existing frames. k.duration = s.frame_count().max(1); } - let palette = [0x4fa3ff, 0xff6b4a, 0x66bb6a, 0xffd54a, 0xba68c8, 0x4dd0e1, 0xff8a65]; - layer.color = anicraft_doc::Rgba::hex(palette[n % palette.len()]); + layer.color = layer_color(n); let tl = s.doc.timeline_mut(s.scene); tl.layers.insert(at, Arc::new(layer)); tl.repair_masks(); diff --git a/crates/engine/src/cmds_width.rs b/crates/engine/src/cmds_width.rs index 9fbf287a..4172770d 100644 --- a/crates/engine/src/cmds_width.rs +++ b/crates/engine/src/cmds_width.rs @@ -22,7 +22,7 @@ pub fn specs() -> Vec { None, "{profile: uniform|taper_both|taper_start|taper_end|bulge|pinch | [[t, left, right], ..], id? (default: the selected shapes)}", true, - set_profile as crate::RunFn, + (|s, p| s.each_layer(false, |s| set_profile(s, p))) as crate::RunFn, ), c( "stroke.set_width_point", @@ -90,7 +90,7 @@ fn set_profile(s: &mut Session, p: &Value) -> Result { let profile = opt_profile(p, "profile")?.ok_or_else(|| EngineError::Param("param 'profile' is required".into()))?; let ids: Vec = match id_param(p)? { Some(id) => vec![id], - None => s.selection.clone(), + None => s.selection.on(s.layer), }; if ids.is_empty() { return Err(EngineError::State("nothing is selected".into())); diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index fb2add3b..25294358 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -5,7 +5,7 @@ //! actually copied. History is bounded by an estimate of that unique memory, not by step count, //! so a thousand small nudges are cheap while one huge import is still evictable. -use anicraft_doc::{Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, Symbol}; +use anicraft_doc::{Document, Element, ElementKind, Keyframe, Layer, LayerId, Symbol}; use std::collections::{HashSet, VecDeque}; use std::mem::size_of; use std::sync::Arc; @@ -30,7 +30,7 @@ pub struct Snapshot { pub scene: usize, pub frame: u32, pub layer: LayerId, - pub selection: Vec, + pub selection: crate::Selection, /// Estimated bytes this snapshot keeps alive that the neighbouring state does not share. pub bytes: usize, } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 7318a1f5..759748ee 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -34,6 +34,7 @@ pub mod history; mod merge; pub mod recovery; pub mod render_service; +pub mod selection; pub mod params; pub mod player; pub mod vfs; @@ -140,6 +141,7 @@ pub fn find_command(id: &str) -> Option { } pub use history::{Snapshot, StateId}; +pub use selection::Selection; /// Last addressable frame (0-based); about 70 minutes at 24 fps. pub const MAX_FRAME: u32 = 100_000; @@ -212,8 +214,8 @@ pub struct Session { pub frame: u32, /// Active layer. pub layer: LayerId, - /// Selected elements on the active layer. - pub selection: Vec, + /// Selected elements at the playhead, each with its layer (ADR 0044). + pub selection: Selection, /// Bumped on every document change, undo and redo (UI invalidation). pub revision: u64, /// Identity of the current document content (equal ids ⇒ identical content). @@ -292,7 +294,7 @@ impl Session { scene: 0, frame: 0, layer, - selection: Vec::new(), + selection: Selection::default(), revision: 1, state, saved_state: Some(state), @@ -509,7 +511,7 @@ impl Session { self.provisional = None; } let Some(p) = self.live_cut() else { return }; - let held = self.selection.iter().any(|s| p.inside.contains(s)); + let held = self.selection.ids().any(|s| p.inside.contains(&s)); let fresh_marquee = id == "raw.select_rect" && params.get("add").and_then(Value::as_bool) != Some(true); if !held || fresh_marquee || id.starts_with("file.") || id == "edit.undo" || id == "edit.redo" { self.heal_cut(); @@ -523,12 +525,10 @@ impl Session { if p.state != self.state || self.gesture.is_some() { return; } - let mut sel: Vec = Vec::with_capacity(self.selection.len()); - for id in &self.selection { - let id = p.origin.iter().find(|(piece, _)| piece == id).map_or(*id, |o| o.1); - if !sel.contains(&id) { - sel.push(id); - } + let mut sel = Selection::default(); + for (layer, id) in self.selection.iter() { + let id = p.origin.iter().find(|(piece, _)| *piece == id).map_or(id, |o| o.1); + sel.insert(layer, id); } if self.saved_state == Some(p.state) { self.saved_state = Some(p.before.state); @@ -728,24 +728,6 @@ impl Session { r } - /// Bounds of the whole selection. - pub fn selection_bounds(&self) -> Rect { - self.selection.iter().fold(Rect::EMPTY, |r, id| r.union(&self.element_bounds(*id))) - } - - /// Drops selected ids that no longer exist on the active layer at the playhead. - pub fn fix_selection(&mut self) { - self.scene = self.scene.min(self.doc.scenes.len().saturating_sub(1)); - if self.doc.timeline(self.scene).layer(self.layer).is_none() { - self.layer = self.doc.timeline(self.scene).layers.first().map_or(LayerId(0), |l| l.id); - } - if self.selection.is_empty() { - return; - } - let ids: Vec = self.visible_elements().iter().map(|e| e.id).collect(); - self.selection.retain(|s| ids.contains(s)); - } - pub fn set_frame(&mut self, frame: u32) { self.frame = frame.min(MAX_FRAME); self.fix_selection(); @@ -815,7 +797,7 @@ impl Session { /// Selected elements in the editable keyframe (copy-on-write: only these are cloned). pub(crate) fn selected_elements_mut(&mut self) -> Result> { - let sel = self.selection.clone(); + let sel: std::collections::HashSet = self.selection.on(self.layer).into_iter().collect(); if sel.is_empty() { return Err(EngineError::State("nothing is selected".into())); } @@ -847,7 +829,8 @@ impl Session { "scenes": self.doc.scenes.iter().map(|s| json!({"name": s.name, "frames": s.timeline.frame_count()})).collect::>(), "movie_frames": self.doc.frame_count(), "layer": self.layer.0, - "selection": self.selection.iter().map(|e| e.0).collect::>(), + "selection": self.selection.id_list(), + "selection_layers": self.selected_layers().iter().map(|l| l.0).collect::>(), "layers": layers, "library": symbols, "sounds": sounds, diff --git a/crates/engine/src/merge.rs b/crates/engine/src/merge.rs index 7e40d918..f7da02df 100644 --- a/crates/engine/src/merge.rs +++ b/crates/engine/src/merge.rs @@ -13,7 +13,7 @@ use std::sync::Arc; pub fn specs() -> Vec { let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; vec![ - c("draw.drop", "Drop", "", None, "{} the selected raw shapes cut and join the raw shapes they touch (after a move)", true, drop as crate::RunFn), + c("draw.drop", "Drop", "", None, "{} the selected raw shapes cut and join the raw shapes they touch (after a move), on each layer", true, (|s, p| s.each_layer(true, |s| drop(s, p))) as crate::RunFn), c("element.select_connected", "Select Connected", "", None, "{x, y, add?, slop?} a raw stroke and the strokes joined to it, or a raw fill and the strokes on and in it", false, select_connected), ] } @@ -272,7 +272,7 @@ fn index_of(table: &mut Vec, v: T) -> u32 { /// `draw.drop`: the selected raw shapes go back into the drawing, on top (Animate merges a moved /// shape when it is let go). fn drop(s: &mut Session, _: &Value) -> Result { - let sel = s.selection.clone(); + let sel = s.selection.on(s.layer); let kf = s.editable_keyframe()?; let mut moving = Vec::new(); kf.elements.retain(|e| { @@ -288,8 +288,8 @@ fn drop(s: &mut Session, _: &Value) -> Result { } let mut keep: Vec = sel.into_iter().filter(|id| !moving.iter().any(|e| e.id == *id)).collect(); keep.extend(merge_in(s, moving)?); - s.selection = keep; - Ok(json!({"dropped": n, "selected": s.selection.iter().map(|e| e.0).collect::>()})) + s.select_only(keep); + Ok(json!({"dropped": n, "selected": s.selection.id_list()})) } // ----- the Paint Bucket and imported drawings (ADR 0042) --------------------------------------- @@ -489,10 +489,6 @@ fn select_connected(s: &mut Session, p: &Value) -> Result { if !add { s.selection.clear(); } - for id in picked { - if !s.selection.contains(&id) { - s.selection.push(id); - } - } - Ok(json!({"selected": s.selection.iter().map(|e| e.0).collect::>()})) + s.selection.extend_on(s.layer, picked); + Ok(json!({"selected": s.selection.id_list()})) } diff --git a/crates/engine/src/raw_tests.rs b/crates/engine/src/raw_tests.rs index 2f8c3220..16b4a58e 100644 --- a/crates/engine/src/raw_tests.rs +++ b/crates/engine/src/raw_tests.rs @@ -297,7 +297,7 @@ fn a_marquee_selects_the_parts_under_it_and_the_parts_add_up() { assert_eq!(r["cut"], 3, "part of the fill, of the top and of the right side: {r}"); let sel = s.selection.clone(); let els = s.visible_elements(); - let chosen: Vec<&Arc> = els.iter().filter(|e| sel.contains(&e.id)).collect(); + let chosen: Vec<&Arc> = els.iter().filter(|e| sel.has_id(e.id)).collect(); assert!(chosen.iter().any(|e| matches!(&e.kind, ElementKind::Shape(sh) if !sh.merge && (area(e) - 400.0).abs() < 0.5)), "the object inside"); assert!(!chosen.iter().any(|e| (area(e) - 2000.0).abs() < 0.5), "not the one across the edge"); // Inside: 50 × 45 of the fill (y from 0 to 45), the right side's upper 45 and the top's @@ -333,7 +333,7 @@ fn letting_go_of_a_marquee_puts_the_drawing_back_whole() { run(&mut s, "element.pick", json!({"x": 20, "y": 40})); assert_eq!(count(&s), (1, 4)); assert_eq!(s.selection.len(), 1); - assert!(raw(&s).iter().any(|e| s.selection.contains(&e.id) && is_fill(e) && (area(e) - 8000.0).abs() < 0.5)); + assert!(raw(&s).iter().any(|e| s.selection.has_id(e.id) && is_fill(e) && (area(e) - 8000.0).abs() < 0.5)); // A new marquee replaces the old one. run(&mut s, "raw.select_rect", json!({"x0": 50, "y0": -20, "x1": 200, "y1": 200})); run(&mut s, "raw.select_rect", json!({"x0": -20, "y0": -20, "x1": 50, "y1": 40})); diff --git a/crates/engine/src/rawsub_tests.rs b/crates/engine/src/rawsub_tests.rs index 01bb916a..e3a49050 100644 --- a/crates/engine/src/rawsub_tests.rs +++ b/crates/engine/src/rawsub_tests.rs @@ -311,7 +311,7 @@ fn gradient_fills_take_part_in_the_merge() { } // Deleting the line joins the halves again: one gradient fill. let line = raw(&s).into_iter().find(|e| fill_color(e).is_none() && matches!(&e.kind, ElementKind::Shape(sh) if sh.stroke.is_some())).unwrap(); - s.selection = vec![line.id]; + s.select_only([line.id]); run(&mut s, "edit.delete", json!({})); let halves: Vec = fills(&s).iter().map(|e| e.id.0).collect(); run(&mut s, "raw.merge", json!({"ids": halves})); @@ -346,7 +346,7 @@ fn subselection_timings() { let t = std::time::Instant::now(); let v = run(&mut s, "raw.subselect", json!({"x": 320, "y": 320})); let click = t.elapsed(); - let sel: Vec = s.selection.clone(); + let sel: Vec = s.selection.ids().collect(); let t = std::time::Instant::now(); let pts = s.raw_points(&sel); let list = t.elapsed(); diff --git a/crates/engine/src/selection.rs b/crates/engine/src/selection.rs new file mode 100644 index 00000000..964cfa78 --- /dev/null +++ b/crates/engine/src/selection.rs @@ -0,0 +1,349 @@ +//! The selection (ADR 0044): elements at the playhead, each named with its layer, so one +//! selection holds artwork on several layers as in Animate. +//! +//! Commands see the selection in one of three ways: +//! * **per layer** ([`Session::each_layer`]): the command's single-layer body runs once for every +//! layer that has selected items, with that layer active and the selection narrowed to it +//! (move, delete, duplicate, arrange, filters, colour effects, break apart, …). A selection on +//! the active layer alone runs the body exactly as before; +//! * **across** the layers: the command reads every selected item with its layer (align and +//! distribute, the Free Transform box, copy, convert to symbol, snapping a move); +//! * **on the active layer** only, where Animate does the same (Subselection, the Width tool, +//! the Eraser's selected fills): [`Selection::on`] with [`Session::layer`]. + +use crate::{EngineError, Result, Session}; +use anicraft_doc::{Element, ElementId, LayerId, LayerKind, evaluate_layer_elements}; +use anicraft_geom::Rect; +use serde_json::{Map, Value, json}; +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +/// The selected elements, in the order they were selected, each with its layer. +#[derive(Clone, Debug, Default)] +pub struct Selection { + items: Vec<(LayerId, ElementId)>, + /// The same pairs, for constant-time membership. + set: HashSet<(LayerId, ElementId)>, +} + +impl PartialEq for Selection { + fn eq(&self, other: &Self) -> bool { + self.items == other.items + } +} + +impl Eq for Selection {} + +impl Selection { + /// `ids` on `layer`. + pub fn only(layer: LayerId, ids: impl IntoIterator) -> Selection { + let mut s = Selection::default(); + s.extend_on(layer, ids); + s + } + + pub fn is_empty(&self) -> bool { + self.items.is_empty() + } + + pub fn len(&self) -> usize { + self.items.len() + } + + pub fn clear(&mut self) { + self.items.clear(); + self.set.clear(); + } + + /// Every `(layer, element)`, in selection order. + pub fn iter(&self) -> impl Iterator + '_ { + self.items.iter().copied() + } + + /// Every selected element id (ids are unique within a document), in selection order. + pub fn ids(&self) -> impl Iterator + '_ { + self.items.iter().map(|(_, e)| *e) + } + + /// The ids as plain numbers, for command results. + pub fn id_list(&self) -> Vec { + self.ids().map(|e| e.0).collect() + } + + pub fn first(&self) -> Option<(LayerId, ElementId)> { + self.items.first().copied() + } + + /// Whether `id` on `layer` is selected. + pub fn contains(&self, layer: LayerId, id: ElementId) -> bool { + self.set.contains(&(layer, id)) + } + + /// Whether `id` is selected on any layer. + pub fn has_id(&self, id: ElementId) -> bool { + self.items.iter().any(|(_, e)| *e == id) + } + + /// The selected ids on `layer`, in selection order. + pub fn on(&self, layer: LayerId) -> Vec { + self.items.iter().filter(|(l, _)| *l == layer).map(|(_, e)| *e).collect() + } + + /// The part of the selection on `layer`. + pub fn narrowed(&self, layer: LayerId) -> Selection { + Selection::only(layer, self.on(layer)) + } + + /// The layers with selected items, in the order they were first selected on. + pub fn layers(&self) -> Vec { + let mut out: Vec = Vec::new(); + for (l, _) in &self.items { + if !out.contains(l) { + out.push(*l); + } + } + out + } + + /// Adds `id` on `layer`; false when it already was selected. + pub fn insert(&mut self, layer: LayerId, id: ElementId) -> bool { + if !self.set.insert((layer, id)) { + return false; + } + self.items.push((layer, id)); + true + } + + pub fn extend_on(&mut self, layer: LayerId, ids: impl IntoIterator) { + for id in ids { + self.insert(layer, id); + } + } + + pub fn remove(&mut self, layer: LayerId, id: ElementId) -> bool { + if !self.set.remove(&(layer, id)) { + return false; + } + self.items.retain(|x| *x != (layer, id)); + true + } + + /// Selects `id` on `layer`, or lets go of it when it was selected (Shift-click). + pub fn toggle(&mut self, layer: LayerId, id: ElementId) { + if !self.remove(layer, id) { + self.insert(layer, id); + } + } + + pub fn retain(&mut self, mut keep: impl FnMut(LayerId, ElementId) -> bool) { + let set = &mut self.set; + self.items.retain(|&(l, e)| { + let k = keep(l, e); + if !k { + set.remove(&(l, e)); + } + k + }); + } + + /// Replaces what is selected on `layer` with `ids`, leaving the other layers alone. + pub fn set_on(&mut self, layer: LayerId, ids: impl IntoIterator) { + self.retain(|l, _| l != layer); + self.extend_on(layer, ids); + } +} + +/// Result keys that are values, not counts: they are not summed over layers. +const VALUE_KEYS: &[&str] = &["filters"]; + +/// One result for a command that ran on several layers: lists are joined, counts added, other +/// values come from the first layer; `layers` lists the layers it ran on. +fn merge_results(results: Vec<(LayerId, Value)>) -> Value { + let mut out = Map::new(); + for (_, v) in &results { + let Value::Object(m) = v else { continue }; + for (k, x) in m { + match (out.get_mut(k), x) { + (None, _) => { + out.insert(k.clone(), x.clone()); + } + (Some(Value::Array(a)), Value::Array(b)) => a.extend(b.iter().cloned()), + (Some(Value::Number(a)), Value::Number(b)) if !VALUE_KEYS.contains(&k.as_str()) => { + if let (Some(p), Some(q)) = (a.as_u64(), b.as_u64()) { + *a = p.saturating_add(q).into(); + } + } + _ => {} + } + } + } + out.insert("layers".into(), json!(results.iter().map(|(l, _)| l.0).collect::>())); + Value::Object(out) +} + +impl Session { + /// The elements on `layer` at the playhead (tweens applied). + pub fn elements_on(&self, layer: LayerId) -> Vec> { + self.doc.timeline(self.scene).layer(layer).and_then(|l| evaluate_layer_elements(l, self.frame)).map(|(_, e)| e.into_owned()).unwrap_or_default() + } + + /// Whether artwork on `layer` can be selected: it is in this scene, shown and unlocked + /// (folders included), and not a folder. + pub fn selectable(&self, layer: LayerId) -> bool { + let tl = self.doc.timeline(self.scene); + let Some(i) = tl.layers.iter().position(|l| l.id == layer) else { return false }; + tl.layers.get(i).is_some_and(|l| l.visible && !l.locked && l.kind != LayerKind::Folder) && !tl.locked_by_folder(layer) && !tl.hidden_by_folder(i) + } + + /// Whether a marquee or Select All gathers artwork from `layer`: a selectable layer with + /// artwork on it. The camera layer holds only the camera, and an armature layer's + /// instances are posed by their bones, so they are gathered only while active. + pub fn gathers(&self, layer: LayerId) -> bool { + let kind = self.doc.timeline(self.scene).layer(layer).map(|l| l.kind); + self.selectable(layer) && (layer == self.layer || !matches!(kind, Some(LayerKind::Camera | LayerKind::Armature))) + } + + /// The layers with selected items, top to bottom. + pub fn selected_layers(&self) -> Vec { + let mine = self.selection.layers(); + self.doc.timeline(self.scene).layers.iter().map(|l| l.id).filter(|l| mine.contains(l)).collect() + } + + /// Every selected element as it looks at the playhead, with its layer: layers top to + /// bottom, each in stacking order. + pub fn selected_elements(&self) -> Vec<(LayerId, Arc)> { + let mut out = Vec::new(); + for l in self.selected_layers() { + out.extend(self.elements_on(l).into_iter().filter(|e| self.selection.contains(l, e.id)).map(|e| (l, e))); + } + out + } + + /// Selects `ids` on the active layer, and nothing else. + pub fn select_only(&mut self, ids: impl IntoIterator) { + self.selection = Selection::only(self.layer, ids); + } + + /// Stage-space bounds of element `id` on `layer` at the playhead. + pub fn element_bounds_on(&self, layer: LayerId, id: ElementId) -> Rect { + let mut r = Rect::EMPTY; + for item in self.display_list().items.iter().filter(|i| i.element == id && i.layer == layer) { + let pad = item.stroke.as_ref().map_or(0.0, anicraft_doc::Stroke::reach); + r = r.union(&item.path.bounds().inflate(pad).transformed(&item.transform)); + } + r + } + + /// Bounds of the whole selection, over every layer (the Free Transform box). + pub fn selection_bounds(&self) -> Rect { + let sel: HashSet<(LayerId, ElementId)> = self.selection.iter().collect(); + let mut r = Rect::EMPTY; + for item in self.display_list().items.iter().filter(|i| sel.contains(&(i.layer, i.element))) { + let pad = item.stroke.as_ref().map_or(0.0, anicraft_doc::Stroke::reach); + r = r.union(&item.path.bounds().inflate(pad).transformed(&item.transform)); + } + r + } + + /// Drops selected items that are gone at the playhead, or whose layer is gone, hidden or + /// locked (a locked or hidden layer is never selected), and keeps the active layer valid. + pub fn fix_selection(&mut self) { + self.scene = self.scene.min(self.doc.scenes.len().saturating_sub(1)); + if self.doc.timeline(self.scene).layer(self.layer).is_none() { + self.layer = self.doc.timeline(self.scene).layers.first().map_or(LayerId(0), |l| l.id); + } + if self.selection.is_empty() { + return; + } + let mut present: HashMap> = HashMap::new(); + for l in self.selection.layers() { + if self.selectable(l) { + present.insert(l, self.elements_on(l).iter().map(|e| e.id).collect()); + } + } + self.selection.retain(|l, id| present.get(&l).is_some_and(|ids| ids.contains(&id))); + } + + /// Runs a command's single-layer body once for every layer with selected items, top to + /// bottom, with that layer active and the selection narrowed to it; the selection is then + /// what the runs left selected, and the active layer stays. A selection on the active layer + /// alone (or none) runs the body once, as before. + /// + /// `strict`: every layer must succeed (an error undoes the whole command). Otherwise a layer + /// where the edit does not apply (no movie clips for a filter, no text to restyle) is left + /// as it was, and the command fails only when it applies nowhere. + pub(crate) fn each_layer(&mut self, strict: bool, mut run: impl FnMut(&mut Session) -> Result) -> Result { + let layers = self.selected_layers(); + match layers.as_slice() { + [] => return run(self), + [one] if *one == self.layer => return run(self), + _ => {} + } + let active = self.layer; + let full = self.selection.clone(); + let mut after = Selection::default(); + let mut results = Vec::new(); + let mut first_err: Option = None; + for l in layers { + let before = (!strict).then(|| self.doc.clone()); + self.layer = l; + self.selection = full.narrowed(l); + // Each layer's run sees what the runs before it changed. + self.dl_cache.replace(None); + let r = run(self); + // A motion tween's target on this layer turns into property keys now (the session + // does this once per command, for one layer). + if let Some(edit) = self.motion_edit.take() + && r.is_ok() + { + crate::cmds_motion::finish_edit(self, edit); + } + self.dl_cache.replace(None); + match r { + Ok(v) => { + for (sl, id) in self.selection.iter() { + after.insert(sl, id); + } + results.push((l, v)); + } + Err(e) if strict => { + self.layer = active; + return Err(e); + } + Err(e) => { + if let Some(d) = before { + self.doc = d; + } + for (sl, id) in full.narrowed(l).iter() { + after.insert(sl, id); + } + first_err.get_or_insert(e); + } + } + } + if self.doc.timeline(self.scene).layer(active).is_some() { + self.layer = active; + } + self.selection = after; + if results.is_empty() { + return Err(first_err.unwrap_or_else(|| EngineError::State("nothing is selected".into()))); + } + Ok(merge_results(results)) + } + + /// Runs `f` with `layer` active, then makes the active layer what it was. + pub(crate) fn with_layer(&mut self, layer: LayerId, f: impl FnOnce(&mut Session) -> T) -> T { + let active = self.layer; + self.layer = layer; + self.dl_cache.replace(None); + let r = f(self); + if let Some(edit) = self.motion_edit.take() { + crate::cmds_motion::finish_edit(self, edit); + } + self.dl_cache.replace(None); + if self.doc.timeline(self.scene).layer(active).is_some() { + self.layer = active; + } + r + } +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1b72779f..4892afdf 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -215,16 +215,16 @@ fn undoable_bulk_deletions_ask_but_are_not_blocked() { fn copy_paste_cut_and_paste_in_place() { let mut s = Session::default(); run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 20, "h": 20})); - let orig = s.selection[0]; + let orig = s.selection.ids().next().unwrap(); run(&mut s, "edit.copy", json!({})); run(&mut s, "edit.paste", json!({})); let els = s.visible_elements(); assert_eq!(els.len(), 2); - assert_ne!(s.selection[0], orig, "pasted elements get fresh ids"); - let pasted = els.iter().find(|e| e.id == s.selection[0]).unwrap(); + assert_ne!(s.selection.ids().next().unwrap(), orig, "pasted elements get fresh ids"); + let pasted = els.iter().find(|e| e.id == s.selection.ids().next().unwrap()).unwrap(); assert_eq!(pasted.transform.translation(), Vec2::new(30.0, 30.0)); run(&mut s, "edit.paste_in_place", json!({})); - let last = s.visible_elements().into_iter().find(|e| e.id == s.selection[0]).unwrap(); + let last = s.visible_elements().into_iter().find(|e| e.id == s.selection.ids().next().unwrap()).unwrap(); assert_eq!(last.transform.translation(), Vec2::new(20.0, 20.0)); // paste centred on a point run(&mut s, "edit.paste", json!({"x": 500, "y": 400})); @@ -241,12 +241,17 @@ fn copy_paste_cut_and_paste_in_place() { fn clipboard_carries_symbols_into_another_document() { let mut s = Session::new(sample::demo()); run(&mut s, "layer.select", json!({"index": 0})); + // Select All takes every unlocked layer's artwork (ADR 0044). run(&mut s, "edit.select_all", json!({})); - run(&mut s, "edit.copy", json!({})); + let copied = run(&mut s, "edit.copy", json!({})); + let used = s.doc.library.len(); run(&mut s, "file.new", json!({"confirm": true})); assert!(s.doc.library.is_empty()); run(&mut s, "edit.paste_in_place", json!({})); - assert_eq!(s.doc.library.len(), 1, "the Ball symbol came along"); + assert!(s.doc.library.iter().any(|x| x.name == "Ball"), "the Ball symbol came along"); + assert_eq!(s.doc.library.len(), used); + // Each copied layer lands on a layer of its own, made for it here. + assert_eq!(s.doc.timeline(0).layers.len() as u64, copied["layers"].as_u64().unwrap()); assert!(!anicraft_doc::evaluate(&s.doc, 0).items.is_empty(), "and it renders"); let ids: Vec = s.doc.library.iter().map(|x| x.id.0).collect(); assert!(s.doc.next_id > *ids.iter().max().unwrap()); @@ -280,10 +285,10 @@ fn align_and_distribute() { } run(&mut s, "edit.select_all", json!({})); run(&mut s, "align.left", json!({})); - let lefts: Vec = s.selection.iter().map(|id| s.element_bounds(*id).min.x).collect(); + let lefts: Vec = s.selection.ids().map(|id| s.element_bounds(id).min.x).collect(); assert!(lefts.iter().all(|x| (x - 10.0).abs() < 1e-3), "{lefts:?}"); run(&mut s, "align.distribute_v", json!({})); - let mut ys: Vec = s.selection.iter().map(|id| s.element_bounds(*id).center().y).collect(); + let mut ys: Vec = s.selection.ids().map(|id| s.element_bounds(id).center().y).collect(); ys.sort_by(f32::total_cmp); assert!(((ys[1] - ys[0]) - (ys[2] - ys[1])).abs() < 1e-3, "{ys:?}"); // a single element aligns to the stage @@ -481,13 +486,13 @@ fn commands_png(s: &Session) -> Vec { fn pick_selects_topmost() { let mut s = Session::default(); run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100})); - let a = s.selection[0]; + let a = s.selection.ids().next().unwrap(); run(&mut s, "draw.rect", json!({"x": 50, "y": 50, "w": 100, "h": 100})); - let b = s.selection[0]; + let b = s.selection.ids().next().unwrap(); run(&mut s, "element.pick", json!({"x": 75, "y": 75})); - assert_eq!(s.selection, vec![b]); + assert_eq!(s.selection.ids().collect::>(), vec![b]); run(&mut s, "element.pick", json!({"x": 10, "y": 10})); - assert_eq!(s.selection, vec![a]); + assert_eq!(s.selection.ids().collect::>(), vec![a]); run(&mut s, "element.pick", json!({"x": 500, "y": 500})); assert!(s.selection.is_empty()); } @@ -872,7 +877,7 @@ fn moving_an_anchor_brings_its_handles_and_is_one_undo_step_in_a_gesture() { fn moves_follow_the_element_transform() { let mut s = Session::default(); run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100})); - let id = s.selection[0].0; + let id = s.selection.ids().next().unwrap().0; run(&mut s, "element.set_transform", json!({"sx": 2, "rotation": 90})); let a0 = stage_anchor(&s, id, 0); run(&mut s, "path.move_points", json!({"id": id, "points": [[0, 0]], "dx": 10, "dy": 0})); @@ -883,7 +888,7 @@ fn moves_follow_the_element_transform() { fn add_delete_and_convert_points() { let mut s = Session::default(); run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100})); - let id = s.selection[0].0; + let id = s.selection.ids().next().unwrap().0; let area = |s: &Session| shape_path(s, id).flatten(&anicraft_geom::Affine::IDENTITY, 0.1)[0].points.len(); let n0 = shape_path(&s, id).editable_anchors().len(); // The closing edge (left side, x = 0) can take a point too. @@ -905,7 +910,7 @@ fn add_delete_and_convert_points() { assert!(s.execute("path.delete_points", &json!({"id": id, "cmds": [0]})).is_err()); // Symbols are not point-editable. run(&mut s, "modify.convert_to_symbol", json!({})); - let inst = s.selection[0].0; + let inst = s.selection.ids().next().unwrap().0; assert!(s.execute("path.add_point", &json!({"id": inst, "x": 0, "y": 0})).is_err()); } @@ -1208,7 +1213,7 @@ fn opening_an_xfl_folder_imports_it_untitled() { let text = s.doc.timeline(s.scene).layers[0].keyframes[0].elements.iter().find(|e| matches!(e.kind, ElementKind::Text(_))).cloned().expect("a text element"); assert_eq!(text.name, "title"); assert!(dl.items.iter().any(|i| matches!(i.fill, Some(anicraft_doc::Paint::Solid(c)) if c == anicraft_doc::Rgba::hex(0x0000ff))), "the text renders"); - s.selection = vec![text.id]; + s.select_only([text.id]); run(&mut s, "text.edit", json!({"text": "Hello again"})); // Saved and opened again, it is the same text. let file = dir.join("imported.anicraft"); @@ -1767,9 +1772,10 @@ fn images_import_as_bitmaps_render_save_and_export() { run(&mut s, "edit.select_all", json!({})); run(&mut s, "edit.duplicate", json!({})); let svg = crate::cmds_file::frame_svg(&s.doc, 0); - // Two images, three instances (the JPEG one was duplicated): each image is embedded once. + // Two images, four instances (Select All took both layers, ADR 0044): each image is + // embedded once. assert_eq!(svg.matches("data:image/png;base64,").count(), 2); - assert_eq!(svg.matches(">(), vec![id]); let el = s.active_layer().unwrap().keyframe_at(s.frame).unwrap().elements.iter().find(|e| e.id == id).unwrap().clone(); assert_eq!(el.name, "dot.png"); assert_eq!(el.transform.apply(anicraft_geom::Vec2::new(3.0, 2.0)), anicraft_geom::Vec2::new(100.0, 50.0), "centred on x/y"); @@ -1882,7 +1888,7 @@ fn text_lays_out_renders_edits_saves_and_breaks_apart() { let mut s = Session::default(); let v = run(&mut s, "text.create", json!({"text": "Hello", "x": 100, "y": 50, "size": 64, "color": "#cc2200"})); let id = ElementId(v["element"].as_u64().unwrap()); - assert_eq!(s.selection, vec![id]); + assert_eq!(s.selection.ids().collect::>(), vec![id]); assert!(v["width"].as_f64().unwrap() > 64.0); let text = |s: &Session| match &s.visible_elements().iter().find(|e| e.id == id).unwrap().kind { ElementKind::Text(t) => t.clone(), @@ -1936,7 +1942,7 @@ fn text_lays_out_renders_edits_saves_and_breaks_apart() { run(&mut s, "element.select", json!({"ids": [id.0]})); let before = anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap(); run(&mut s, "modify.break_apart", json!({})); - assert!(matches!(s.visible_elements().iter().find(|e| s.selection.contains(&e.id)).unwrap().kind, ElementKind::Shape(_))); + assert!(matches!(s.visible_elements().iter().find(|e| s.selection.has_id(e.id)).unwrap().kind, ElementKind::Shape(_))); assert_eq!(anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap().data, before.data, "a shape exactly like the text"); let fonts = run(&mut s, "text.fonts", json!({})); assert!(fonts["families"].as_array().is_some_and(|f| !f.is_empty())); diff --git a/crates/engine/src/tests_actions.rs b/crates/engine/src/tests_actions.rs index 697c094e..bf45089e 100644 --- a/crates/engine/src/tests_actions.rs +++ b/crates/engine/src/tests_actions.rs @@ -16,7 +16,7 @@ fn with_instance(kind: &str) -> (Session, u64) { let id = s.execute("draw.rect", &json!({"x": 100, "y": 100, "w": 80, "h": 40})).unwrap()["element"].as_u64().unwrap(); s.execute("element.select", &json!({"ids": [id]})).unwrap(); let v = s.execute("modify.convert_to_symbol", &json!({"name": "Thing"})).unwrap(); - let inst = v["instance"].as_u64().or_else(|| s.selection.first().map(|e| e.0)).unwrap(); + let inst = v["instance"].as_u64().or_else(|| s.selection.first().map(|(_, e)| e.0)).unwrap(); s.execute("symbol.set_kind", &json!({"kind": kind})).unwrap(); (s, inst) } diff --git a/crates/engine/src/tests_bone.rs b/crates/engine/src/tests_bone.rs index bdf3b972..d21f2a01 100644 --- a/crates/engine/src/tests_bone.rs +++ b/crates/engine/src/tests_bone.rs @@ -185,7 +185,7 @@ fn poses_key_frames_and_tween_with_easing() { #[test] fn artwork_edits_are_refused_on_the_armature_layer() { let (mut s, _, _) = rigged(); - s.selection = vec![ElementId(HAND)]; + s.select_only([ElementId(HAND)]); for (id, p) in [("draw.rect", json!({"x": 0, "y": 0, "w": 5, "h": 5})), ("element.translate", json!({"dx": 5, "dy": 0})), ("edit.delete", json!({})), ("timeline.create_motion_tween", json!({}))] { let e = s.execute(id, &p).unwrap_err().to_string(); assert!(e.contains("armature"), "{id}: {e}"); diff --git a/src/actions_panel.rs b/src/actions_panel.rs index 8ae72684..2f142228 100644 --- a/src/actions_panel.rs +++ b/src/actions_panel.rs @@ -70,11 +70,11 @@ pub fn show(app: &mut App, ctx: &egui::Context) { /// The selected movie clip or button instance on the active layer, if exactly one is selected. fn selected_instance(app: &App) -> Option<(Element, SymbolKind)> { - let [id] = app.s.selection.as_slice() else { return None }; - let e = app.s.visible_elements().into_iter().find(|e| e.id == *id)?; + let sel = app.s.selected_elements(); + let [(_, e)] = sel.as_slice() else { return None }; let ElementKind::Symbol { symbol, .. } = &e.kind else { return None }; let kind = app.s.doc.symbol(*symbol)?.kind; - (kind != SymbolKind::Graphic).then(|| ((*e).clone(), kind)) + (kind != SymbolKind::Graphic).then(|| ((**e).clone(), kind)) } fn panel(app: &mut App, ui: &mut egui::Ui) { diff --git a/src/app.rs b/src/app.rs index 9df38925..6790dd81 100644 --- a/src/app.rs +++ b/src/app.rs @@ -580,8 +580,7 @@ impl App { /// Runs an engine command, reporting failures in the status bar. /// After a move, selected raw shapes merge where they land (ADR 0031). pub fn drop_raw(&mut self) { - let sel = &self.s.selection; - let raw = self.s.visible_elements().iter().any(|e| sel.contains(&e.id) && matches!(&e.kind, anicraft_engine::doc::ElementKind::Shape(sh) if sh.merge)); + let raw = self.s.selected_elements().iter().any(|(_, e)| matches!(&e.kind, anicraft_engine::doc::ElementKind::Shape(sh) if sh.merge)); if raw { self.run("draw.drop", json!({})); } @@ -912,7 +911,7 @@ impl App { self.raw_ends = Vec::new(); let anchor = anicraft_engine::geom::Vec2::new(600.0, 330.0); self.raw_anchors = vec![anchor]; - let pts = self.s.raw_points(&self.s.selection.clone()); + let pts = self.s.raw_points(&self.s.selection.on(self.s.layer)); if let (Some(_), Some(h)) = (v, pts.handles.iter().find(|h| h.anchor.distance(anchor) < 0.5 && h.at.y > anchor.y)) { self.s.begin_gesture("Move Handle"); let r = self.run("raw.move_handle", json!({"id": h.id.0, "cmd": h.cmd, "slot": h.slot, "dx": 40, "dy": 10, "merge": false})); diff --git a/src/erasertool.rs b/src/erasertool.rs index 8d270b4b..5692c7b1 100644 --- a/src/erasertool.rs +++ b/src/erasertool.rs @@ -116,8 +116,7 @@ pub fn eyedropper(app: &mut App, p: Vec2, shift: bool, zoom: f32) { _ if into_fill => format!("fill {color}"), _ => format!("line {color}, {} px", v["width"].as_f64().map_or(String::new(), |w| format!("{w:.1}"))), }; - let sel = &app.s.selection; - let shapes = app.s.visible_elements().iter().filter(|e| sel.contains(&e.id) && matches!(e.kind, ElementKind::Shape(_))).count(); + let shapes = app.s.selected_elements().iter().filter(|(_, e)| matches!(e.kind, ElementKind::Shape(_))).count(); if shapes > 0 { if let Some(r) = app.run("paint.apply_style", json!({"fill": into_fill, "stroke": !into_fill})) { let n = r["changed"].as_u64().unwrap_or(0); diff --git a/src/motion_path.rs b/src/motion_path.rs index 5501baf3..9fba38eb 100644 --- a/src/motion_path.rs +++ b/src/motion_path.rs @@ -68,7 +68,7 @@ pub fn shown(app: &App) -> Option { let (a, b) = sel.frames(); sel.layers(&tl.layers).contains(&layer.id) && a < k.end() && b >= k.start }); - if !app.s.selection.contains(&target.id) && !span_selected { + if !app.s.selection.contains(layer.id, target.id) && !span_selected { return None; } let base = Props::of(target); diff --git a/src/pathtools.rs b/src/pathtools.rs index 2cbb159e..e96cbe8a 100644 --- a/src/pathtools.rs +++ b/src/pathtools.rs @@ -202,7 +202,7 @@ fn selected_shapes(app: &App) -> Vec<(ElementId, Arc, Affine)> { app.s .visible_elements() .into_iter() - .filter(|e| app.s.selection.contains(&e.id)) + .filter(|e| app.s.selection.contains(app.s.layer, e.id)) .filter_map(|e| match &e.kind { // Raw shapes show their shared points instead (ADR 0042, below). ElementKind::Shape(sh) if sh.merge => None, @@ -272,8 +272,8 @@ pub fn subselect_drag_start(app: &mut App, press: Pos2, shift: bool, xf: Xf) -> app.s.begin_gesture("Move Points"); return Drag::Points { last: pos2(sp.x, sp.y) }; } - if let Some((_, el)) = app.s.hit_test(sp, 3.0 * xf.unit()) { - if !app.s.selection.contains(&el) { + if let Some((layer, el)) = app.s.hit_test(sp, 3.0 * xf.unit()) { + if !app.s.selection.contains(layer, el) { app.run("element.pick", json!({"x": sp.x, "y": sp.y, "add": shift})); app.points.clear(); } @@ -436,7 +436,7 @@ fn is_raw(e: &anicraft_engine::doc::Element) -> bool { /// The selected raw shapes on the active layer: Subselection shows their points. fn raw_selected(app: &App) -> Vec { - app.s.visible_elements().iter().filter(|e| app.s.selection.contains(&e.id) && is_raw(e)).map(|e| e.id).collect() + app.s.visible_elements().iter().filter(|e| app.s.selection.contains(app.s.layer, e.id) && is_raw(e)).map(|e| e.id).collect() } /// The anchors and handles of the selected raw shapes. @@ -550,7 +550,7 @@ fn raw_drag_start(app: &mut App, press: Pos2, shift: bool, xf: Xf) -> Option { - if !app.s.selection.contains(&id) { + Some((layer, Grab::Fill { id } | Grab::Object { id })) => { + if !app.s.selection.contains(layer, id) { app.run("element.pick", json!({"x": sp.x, "y": sp.y, "add": shift})); } app.s.begin_gesture("Move"); @@ -633,10 +633,10 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { && let Some(p) = resp.interact_pointer_pos() { let sp = to_stage(p); - let under = app.s.hit_test(to_v(sp), 3.0 / zoom).map(|(_, e)| e); + let under = app.s.hit_test(to_v(sp), 3.0 / zoom); // On the motion path, the menu is for its points: the selection stays. let on_path = !panning && crate::motion_path::secondary_click(app, p, xf); - if !on_path && under.is_none_or(|e| !app.s.selection.contains(&e)) { + if !on_path && under.is_none_or(|(l, e)| !app.s.selection.contains(l, e)) { app.run("element.pick", json!({"x": sp.x, "y": sp.y, "add": false})); } } @@ -830,7 +830,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let to_px = Affine::translate(origin.x, origin.y).mul(&Affine::scale(zoom, zoom)); let dl = app.s.display_list(); let stroke = Stroke::new(1.5, T.selection); - for item in dl.items.iter().filter(|i| app.s.selection.contains(&i.element)).take(2_000) { + for item in dl.items.iter().filter(|i| app.s.selection.contains(i.layer, i.element)).take(2_000) { for pl in item.path.flatten(&to_px.mul(&item.transform), 0.5) { let pts: Vec = pl.points.iter().map(|p| pos2(p.x, p.y)).collect(); painter.add(if pl.closed { egui::Shape::closed_line(pts, stroke) } else { egui::Shape::line(pts, stroke) }); @@ -876,9 +876,9 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { && app.palette.is_none() && !app.modal_open() && let Some(sp) = app.cursor_stage - && let Some((_, el)) = app.s.hit_test(to_v(sp), 3.0 / zoom) - && !app.s.selection.contains(&el) && !raw.contains(&el) { - let b = app.s.element_bounds(el); + && let Some((layer, el)) = app.s.hit_test(to_v(sp), 3.0 / zoom) + && !app.s.selection.contains(layer, el) && !raw.contains(&(layer, el)) { + let b = app.s.element_bounds_on(layer, el); if !b.is_empty() { let r = Rect::from_min_max(to_screen(b.min), to_screen(b.max)); painter.rect_stroke(r, 0.0, Stroke::new(1.0, T.selection.gamma_multiply(0.55)), StrokeKind::Middle); @@ -890,13 +890,15 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let to_px = Affine::translate(origin.x, origin.y).mul(&Affine::scale(zoom, zoom)); let mut mesh = egui::Mesh::default(); let mut budget = MAX_DOTS; - for item in app.s.display_list().items.iter().filter(|i| app.s.selection.contains(&i.element) && raw.contains(&i.element)) { + for item in app.s.display_list().items.iter().filter(|i| app.s.selection.contains(i.layer, i.element) && raw.contains(&(i.layer, i.element))) { selection_dots(&mut mesh, item, &to_px.mul(&item.transform), canvas, &mut budget); } painter.add(egui::Shape::mesh(mesh)); } - for id in app.s.selection.clone() { - let b = app.s.element_bounds(id); + // Every selected element, on whichever layer it is (ADR 0044). + for (layer, e) in app.s.selected_elements() { + let id = e.id; + let b = app.s.element_bounds_on(layer, id); if b.is_empty() { continue; } @@ -905,7 +907,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { // Subselection and Width show outlines and points instead (below). continue; } - if app.tool == Tool::Select && raw.contains(&id) { + if app.tool == Tool::Select && raw.contains(&(layer, id)) { continue; // dots above } if transforming { @@ -920,10 +922,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { painter.rect_stroke(h, 0.0, sel_stroke, StrokeKind::Middle); } // registration point - if let Some(e) = app.s.visible_elements().iter().find(|e| e.id == id) { - let o = to_screen(e.transform.translation()); - painter.circle(o, 3.5, Color32::WHITE, Stroke::new(1.0, Color32::BLACK)); - } + let o = to_screen(e.transform.translation()); + painter.circle(o, 3.5, Color32::WHITE, Stroke::new(1.0, Color32::BLACK)); } // Free transform box: recomputed every frame so it follows the artwork while you drag. if transforming && let Some(b) = bounds_arr(app.s.selection_bounds()) { @@ -1002,10 +1002,12 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { painter.text(canvas.right_bottom() + vec2(-10.0, -8.0), egui::Align2::RIGHT_BOTTOM, badge, crate::theme::font(crate::theme::Type::Data), T.text_dim); // Last, so the focus ring is drawn over the artwork. let selected = app.s.selection.len(); - let what = match selected { - 0 => String::new(), - 1 => " · 1 element selected".to_string(), - n => format!(" · {n} elements selected"), + let on = app.s.selected_layers().len(); + let what = match (selected, on) { + (0, _) => String::new(), + (1, _) => " · 1 element selected".to_string(), + (n, 0 | 1) => format!(" · {n} elements selected"), + (n, l) => format!(" · {n} elements selected on {l} layers"), }; crate::a11y::surface(ui, &resp, &format!("Stage · {} tool · frame {}{what}", app.tool.label(), app.s.frame + 1)); } @@ -1096,8 +1098,10 @@ fn grab_mark(painter: &egui::Painter, p: Pos2, grab: Grab) { } /// The raw shapes (parts of the layer's merged drawing) on the active layer. -fn raw_ids(app: &App) -> std::collections::HashSet { - app.s.visible_elements().iter().filter(|e| matches!(&e.kind, anicraft_engine::doc::ElementKind::Shape(sh) if sh.merge)).map(|e| e.id).collect() +/// The raw shapes at the playhead, on every layer, with their layers. +fn raw_ids(app: &App) -> std::collections::HashSet<(anicraft_engine::doc::LayerId, anicraft_engine::doc::ElementId)> { + let layers: Vec<_> = app.s.doc.timeline(app.s.scene).layers.iter().map(|l| l.id).collect(); + layers.into_iter().flat_map(|l| app.s.elements_on(l).into_iter().filter(|e| matches!(&e.kind, anicraft_engine::doc::ElementKind::Shape(sh) if sh.merge)).map(move |e| (l, e.id))).collect() } /// Most selection dots drawn in a frame. diff --git a/src/widthtool.rs b/src/widthtool.rs index cba6eb38..5ad57491 100644 --- a/src/widthtool.rs +++ b/src/widthtool.rs @@ -131,7 +131,7 @@ fn hit(app: &App, at: Pos2, xf: Xf) -> Option { /// Returns the drag (the gesture is open: one undo step). pub fn drag_start(app: &mut App, press: Pos2, xf: Xf) -> Drag { let Some(h) = hit(app, press, xf) else { return Drag::None }; - if !app.s.selection.contains(&h.id) { + if !app.s.selection.contains(app.s.layer, h.id) { app.run("element.select", json!({"ids": [h.id.0]})); } app.s.begin_gesture("Width");