GitCorner

Code

ossartcraftphotocraft🌐
856f865cf98d
//! Photoshop Actions files (`.atn`): Load Actions (`actions.load`) and Save Actions
//! (`actions.save`), plus the two step commands a Photoshop set needs: `actions.stopMessage`
//! (Photoshop's Insert Stop) and `actions.photoshopStep` (a step PhotoCraft has no command for
//! yet, kept verbatim so Save Actions writes it back unchanged).
//!
//! Parsing and writing live in `craft-psd` (`atn`); this module maps Photoshop *events*
//! (`gaussianBlur` with `Rds`, `make` of an adjustment layer, `set` of the selection…) onto
//! PhotoCraft commands and back. An event is keyed by both its four-character code (`GsnB`,
//! older files) and its string name (`gaussianBlur`, Photoshop 2024 and later), as the two are
//! interchangeable in Photoshop. The table ([`EVENTS`]) is bidirectional: a step that was
//! imported exports to the same event. Events outside it become `actions.photoshopStep` steps,
//! which fail at playback with the step's Photoshop name, so an action never silently skips
//! work; tool selections and other steps with no document effect are imported switched off.
//!
//! Layer references by name (`select` of layer "Shadow") become `{"layer": "Shadow"}`, which
//! `commands::layer_param` resolves in whatever document the action plays on (#219). A switch
//! to another open document (`select` of `Dcmn` by offset) becomes `document.activate
//! {"offset"}`, the document that many places from the active one in opening order, not dragged
//! tab order (#7103).

use craft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem};
use craft_psd::descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D};
use serde_json::{Map, Value, json};

use crate::actions_cmds::Action;
use crate::commands::CommandSpec;
use crate::{EngineError, Result, Session};

mod adjustments;
mod convert;
mod descriptors;
mod events;
mod fields;
mod files;
mod menu_item;

mod steps_artboard;
mod steps_artboard_section;
mod steps_automate;
mod steps_batch;
mod steps_calculations;
mod steps_channels;
mod steps_content_aware;
mod steps_direct_adjustments;
mod steps_distort;
mod steps_doc;
mod steps_droplet;
mod steps_frame_section;
mod steps_gallery;
mod steps_gradient;
mod steps_image;
mod steps_layer;
mod steps_layer_style;
mod steps_lookup;
mod steps_make;
mod steps_measurement;
mod steps_mode_change;
mod steps_path;
mod steps_perspective_warp;
mod steps_type_path;

mod steps_other;
mod steps_render;
mod steps_selection;
mod steps_shape_blur;
mod steps_stack;
mod steps_stylize;
mod steps_video;
mod tables;

#[cfg(test)]
use adjustments::{levels_from, selective_from};
pub use convert::{Imported, Skipped, Unsupported, export, function_key_name, import, import_with_encoding, parse_function_key};
#[cfg(test)]
use convert::{MAX_NAME_CHARS, export_item, normalise};
#[cfg(test)]
use descriptors::{
    PCT, PT, PX, ang, class, class_ref, code, color_desc, color_hex, desc, enm, get_bool, get_enum, get_list, get_num, get_obj, get_ref, layer_ref, long,
    name_ref, path_text, path_value, pct, px, target_ref, text, trimmed,
};
use descriptors::{jbool, jstr};
#[cfg(test)]
use events::{EVENTS, event_and_descriptor, event_for};
#[cfg(test)]
use fields::Mapped;
use files::{load, save};
pub use menu_item::{MENU_ITEM, menu_item_command, menu_item_commands, menu_item_needs_settings};
#[cfg(test)]
use steps_doc::crop_from;
pub(crate) use steps_gallery::RECORDED_EVENT;
#[cfg(test)]
use steps_image::{apply_image_from, transform_to};
#[cfg(test)]
use steps_layer::quick_mask_ref;
#[cfg(test)]
use steps_make::make_from;
#[cfg(test)]
use tables::{blend_label, blend_ps, channel_ref};

/// A step PhotoCraft cannot play yet, kept verbatim (`{"event", "name", "descriptor": base64}`).
pub const PHOTOSHOP_STEP: &str = "actions.photoshopStep";
/// Photoshop's Insert Stop: `{"message", "allowContinue"}`.
pub const STOP_MESSAGE: &str = "actions.stopMessage";
/// The set name Save Actions uses for actions that came from no set.
pub const DEFAULT_SET: &str = "PhotoCraft Actions";

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(())
}

fn stop_message(_: &mut Session, p: &Value) -> Result<Value> {
    let message = jstr(p, "message").unwrap_or("Stop").to_string();
    if jbool(p, "allowContinue").unwrap_or(false) {
        Ok(json!({"message": message, "continued": true}))
    } else {
        Err(EngineError::Other(format!("stopped by the action: {message}")))
    }
}

