GitCorner

Code

ossartcraftphotocraft🌐
856f865cf98d
//! Editing an action's steps and its set, as the Actions panel does beyond recording:
//! `actions.insert` (Photoshop's Insert Stop… and Insert Menu Item…), `actions.dialog` (the
//! panel's dialog toggle column), `actions.assignSet` (which set folder an action sits in) and
//! `actions.newSet` (New Set…, an empty set folder).
//!
//! All three refuse to run during playback, commit pending recorded steps first, and keep the
//! per-step flag sets (`disabled`, `dialogs`) in step with the moved indices, like
//! `actions.move` and `actions.delete`.

use serde_json::{Value, json};

use crate::actions_cmds::{ActionStep, flush_recording, list_error, not_playing, note_automation_edit, pending_steps, resolve, shift_action_calls};
use crate::commands::CommandSpec;
use crate::{EngineError, Result, Session};

mod insert_path;
mod library_commands;
mod record_again;

pub use insert_path::selected_path as selected_recording_path;
pub(crate) use library_commands::enabled as library_change_enabled;
pub use library_commands::{BASICS_SET, LibraryUndo, undo_library_label};
pub(crate) use library_commands::{confirmed_idle, publish_library};
pub use record_again::{RecordAgainTarget, target as record_again_target};

fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
    EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
}

fn always(_: &Session) -> std::result::Result<(), String> {
    Ok(())
}

/// Flush under the old mode so changing the toggle never retroactively records or loses a stroke.
fn allow_tool_recording(s: &mut Session, p: &Value) -> Result<Value> {
    let cmd = "actions.allowToolRecording";
    not_playing(s, cmd)?;
    let enabled = match p.get("enabled") {
        None | Some(Value::Null) => !s.actions.record_tools,
        Some(Value::Bool(enabled)) => *enabled,
        Some(_) => return Err(bad(cmd, "`enabled` must be true or false")),
    };
    if enabled != s.actions.record_tools {
        if s.actions.recording.is_some() && s.tool_stroke_job_running() {
            return Err(bad(cmd, "wait for the current tool stroke before changing recording"));
        }
        flush_recording(s)?;
        s.actions.record_tools = enabled;
    }
    Ok(json!({"enabled": enabled}))
}

/// Insert a menu event with absent settings, reusing the ordinary validated step insertion.
fn insert_menu_item(s: &mut Session, p: &Value) -> Result<Value> {
    if p.as_object().is_some_and(|o| o.keys().any(|k| !matches!(k.as_str(), "action" | "at" | "id" | "eventKind"))) {
        return Err(bad("actions.insertMenuItem", "menu items accept no recorded settings"));
    }
    let params = json!({"id":p.get("id"),"eventKind":p.get("eventKind").cloned().unwrap_or(json!("name"))});
    crate::atn_cmds::menu_item_command(&params)?;
    s.execute("actions.insert", json!({"action":p.get("action"),"at":p.get("at"),"id":crate::atn_cmds::MENU_ITEM,"params":params}))
}

fn index(p: &Value, key: &str, cmd: &str) -> Result<Option<usize>> {
    match p.get(key) {
        None | Some(Value::Null) => Ok(None),
        Some(v) => v.as_u64().and_then(|n| usize::try_from(n).ok()).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a non-negative integer"))),
    }
}

/// Whether `id` can be a step: a registered command, a Play Action call, or one of the desktop
/// shell's recorded save/view commands.
fn is_step_command(id: &str) -> bool {
    crate::commands::find(id).is_some() || id == "actions.play" || crate::actions_cmds::shell_save_command(id) || crate::actions_cmds::shell_view_command(id)
}

/// `actions.insert`: insert a step into an action, marking the action as automation's when an
/// automation gate is installed.
fn insert(s: &mut Session, p: &Value) -> Result<Value> {
    let cmd = "actions.insert";
    not_playing(s, cmd)?;
    let idx = resolve(s.actions.list.actions(), p, cmd)?;
    let id = match p.get("id") {
        Some(Value::String(id)) if !id.trim().is_empty() => id.trim().to_string(),
        _ => return Err(bad(cmd, "needs `id`, the command the step runs")),
    };
    if !is_step_command(&id) {
        return Err(bad(cmd, format!("unknown command `{id}`")));
    }
    let params = match p.get("params") {
        None | Some(Value::Null) => json!({}),
        Some(v @ Value::Object(_)) => v.clone(),
        Some(_) => return Err(bad(cmd, "`params` must be an object")),
    };
    if id == "actions.play" {
        // Refuse the one cycle visible here; deeper ones are caught at playback.
        let target = params.get("action");
        let is_self = target.and_then(Value::as_str) == Some(s.actions.list.actions()[idx].name.as_str()) || target.and_then(Value::as_u64) == Some(idx as u64);
        if is_self {
            return Err(bad(cmd, "an action cannot play itself"));
        }
    }
    let len = s.actions.list.step_count(idx).saturating_add(pending_steps(s, idx).count());
    let at = index(p, "at", cmd)?.unwrap_or(len);
    if at > len {
        return Err(bad(cmd, format!("`at` {at} is past the last step ({len})")));
    }
    if s.actions.recording.is_some_and(|(_, i)| i == idx) {
        flush_recording(s)?;
    }
    let is_stop = id == crate::atn_cmds::STOP_MESSAGE;
    s.actions.list.insert_step(idx, at, ActionStep::new(id, params)).map_err(|e| list_error(cmd, e))?;
    // A newly inserted Stop shows its message in the app. Duplicates keep their own flags.
    if is_stop {
        s.actions.list.set_dialog(idx, at, true).map_err(|e| list_error(cmd, e))?;
    }
    note_automation_edit(s, idx);
    Ok(step_result(s, idx, at))
}

/// The result of an insert or a step duplicate: step `at` of action `idx` as it now stands.
fn step_result(s: &Session, idx: usize, at: usize) -> Value {
    let action = &s.actions.list.actions()[idx];
    json!({"action": action.name, "step": at, "id": action.steps[at].command, "steps": action.steps.len()})
}

/// Duplicate a step or action below its source, preserving settings and per-step flags.
fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
    let cmd = "actions.duplicate";
    not_playing(s, cmd)?;
    if let Some(set) = p.get("set") {
        if p.get("action").is_some() || p.get("step").is_some() {
            return Err(bad(cmd, "select a set or an action step, not both"));
        }
        return duplicate_set(s, set.as_str().ok_or_else(|| bad(cmd, "set must be a name"))?);
    }
    let idx = resolve(s.actions.list.actions(), p, cmd)?;
    if let Some(step) = index(p, "step", cmd)? {
        let len = s.actions.list.step_count(idx).saturating_add(pending_steps(s, idx).count());
        if step >= len {
            return Err(bad(cmd, "step is out of range"));
        }
        if s.actions.recording.is_some_and(|(_, i)| i == idx) {
            flush_recording(s)?;
        }
        s.actions.list.duplicate_step(idx, step).map_err(|e| list_error(cmd, e))?;
        note_automation_edit(s, idx);
        let mut result = step_result(s, idx, step + 1);
        result["index"] = json!(idx);
        return Ok(result);
    }
    if s.actions.recording.is_some() {
        return Err(bad(cmd, "stop recording before duplicating an action"));
    }
    let at = s.actions.list.duplicate_action(idx, shift_action_calls).map_err(|e| list_error(cmd, e))?;
    let copy = &s.actions.list.actions()[at];
    Ok(json!({"action": copy.name, "index": at, "steps": copy.steps.len()}))
}

/// Copy the named group represented by main, including a session-only empty New Set.
fn duplicate_set(s: &mut Session, source: &str) -> Result<Value> {
    let cmd = "actions.duplicate";
    if s.actions.recording.is_some() {
        return Err(bad(cmd, "stop recording before duplicating a set"));
    }
    let sets = set_names(s);
    if !sets.iter().any(|name| name == source) {
        return Err(bad(cmd, "the selected set no longer exists"));
    }
    let name = s.actions.list.duplicate_set(source, shift_action_calls).map_err(|e| list_error(cmd, e))?;
    let copies = s.actions.list.actions().iter().filter(|action| action.set.as_deref() == Some(name.as_str())).count();
    match s.actions.list.actions().iter().position(|action| action.set.as_deref() == Some(name.as_str())) {
        Some(at) => Ok(json!({"set": name, "index": at, "actions": copies})),
        None => Ok(json!({"set": name, "actions": 0})),
    }
}

/// The panel's dialog toggle column. With `step`, switch one step's dialog on or off; without
/// it, every step (all on unless all already are, like clicking the action's own toggle).
fn dialog(s: &mut Session, p: &Value) -> Result<Value> {
    let cmd = "actions.dialog";
    not_playing(s, cmd)?;
    let idx = resolve(s.actions.list.actions(), p, cmd)?;
    let enabled = match p.get("enabled") {
        None | Some(Value::Null) => None,
        Some(Value::Bool(b)) => Some(*b),
        Some(_) => return Err(bad(cmd, "`enabled` must be true or false")),
    };
    let step = index(p, "step", cmd)?;
    let len = s.actions.list.step_count(idx).saturating_add(pending_steps(s, idx).count());
    if step.is_some_and(|step| step >= len) {
        return Err(bad(cmd, "step is out of range"));
    }
    if s.actions.recording.is_some_and(|(_, i)| i == idx) {
        flush_recording(s)?;
    }
    let action = &s.actions.list.actions()[idx];
    // One step, or every step: on unless all already are.
    let edits: Vec<(usize, bool)> = match step {
        Some(step) => vec![(step, enabled.unwrap_or(!action.dialogs.contains(&step)))],
        None => {
            let on = enabled.unwrap_or(action.dialogs.len() < action.steps.len());
            (0..action.steps.len()).map(|step| (step, on)).collect()
        }
    };
    for (step, on) in edits {
        s.actions.list.set_dialog(idx, step, on).map_err(|e| list_error(cmd, e))?;
    }
    let action = &s.actions.list.actions()[idx];
    Ok(json!({"action": action.name, "dialogs": action.dialogs}))
}