fn photoshop_step_run(_: &mut Session, p: &Value) -> Result<Value> {
    let name = jstr(p, "name").filter(|n| !n.is_empty()).unwrap_or("this step");
    let event = jstr(p, "event").unwrap_or("?");
    Err(EngineError::Other(format!("Photoshop step \"{name}\" ({event}) has no PhotoCraft equivalent yet; switch it off in the Actions panel to skip it")))
}

pub use files::validate_replacement;

pub fn specs() -> Vec<CommandSpec> {
    vec![
        CommandSpec {
            id: "actions.replace",
            label: "Replace Actions…",
            menu: &[],
            shortcut: None,
            params: r#"{"path":".atn file"?,"data":base64?,"confirm":true,"encoding":label?} → {sets,actions,warnings,unsupported}. Replaces the whole library with every set of the ATN archive (a set name or action name the archive repeats gets a numbered name) and the action shortcuts with its function keys. Undo with actions.undoLibrary."#,
            enabled: crate::actions_edit_cmds::library_change_enabled,
            run: files::replace,
            journal: false,
        },
        CommandSpec {
            id: "actions.load",
            label: "Load Actions…",
            menu: &[],
            shortcut: None,
            params: r##"{"path":".atn file"?,"data":base64 bytes?,"set":name? (override the file's set name),"replace":bool=true (replace the actions of a set of the same name),"encoding":"auto"|label="auto" (the encoding of 8-bit step names: shift_jis, gbk, big5, euc-kr, windows-1252, macintosh…; auto works it out)} → {set, actions:[names], steps, unsupported:[{action, step, event, name}], functionKeys:[{action, key}], warnings, encoding}. Photoshop steps PhotoCraft cannot play become actions.photoshopStep steps (kept for Save Actions; they fail at playback with the step's name); tool selections and other steps with no document effect are imported switched off. Layer references by name replay in any document."##,
            enabled: always,
            run: load,
            journal: false,
        },
        CommandSpec {
            id: "actions.save",
            label: "Save Actions…",
            menu: &[],
            shortcut: None,
            params: r##"{"path":".atn file"? (else the bytes come back as base64 `data`),"set":name? (that set's actions, none for an empty New Set set; default: every action, as the set "PhotoCraft Actions"),"action":name|index? (one action),"skipUnsupported":bool=false (leave out steps with no Photoshop equivalent instead of failing)} → {set, actions:[names], steps, bytes, skipped:[{action, step, id}], path|data}"##,
            enabled: always,
            run: save,
            journal: false,
        },
        CommandSpec {
            id: STOP_MESSAGE,
            label: "Stop",
            menu: &[],
            shortcut: None,
            params: r##"{"message":str,"allowContinue":bool=false} (Photoshop's Insert Stop: a step that shows the message; headless playback continues when allowContinue is set and otherwise stops the action with the message)"##,
            enabled: always,
            run: stop_message,
            journal: true,
        },
        CommandSpec {
            id: MENU_ITEM,
            label: "Menu Item",
            menu: &[],
            shortcut: None,
            params: r##"{"id":menu command,"eventKind":"name"|"code"="name"} (a descriptor-free Image Size or unambiguous mapped filter menu event; desktop playback asks for settings when needed, headless playback only runs stateless menu items)"##,
            enabled: always,
            run: menu_item::run,
            journal: true,
        },
        CommandSpec {
            id: PHOTOSHOP_STEP,
            label: "Photoshop Step",
            menu: &[],
            shortcut: None,
            params: r##"{"event":id,"name":str,"descriptor":base64?} (a step from a .atn file PhotoCraft has no command for: fails at playback, written back by actions.save)"##,
            enabled: always,
            run: photoshop_step_run,
            journal: true,
        },
    ]
}

#[cfg(test)]
mod tests;

#[cfg(test)]
mod layer_props_tests;

#[cfg(test)]
mod layer_list_tests;

#[cfg(test)]
mod automate_tests;

#[cfg(test)]
mod stylize_tests;

#[cfg(test)]
mod measurement_tests;

#[cfg(test)]
mod selection_tests;

#[cfg(test)]
mod render_tests;

#[cfg(test)]
mod frame_section_tests;

#[cfg(test)]
mod recorded_tools_tests;

#[cfg(test)]
mod mode_change_tests;

#[cfg(test)]
mod artboard_section_tests;

#[cfg(test)]
mod fade_step_tests;

#[cfg(test)]
#[path = "atn_cmds/canvas_size_default_anchor_tests.rs"]
mod canvas_size_default_anchor_tests;