fn assign_set(s: &mut Session, p: &Value) -> Result<Value> {
    let cmd = "actions.assignSet";
    not_playing(s, cmd)?;
    let idx = resolve(s.actions.list.actions(), p, cmd)?;
    let set = match p.get("set") {
        None | Some(Value::Null) => None,
        Some(Value::String(n)) if !n.trim().is_empty() => Some(n.trim().to_string()),
        Some(Value::String(_)) => return Err(bad(cmd, "`set` is empty; pass null to take the action out of its set")),
        Some(_) => return Err(bad(cmd, "`set` must be a name or null")),
    };
    s.actions.list.assign_set(idx, set).map_err(|e| list_error(cmd, e))?;
    let action = &s.actions.list.actions()[idx];
    Ok(json!({"action": action.name, "set": action.set}))
}

/// Every set name, in the Actions panel's order: the sets of the actions as they first appear,
/// then the empty ones New Set made.
pub fn set_names(s: &Session) -> Vec<String> {
    s.actions.list.sets().into_iter().map(str::to_owned).collect()
}

/// New Set…: an empty set folder, named `name` or "Set N" (the first number no set has), that New
/// Action can record into.
fn new_set(s: &mut Session, p: &Value) -> Result<Value> {
    let cmd = "actions.newSet";
    not_playing(s, cmd)?;
    let names = set_names(s);
    let name = match p.get("name") {
        None | Some(Value::Null) => (1u32..).map(|n| format!("Set {n}")).find(|n| !names.contains(n)).ok_or_else(|| bad(cmd, "no free set name"))?,
        Some(Value::String(n)) if !n.trim().is_empty() => n.trim().to_string(),
        Some(Value::String(_)) => return Err(bad(cmd, "`name` is empty")),
        Some(_) => return Err(bad(cmd, "`name` must be a string")),
    };
    if names.contains(&name) {
        return Err(bad(cmd, format!("a set named `{name}` already exists")));
    }
    s.actions.list.new_set(&name).map_err(|e| list_error(cmd, e))?;
    Ok(json!({"set": name}))
}

/// The conditions of Photoshop's Insert Conditional, by their string ids.
pub const CONDITIONS: &[&str] = &[
    "always",
    "never",
    "isOpen",
    "landscape",
    "square",
    "portrait",
    "modeIsRGB",
    "modeIsCMYK",
    "modeIsGrayscale",
    "modeIsLab",
    "modeIsBitmap",
    "modeIsIndexed",
    "modeIsDuotone",
    "modeIsMultichannel",
    "depth8",
    "depth16",
    "depth32",
    "unsaved",
    "hasSelection",
    "hasLayers",
    "hasAlphaChannels",
    "isBackground",
    "isPixelLayer",
    "isAdjustmentLayer",
    "isShapeLayer",
    "isTypeLayer",
    "isSmartObject",
    "isLayerGroup",
    "isLocked",
    "isVisible",
    "hasPixelMask",
    "hasVectorMask",
    "hasEffects",
];

/// Whether `condition` holds for the active document and layer. Layer conditions are false
/// without a document or an active layer; `isOpen` is whether a document is open.
pub fn evaluate(s: &Session, condition: &str) -> Result<bool> {
    use photocraft_color::ColorMode;
    use photocraft_doc::LayerContent;
    if !CONDITIONS.contains(&condition) {
        return Err(bad("actions.conditional", format!("unknown condition `{condition}` ({})", CONDITIONS.join("|"))));
    }
    let Some(d) = s.active() else { return Ok(condition == "always") };
    let doc = &d.doc;
    let layer = d.active_layer.and_then(|id| doc.layer(id));
    let (w, h) = (doc.size.width, doc.size.height);
    Ok(match condition {
        "always" | "isOpen" => true,
        "never" => false,
        "landscape" => w > h,
        "square" => w == h,
        "portrait" => h > w,
        "modeIsRGB" => doc.mode == ColorMode::Rgb,
        "modeIsCMYK" => doc.mode == ColorMode::Cmyk,
        "modeIsGrayscale" => doc.mode == ColorMode::Grayscale,
        "modeIsLab" => doc.mode == ColorMode::Lab,
        "modeIsBitmap" => doc.mode == ColorMode::Bitmap,
        "modeIsIndexed" => doc.mode == ColorMode::Indexed,
        "modeIsDuotone" => doc.mode == ColorMode::Duotone,
        "modeIsMultichannel" => doc.mode == ColorMode::Multichannel,
        "depth8" => doc.depth == photocraft_color::SampleType::U8,
        "depth16" => doc.depth == photocraft_color::SampleType::U16,
        "depth32" => doc.depth == photocraft_color::SampleType::F32,
        "unsaved" => d.is_dirty(),
        "hasSelection" => doc.selection.is_some(),
        // More than a lone Background: any layer that isn't the background.
        "hasLayers" => doc.walk().iter().any(|(_, _, l)| !doc.is_background(l.id)),
        "hasAlphaChannels" => !doc.channels.is_empty(),
        "isBackground" => layer.is_some_and(|l| doc.is_background(l.id)),
        "isPixelLayer" => layer.is_some_and(|l| matches!(l.content, LayerContent::Raster(_)) && !doc.is_background(l.id)),
        "isAdjustmentLayer" => layer.is_some_and(|l| matches!(l.content, LayerContent::Adjustment(_))),
        "isShapeLayer" => layer.is_some_and(|l| matches!(l.content, LayerContent::Shape(_))),
        "isTypeLayer" => layer.is_some_and(|l| matches!(l.content, LayerContent::Text(_))),
        "isSmartObject" => layer.is_some_and(|l| matches!(l.content, LayerContent::Smart(_))),
        "isLayerGroup" => layer.is_some_and(|l| l.is_group()),
        "isLocked" => layer.is_some_and(|l| l.locks.all || l.locks.pixels || l.locks.position || l.locks.transparency),
        "isVisible" => layer.is_some_and(|l| l.visible),
        "hasPixelMask" => layer.is_some_and(|l| l.mask.is_some()),
        "hasVectorMask" => layer.is_some_and(|l| l.vector_mask.is_some()),
        "hasEffects" => layer.is_some_and(|l| !l.effects.items.is_empty()),
        _ => false,
    })
}

/// Photoshop's Insert Conditional as a step: test the condition, play `then` or `else`.
fn conditional(s: &mut Session, p: &Value) -> Result<Value> {
    let cmd = "actions.conditional";
    let condition = match p.get("if") {
        Some(Value::String(c)) => c.clone(),
        _ => return Err(bad(cmd, format!("needs `if`, one of {}", CONDITIONS.join("|")))),
    };
    let branch = |key: &str| -> Result<Option<String>> {
        match p.get(key) {
            None | Some(Value::Null) => Ok(None),
            Some(Value::String(n)) if !n.trim().is_empty() => Ok(Some(n.clone())),
            Some(Value::String(_)) => Ok(None),
            Some(_) => Err(bad(cmd, format!("`{key}` must be an action name or null"))),
        }
    };
    let (then, otherwise) = (branch("then")?, branch("else")?);
    let holds = evaluate(s, &condition)?;
    let played = if holds { then } else { otherwise };
    let mut out = json!({"if": condition, "holds": holds, "played": played});
    if let Some(name) = played {
        let r = s.execute("actions.play", json!({"action": name}))?;
        if let Some(f) = r.get("failed") {
            out["failed"] = f.clone();
        }
        out["ran"] = r.get("ran").cloned().unwrap_or(json!(0));
        out["action"] = json!(name);
    }
    Ok(out)
}

pub fn specs() -> Vec<CommandSpec> {
    vec![
        CommandSpec {
            id: "actions.clearAll",
            label: "Clear All Actions",
            menu: &[],
            shortcut: None,
            params: r#"{"confirm":true} → {cleared}. Removes every action and set, empty ones included, and the action shortcuts. Undo with actions.undoLibrary."#,
            enabled: library_commands::enabled,
            run: library_commands::clear,
            journal: false,
        },
        CommandSpec {
            id: "actions.reset",
            label: "Reset Actions…",
            menu: &[],
            shortcut: None,
            params: r#"{"confirm":true,"mode":"replace"|"append"} → {set,appended,actions:[names]}. Restores the PhotoCraft Basics set; appended beside a set of that name it gets a numbered name."#,
            enabled: library_commands::enabled,
            run: library_commands::reset,
            journal: false,
        },
        CommandSpec {
            id: "actions.undoLibrary",
            label: "Undo Actions Library Change",
            menu: &[],
            shortcut: None,
            params: "{} → {undone}. Restores the library and action shortcuts from before the latest Clear All, Reset or Replace without editing document History.",
            enabled: library_commands::undo_enabled,
            run: library_commands::undo,
            journal: false,
        },
        CommandSpec {
            id: "actions.insertMenuItem",
            label: "Insert Menu Item…",
            menu: &[],
            shortcut: None,
            params: r##"{"action":name|index,"id":menu command,"at":index?,"eventKind":"name"|"code"="name"} → {action,step,id,steps}. Records an unambiguous supported menu event without settings. Image Size and mapped filter menu events are supported. Desktop playback opens the existing editor when settings are needed; no-settings items run immediately."##,
            enabled: always,
            run: insert_menu_item,
            journal: false,
        },
        CommandSpec {
            id: "actions.insertPath",
            label: "Insert Path",
            menu: &[],
            shortcut: None,
            params: r##"{"action":name|index,"name":"work"|"layer"|saved path name,"at":index?} → {action,step,id,steps}. Snapshot exactly the selected path as a path.set work-path step, preserving cubic handles and path options. No fallback from a missing Work Path to a layer path. The measured Work Path ATN descriptor supports absolute coordinates, cubic handles, even-odd subpaths and Add/Subtract/XOR. Paths outside that measured form still play natively and are reported as unsupported by ATN export."##,
            enabled: always,
            run: insert_path::run,
            journal: false,
        },
        CommandSpec {
            id: "actions.allowToolRecording",
            label: "Allow Tool Recording",
            menu: &[],
            shortcut: None,
            params: r##"{"enabled":bool?=toggle} → {enabled:bool}. Opt in to recording painting-tool strokes (off initially). Existing pending steps are committed under the previous mode. Painting, history and the journal are unchanged. actions.list reports toolRecording."##,
            enabled: always,
            run: allow_tool_recording,
            journal: false,
        },
        CommandSpec {
            id: "actions.recordAgain",
            label: "Record Again",
            menu: &[],
            shortcut: None,
            params: r##"{"action":name|index,"step":index,"params":{new settings},"revision":u64?} → {action,step,id,result}. Replays the selected command and stores its new settings only after success, preserving its enabled/dialog flags. The panel opens the command's editor at the recorded settings. Stop recording or playback first; revision optionally rejects stale library state."##,
            enabled: always,
            run: record_again::run,
            journal: false,
        },
        CommandSpec {
            id: "actions.duplicate",
            label: "Duplicate Action",
            menu: &[],
            shortcut: None,
            params: r##"{"action":name|index,"step":index?} or {"set":name} → {action?,index?,step?,steps?,set?,actions?}. Copy an action, step or named set below the source. Copies retain settings and flags, and leave shortcuts with the originals."##,
            enabled: always,
            run: duplicate,
            journal: false,
        },
        CommandSpec {
            id: "actions.insert",
            label: "Insert Step",
            menu: &[],
            shortcut: None,
            params: r##"{"action":name|index, "id":command id, "params":{}?, "at":index?=end} → {action, step, id, steps}. Inserts a step at the 0-based position (the reference application's Insert Stop… with id actions.stopMessage, its dialog toggle on; Insert Menu Item… with any command). Pending recorded steps count; flags of the steps after it follow them."##,
            enabled: always,
            run: insert,
            journal: false,
        },
        CommandSpec {
            id: "actions.dialog",
            label: "Toggle Step Dialog",
            menu: &[],
            shortcut: None,
            params: r##"{"action":name|index, "step":index?, "enabled":bool?} → {action, dialogs:[step…]}. The Actions panel's dialog toggle: the desktop shell shows the step's dialog, seeded with its recorded params, and resumes playback when it is confirmed; headless playback runs the recorded params. Omitted enabled flips it; without step, every step: on unless all already are, or as enabled says."##,
            enabled: always,
            run: dialog,
            journal: false,
        },
        CommandSpec {
            id: "actions.conditional",
            label: "Conditional",
            menu: &[],
            shortcut: None,
            params: r##"{"if":condition, "then":action name|null, "else":action name|null} → {if, holds, played, ran?, failed?}. Photoshop's Insert Conditional: conditions always|never|isOpen|landscape|square|portrait|modeIsRGB|modeIsCMYK|modeIsGrayscale|modeIsLab|modeIsBitmap|modeIsIndexed|modeIsDuotone|modeIsMultichannel|depth8|depth16|depth32|unsaved|hasSelection|hasLayers|hasAlphaChannels|isBackground|isPixelLayer|isAdjustmentLayer|isShapeLayer|isTypeLayer|isSmartObject|isLayerGroup|isLocked|isVisible|hasPixelMask|hasVectorMask|hasEffects (layer conditions test the active layer). The branch plays as actions.play does; its failure stops the calling action."##,
            enabled: always,
            run: conditional,
            journal: true,
        },
        CommandSpec {
            id: "actions.assignSet",
            label: "Move to Set",
            menu: &[],
            shortcut: None,
            params: r##"{"action":name|index, "set":name|null} → {action, set}. The set folder the Actions panel shows the action under (what Load Actions fills and Save Actions writes); null takes it out of any set."##,
            enabled: always,
            run: assign_set,
            journal: false,
        },
        CommandSpec {
            id: "actions.newSet",
            label: "New Set",
            menu: &[],
            shortcut: None,
            params: r##"{"name":str? (default "Set N")} → {set}. An empty set folder in the Actions panel, as Photoshop's New Set… makes; New Action records into the selected set (actions.record's `set`). Save Actions… (actions.save's `set`) writes it even while empty, and the preset store keeps it between sessions."##,
            enabled: always,
            run: new_set,
            journal: false,
        },
    ]
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::actions_cmds::Action;

    fn session_with(steps: &[&str]) -> Session {
        let mut s = Session::new();
        s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
        s.actions.list.push(Action::new("A", steps.iter().map(|id| ActionStep::new(*id, json!({}))).collect())).unwrap();
        s
    }

    #[test]
    fn insert_places_the_step_and_shifts_the_flags() {
        let mut s = session_with(&["select.all", "select.inverse", "select.deselect"]);
        s.execute("actions.toggle", json!({"action": "A", "step": 1})).unwrap();
        s.execute("actions.dialog", json!({"action": "A", "step": 2})).unwrap();
        let r = s
            .execute("actions.insert", json!({"action": "A", "at": 1, "id": "actions.stopMessage", "params": {"message": "Check", "allowContinue": true}}))
            .unwrap();
        assert_eq!((r["step"].as_u64(), r["steps"].as_u64()), (Some(1), Some(4)));
        let a = &s.actions.list.actions()[0];
        assert_eq!(a.steps[1], ActionStep::new("actions.stopMessage", json!({"message": "Check", "allowContinue": true})));
        assert_eq!(a.disabled.iter().copied().collect::<Vec<_>>(), [2], "the switched-off step moved down one");
        assert_eq!(a.dialogs.iter().copied().collect::<Vec<_>>(), [1, 3], "the inserted Stop's dialog is on; the old toggle moved down one");
        // Default position: the end. A bare id works for a parameterless command.
        let r = s.execute("actions.insert", json!({"action": 0, "id": "layer.new.layer"})).unwrap();
        assert_eq!(r["step"], 4);
        assert_eq!(s.actions.list.actions()[0].steps[4].command, "layer.new.layer");
        // Playback runs the inserted stop and continues past it.
        let played = s.execute("actions.play", json!({"action": "A"})).unwrap();
        assert_eq!(played["ran"], 4, "{played}");
        assert!(played.get("failed").is_none(), "{played}");
    }

    #[test]
    fn insert_while_recording_keeps_pending_steps_in_order() {
        let mut s = session_with(&[]);
        s.execute("actions.record", json!({"action": "A"})).unwrap();
        s.execute("layer.new.layer", json!({"name": "One"})).unwrap();
        s.execute("actions.insert", json!({"action": "A", "at": 0, "id": "select.all"})).unwrap();
        s.execute("layer.new.layer", json!({"name": "Two"})).unwrap();
        s.execute("actions.stop", json!({})).unwrap();
        let ids: Vec<&str> = s.actions.list.actions()[0].steps.iter().map(|step| step.command.as_str()).collect();
        assert_eq!(ids, ["select.all", "layer.new.layer", "layer.new.layer"]);
    }

    #[test]
    fn dialog_toggles_one_step_or_all() {
        let mut s = session_with(&["select.all", "select.inverse"]);
        assert_eq!(s.execute("actions.dialog", json!({"action": "A", "step": 0})).unwrap()["dialogs"], json!([0]));
        assert_eq!(s.execute("actions.dialog", json!({"action": "A", "step": 0})).unwrap()["dialogs"], json!([]));
        assert_eq!(s.execute("actions.dialog", json!({"action": "A", "step": 1, "enabled": true})).unwrap()["dialogs"], json!([1]));
        assert_eq!(s.execute("actions.dialog", json!({"action": "A"})).unwrap()["dialogs"], json!([0, 1]), "not all on: all on");
        assert_eq!(s.execute("actions.dialog", json!({"action": "A"})).unwrap()["dialogs"], json!([]), "all on: all off");
        assert_eq!(s.execute("actions.dialog", json!({"action": "A", "enabled": true})).unwrap()["dialogs"], json!([0, 1]));
        assert_eq!(s.execute("actions.get", json!({"action": "A"})).unwrap()["dialogs"], json!([0, 1]));
        // Deleting a step keeps the flags of the others in place.
        s.execute("actions.delete", json!({"action": "A", "step": 0})).unwrap();
        assert_eq!(s.actions.list.actions()[0].dialogs.iter().copied().collect::<Vec<_>>(), [0]);
    }

    #[test]
    fn conditional_tests_the_document_and_plays_a_branch() {
        let mut s = session_with(&[]);
        s.actions.list.push(Action::new("Yes", vec![ActionStep::new("layer.new.layer", json!({"name": "yes"}))])).unwrap();
        s.actions.list.push(Action::new("No", vec![ActionStep::new("layer.new.layer", json!({"name": "no"}))])).unwrap();
        let names = |s: &Session| s.active().unwrap().doc.walk().iter().map(|(_, _, l)| l.name.clone()).collect::<Vec<_>>();
        // 8 × 8: square, not landscape; one Background: no layers yet.
        for (cond, expect) in [
            ("square", true),
            ("landscape", false),
            ("portrait", false),
            ("modeIsRGB", true),
            ("modeIsCMYK", false),
            ("depth8", true),
            ("hasLayers", false),
            ("hasSelection", false),
            ("isBackground", true),
            ("isPixelLayer", false),
            ("hasEffects", false),
            ("always", true),
            ("never", false),
            ("isOpen", true),
        ] {
            assert_eq!(evaluate(&s, cond).unwrap(), expect, "{cond}");
        }
        let r = s.execute("actions.conditional", json!({"if": "square", "then": "Yes", "else": "No"})).unwrap();
        assert_eq!((r["holds"].as_bool(), r["played"].as_str(), r["ran"].as_u64()), (Some(true), Some("Yes"), Some(1)));
        assert_eq!(names(&s).last().map(String::as_str), Some("yes"));
        for (cond, expect) in [("hasLayers", true), ("isPixelLayer", true), ("isBackground", false), ("isVisible", true)] {
            assert_eq!(evaluate(&s, cond).unwrap(), expect, "{cond}");
        }
        let r = s.execute("actions.conditional", json!({"if": "landscape", "then": "Yes", "else": "No"})).unwrap();
        assert_eq!((r["holds"].as_bool(), r["played"].as_str()), (Some(false), Some("No")));
        assert_eq!(names(&s).last().map(String::as_str), Some("no"));
        // No branch for the outcome: nothing plays, no error.
        let r = s.execute("actions.conditional", json!({"if": "landscape", "then": "Yes"})).unwrap();
        assert!(r["played"].is_null());
        // A failing branch reports like a nested Play, and stops a calling action.
        s.actions.list.push(Action::new("Bad", vec![ActionStep::new("layer.delete", json!({"layer": 999}))])).unwrap();
        let r = s.execute("actions.conditional", json!({"if": "always", "then": "Bad"})).unwrap();
        assert!(r["failed"].is_object(), "{r}");
        assert!(crate::actions_cmds::nested_failure("actions.conditional", &r).is_some());
        s.actions
            .list
            .push(Action::new(
                "Caller",
                vec![
                    ActionStep::new("actions.conditional", json!({"if": "always", "then": "Bad"})),
                    ActionStep::new("layer.new.layer", json!({"name": "after"})),
                ],
            ))
            .unwrap();
        let played = s.execute("actions.play", json!({"action": "Caller"})).unwrap();
        assert_eq!(played["failed"]["step"], 0, "{played}");
        assert_ne!(names(&s).last().map(String::as_str), Some("after"));
        // Without a document only always/never answer; layer conditions are false.
        let t = Session::new();
        assert!(evaluate(&t, "always").unwrap());
        assert!(!evaluate(&t, "isOpen").unwrap());
        assert!(!evaluate(&t, "isBackground").unwrap());
        for p in [json!({}), json!({"if": "sometimes"}), json!({"if": 3}), json!({"if": "always", "then": 5}), json!({"if": "always", "then": "Nope"})] {
            assert!(
                s.execute("actions.conditional", p.clone()).is_err() || s.execute("actions.conditional", p.clone()).unwrap().get("failed").is_some(),
                "{p}"
            );
        }
    }

    #[test]
    fn new_set_makes_an_empty_folder_that_new_actions_record_into() {
        let mut s = session_with(&["select.all"]);
        s.execute("actions.assignSet", json!({"action": "A", "set": "Set 1"})).unwrap();
        // Numbered past the sets the actions already have.
        assert_eq!(s.execute("actions.newSet", json!({})).unwrap()["set"], "Set 2");
        assert_eq!(s.execute("actions.newSet", json!({"name": " Retouch "})).unwrap()["set"], "Retouch");
        assert_eq!(set_names(&s), ["Set 1", "Set 2", "Retouch"]);
        // CodeRabbit on batch 11: Actions List names the empty sets too, so an agent can find them.
        assert_eq!(s.execute("actions.list", json!({})).unwrap()["sets"], json!(["Set 1", "Set 2", "Retouch"]));
        assert!(s.execute("actions.newSet", json!({"name": "Set 1"})).is_err(), "a set an action is in");
        assert!(s.execute("actions.newSet", json!({"name": "Retouch"})).is_err(), "an empty set");
        assert!(s.execute("actions.newSet", json!({"name": " "})).is_err());
        // New Action into the empty set.
        let r = s.execute("actions.record", json!({"set": "Retouch"})).unwrap();
        s.execute("actions.stop", json!({})).unwrap();
        let i = r["index"].as_u64().unwrap() as usize;
        assert_eq!(s.actions.list.actions()[i].set.as_deref(), Some("Retouch"));
        assert_eq!(set_names(&s), ["Set 1", "Retouch", "Set 2"], "Retouch now holds an action");
        assert!(s.execute("actions.record", json!({"set": 3})).is_err());
    }

    #[test]
    fn assign_set_moves_an_action_between_folders() {
        let mut s = session_with(&["select.all"]);
        assert_eq!(s.execute("actions.assignSet", json!({"action": "A", "set": " Retouch "})).unwrap()["set"], "Retouch");
        assert_eq!(s.actions.list.actions()[0].set.as_deref(), Some("Retouch"));
        assert_eq!(s.execute("actions.list", json!({})).unwrap()["actions"][0]["set"], "Retouch");
        assert_eq!(s.execute("actions.assignSet", json!({"action": 0, "set": null})).unwrap()["set"], Value::Null);
        assert_eq!(s.actions.list.actions()[0].set, None);
    }

    #[test]
    fn bad_params_fail_gracefully() {
        let mut s = session_with(&["select.all"]);
        let before = s.actions.list.clone();
        for p in [
            json!({}),
            json!({"action": "A"}),
            json!({"action": "A", "id": ""}),
            json!({"action": "A", "id": 5}),
            json!({"action": "A", "id": "not.a.command"}),
            json!({"action": "A", "id": "select.all", "at": 2}),
            json!({"action": "A", "id": "select.all", "at": -1}),
            json!({"action": "A", "id": "select.all", "params": "x"}),
            json!({"action": "A", "id": "actions.play", "params": {"action": "A"}}),
            json!({"action": 9, "id": "select.all"}),
        ] {
            assert!(s.execute("actions.insert", p.clone()).is_err(), "{p}");
        }
        for p in
            [json!({}), json!({"action": "A", "step": 1}), json!({"action": "A", "step": "x"}), json!({"action": "A", "enabled": "yes"}), json!({"action": 3})]
        {
            assert!(s.execute("actions.dialog", p.clone()).is_err(), "{p}");
        }
        for p in [json!({}), json!({"action": "A", "set": ""}), json!({"action": "A", "set": 7}), json!({"action": "B", "set": "S"})] {
            assert!(s.execute("actions.assignSet", p.clone()).is_err(), "{p}");
        }
        assert_eq!(s.actions.list, before, "rejected edits change nothing");
        // Nothing edits during playback.
        s.actions.list.push(Action::new("Loop", vec![ActionStep::new("actions.insert", json!({"action": "A", "id": "select.all"}))])).unwrap();
        let played = s.execute("actions.play", json!({"action": "Loop"})).unwrap();
        assert!(played["failed"]["error"].as_str().unwrap().contains("playback"), "{played}");
    }

    fn record_conditional(width: u32, height: u32) -> (Session, usize) {
        let mut s = Session::new();
        s.execute("file.new", json!({"width": width, "height": height})).unwrap();
        s.actions.list.push(Action::new("Tall", vec![ActionStep::new("layer.new.layer", json!({"name": "Tall"}))])).unwrap();
        let layers = s.active().unwrap().doc.walk().len();
        s.execute("actions.record", json!({"name": "Parent"})).unwrap();
        s.execute("actions.conditional", json!({"if": "portrait", "then": "Tall", "else": null})).unwrap();
        s.execute("actions.stop", json!({})).unwrap();
        (s, layers)
    }

    fn parent_steps(s: &Session) -> Vec<ActionStep> {
        s.actions.list.actions().iter().find(|a| a.name == "Parent").unwrap().steps.clone()
    }

    #[test]
    fn recording_a_conditional_keeps_the_step_when_no_branch_runs() {
        let (mut s, layers) = record_conditional(8, 4);
        let expected = vec![ActionStep::new("actions.conditional", json!({"if": "portrait", "then": "Tall", "else": null}))];
        assert_eq!(parent_steps(&s), expected);
        assert_eq!(s.active().unwrap().doc.walk().len(), layers, "the false predicate runs no branch");
        s.execute("file.new", json!({"width": 4, "height": 8})).unwrap();
        let before = s.active().unwrap().doc.walk().len();
        let played = s.execute("actions.play", json!({"action": "Parent"})).unwrap();
        assert_eq!(played["ran"], 1, "{played}");
        let doc = &s.active().unwrap().doc;
        assert_eq!(doc.walk().len(), before + 1);
        assert!(doc.walk().iter().any(|(_, _, l)| l.name == "Tall"));
    }

    #[test]
    fn recording_a_conditional_keeps_the_predicate_when_a_branch_runs() {
        let (s, layers) = record_conditional(4, 8);
        let expected = vec![ActionStep::new("actions.conditional", json!({"if": "portrait", "then": "Tall", "else": null}))];
        assert_eq!(parent_steps(&s), expected, "no nested actions.play is recorded");
        assert_eq!(s.active().unwrap().doc.walk().len(), layers + 1, "the true predicate runs Tall");
    }
}