GitCorner

Code

ossartcraftvectorcraft🌐
2bc41aeb8602
use super::{
    CommandSpec, DRAWS_SHAPE, EngineError, JOURNALED_READS, NodeId, Result, SELECTS_GIVEN_IDS, Selection, Session, TAKES_GUIDE_IDS, Value, cmd,
    find_command, given_ids, guard, strip_replay_only, waits_for_tool_edit,
};

/// A command's result `r` with the warnings of the previews that settling an interaction applied
/// before it ran: `previewWarning` holds them, and `warning` too when the command gives none of its
/// own, so the status bar shows the command's own warning when there is one. A null result becomes
/// an object holding them; any other result that isn't an object is returned as it is.
fn with_settled_warnings(mut r: Value, settled: &[String]) -> Value {
    if settled.is_empty() {
        return r;
    }
    if r.is_null() {
        r = Value::Object(serde_json::Map::new());
    }
    if let Value::Object(m) = &mut r {
        let w = Value::String(settled.join("; "));
        if m.get("warning").is_none_or(Value::is_null) {
            m.insert("warning".into(), w.clone());
        }
        m.insert("previewWarning".into(), w);
    }
    r
}

impl Session {
    /// `spec`'s `enabled` with `ids` selected instead of the selection, which is then put back.
    fn enabled_with_selection(&mut self, spec: &CommandSpec, ids: Vec<NodeId>) -> std::result::Result<(), String> {
        let Some(d) = self.active_mut() else { return (spec.enabled)(self) };
        let old = std::mem::replace(&mut d.selection, Selection { objects: ids, ..Selection::default() });
        let r = (spec.enabled)(self);
        if let Some(d) = self.active_mut() {
            d.selection = old;
        }
        r
    }

    /// Error, under the command's own id, at the first of `ids` that is malformed, else at the first
    /// that names no node or names a layer or sublayer: a command in [`SELECTS_GIVEN_IDS`] acts on
    /// objects.
    fn check_given_ids(&self, id: &str, params: &Value) -> Result<()> {
        let (Some(st), Some(ids)) = (self.active(), params.get("ids")) else { return Ok(()) };
        let Some(given) = ids.as_array() else { return cmd::checked_ids_param(self, params, "ids", id).map(drop) };
        // A malformed entry anywhere in the list is refused first, under the key and the entry.
        cmd::ids_param(params, "ids", id)?;
        for value in given {
            let node = cmd::checked_id(self, value, id)?;
            if st.doc.node(node).is_some_and(|n| n.is_layer()) {
                return Err(if id.starts_with("object.arrange.") {
                    cmd::bad(id, format!("id {value} is a layer, not an object; move layers with layer.move"))
                } else {
                    cmd::bad(id, format!("id {value} is a layer, not an object"))
                });
            }
        }
        Ok(())
    }

    /// Execute a command by id. This is THE entry point for every frontend.
    pub fn execute(&mut self, id: &str, params: &Value) -> Result<Value> {
        let spec = find_command(id).ok_or_else(|| cmd::params::unknown_command(id))?;
        // A clipboard import is a query that replaces the clipboard, which the end of a run sets too.
        if self.depth == 0 && self.script_key.is_some() && (waits_for_tool_edit(id) || id.starts_with("clipboard.import")) {
            return Err(EngineError::Busy);
        }
        // A step of a batch a script runs is held to the same rule as the script's own commands.
        if self.script_in_run && crate::script::refused_to_scripts(id) {
            return Err(EngineError::Other(crate::script::refused_text(id)));
        }
        // An edit the active tool is computing on another thread (a Shape Builder merge) is
        // applied before a command that may edit, select, save or give a document a new revision,
        // as the click came first. Queries that only read do not wait for it.
        if self.depth == 0 && waits_for_tool_edit(id) {
            self.finish_tool_edit_later()?;
        }
        let outer = std::mem::replace(&mut self.reading, !spec.journal || JOURNALED_READS.contains(&id));
        // A preview that a top-level command applied first (a drag with Real-time Drawing off, kept
        // before Undo) reports its warning in the command's result.
        let r = if self.depth == 0 {
            let (r, settled) = self.collect_settled_warnings(|s| s.execute_spec(spec, id, params));
            r.map(|v| with_settled_warnings(v, &settled))
        } else {
            self.execute_spec(spec, id, params)
        };
        self.reading = outer;
        r
    }

    fn execute_spec(&mut self, spec: &'static CommandSpec, id: &str, params: &Value) -> Result<Value> {
        // A key the command's params description doesn't name is a parameter error (#1442), before
        // anything runs, for the commands other commands run too. A `command.batch` or an
        // `action.batch` checks its steps before the first one runs, and each step is checked again
        // as it runs, against the document the steps before it left (the effects `effect.setParams`
        // edits). Saved steps played with `replay` aren't checked.
        if !self.replaying {
            self.check_params(id, params)?;
        }
        // A command with a parameter schema runs only with params that pass it, and with the
        // defaults of omitted values filled in; the journal keeps the params as given. Saved steps
        // keep their keys the schema doesn't name, as above.
        let checked = crate::schemas::check(spec, params, self.replaying)?;
        let run_params = checked.as_ref().unwrap_or(params);
        // Objects given as `id` (where it stands for `ids` of one) or as `ids` beside it are checked
        // before anything else: a malformed one, or one naming no object, is an error under this
        // command's id, never the selection in its place. `effect.apply {id: "stylize.dropShadow"}`
        // without `effect` names the effect (its older key), not an object.
        let effect_named = id == "effect.apply"
            && params.get("effect").is_none()
            && params.get("ids").is_none_or(Value::is_null)
            && params.get("id").and_then(Value::as_str).is_some_and(|e| !e.starts_with('$'));
        if cmd::params::id_stands_for_ids(spec.params) && !effect_named && self.active().is_some() {
            // `effect.refreshDeferred` looks its objects up itself: they can also be in the art of
            // a symbol, pattern, brush or opacity mask.
            if id == "effect.refreshDeferred" {
                cmd::given_object_ids(params, id)?;
            } else {
                cmd::given_nodes(self, params, id, TAKES_GUIDE_IDS.contains(&id))?;
            }
        }
        if SELECTS_GIVEN_IDS.contains(&id) {
            self.check_given_ids(id, params)?;
        }
        // An `ids` list with an entry that is not an object id, or an `ids` that is not a list, is
        // refused under the command's id before the menu check, which would otherwise run on the
        // other entries or on the selection. This holds with no document open too, where commands
        // such as `effect.list` still run.
        if cmd::params::takes_key(spec.params, "ids") {
            cmd::ids_param(params, "ids", id)?;
        }
        // Clear's menu needs a selection; an agent supplying explicit targets only needs a
        // document. The command validates those targets before making any edit. Cut and Copy given
        // the artboards the journal recorded need only a document too, whatever is selected and
        // whichever tool is chosen.
        let given = given_ids(spec.params, params);
        // The guide commands take ruler guides by index; an object command given one's id is refused.
        if !TAKES_GUIDE_IDS.contains(&id)
            && let (Some(ids), Some(st)) = (&given, self.active())
            && let Some(guide) = ids.iter().find(|i| st.doc.node(**i).is_some_and(|n| n.is_ruler_guide()))
        {
            let value = guide.0;
            return Err(cmd::bad(id, format!("id {value} is a ruler guide, not an object")));
        }
        let enabled = if (id == "edit.clear" && params.get("ids").is_some())
            || (matches!(id, "edit.copy" | "edit.cut") && params.get("selectedArtboards").is_some())
        {
            cmd::has_doc(self)
        } else if let Some(ids) = given.clone() {
            // Objects given as `ids` (or `id`) stand in for the selection: the command is enabled
            // as it is with them selected (#1575).
            self.enabled_with_selection(spec, ids)
        } else {
            (spec.enabled)(self)
        };
        if let Err(why) = enabled {
            return Err(EngineError::Disabled(id.to_string(), why));
        }
        // Only top-level commands are journaled (commands that call other commands would otherwise
        // be recorded twice and replay differently).
        if self.depth == 0 {
            self.journal_note.clear();
            self.note_depth = 1;
            self.journal_query = false;
            self.batch_stash = None;
            self.batch_steps = None;
        }
        // A selection-only command given `ids` (or `id`) selects them first, in the same undo step
        // (#2130); when the command then fails, the selection (and the current layer selecting
        // them made current) goes back to how it was, as when the ids are refused.
        let select_first = SELECTS_GIVEN_IDS
            .contains(&id)
            .then(|| {
                params.get("ids").filter(|v| !v.is_null()).cloned().or_else(|| given.map(|ids| ids.iter().map(|i| i.0).collect::<Vec<_>>().into()))
            })
            .flatten();
        let selected_before = select_first.as_ref().and(self.active()).map(|d| (d.uid, d.selection.clone(), d.active_layer));
        // Only a selection command that changes the selection loads its paints for new art: other
        // commands, and clicking what is already selected, keep a sampled paint in the proxies.
        let selection_was = (id.starts_with("select.") || id == "layer.target").then(|| self.active().map(|d| d.selection.clone())).flatten();
        let run = |s: &mut Session| {
            if let Some(ids) = &select_first {
                s.execute("select.set", &serde_json::json!({ "ids": ids }))?;
            }
            let r = cmd::run_spec(s, spec, run_params);
            if r.is_err()
                && let Some((uid, selection, layer)) = selected_before
                && let Some(st) = s.docs.iter_mut().find(|d| d.uid == uid)
            {
                st.selection = selection;
                st.active_layer = layer;
                st.revision += 1;
            }
            r
        };
        // The entries the command journals belong to the undo groups of the documents it edits, and to
        // the group of the document it starts in when it ends there too.
        let (doc, journal, grouped) = (self.active().map(|d| d.uid), self.journal.len(), self.undo_group_docs());
        let open = (self.depth == 0).then(|| self.docs.iter().map(|d| d.uid).collect::<Vec<_>>());
        let r = if self.depth == 0 { self.run_guarded(id, run) } else { self.run_nested(run) };
        // Colors are drawn and converted through the profiles of the document in front now, also
        // after an undone or redone Assign Profile, a failed or panicked command's documents put
        // back, and a batch step, before the next step converts through them.
        self.sync_front_profiles();
        if r.is_err() && self.depth == 0 {
            self.batch_paint_docs.clear();
            // A failed or panicked command's documents are put back: type is drawn in their
            // composite fonts again, not in those the command set.
            cmd::compositefonts::sync(self);
        }
        let r = r?;
        if self.depth == 0 {
            // A color-mode history step restores exact new-art colors; selection inheritance
            // must not immediately replace that restoration.
            let restored = self.active().is_some_and(|d| match id {
                "edit.undo" => d.history.redo.last().is_some_and(|e| e.color_mode_paints.is_some()),
                "edit.redo" => d.history.undo.last().is_some_and(|e| e.color_mode_paints.is_some()),
                _ => false,
            });
            if !restored {
                self.inherit_new_art();
                if selection_was.is_some_and(|was| self.active().is_some_and(|d| d.selection != was)) {
                    self.load_selection_paints();
                }
            }
            for uid in std::mem::take(&mut self.batch_paint_docs) {
                if let Some(st) = self.docs.iter_mut().find(|d| d.uid == uid)
                    && let Some(e) = st.history.undo.last_mut()
                    && let Some((_, after)) = &mut e.color_mode_paints
                {
                    after.clone_from(&self.paint);
                    e.recost_paints();
                    st.history.trim();
                }
            }
        }
        if let Some(open) = open {
            self.open_undo_groups_in_new_documents(&open);
            // Type is drawn in the composite fonts of the documents open now, an undone or opened
            // document's included.
            cmd::compositefonts::sync(self);
        }
        let journaled = spec.journal || (self.depth == 0 && std::mem::take(&mut self.journal_query));
        if journaled && self.depth == 0 && self.active().is_none_or(|d| d.interaction.is_none()) {
            let p = self.noted(params);
            self.note_shape_drawn(id, &p);
            self.journal.push((id.to_string(), p));
        }
        if self.depth == 0 {
            self.journal_in_undo_groups(doc, &grouped, journal);
            self.trim_histories();
            self.after_command(Some(id));
        } else if matches!(id, "edit.undo" | "edit.redo") {
            // A step of `command.batch`: the tool hears of it as it does of the command alone.
            self.notify_text_tool(id);
        }
        Ok(r)
    }

    /// Is the interface in Japanese? Then new type starts with em box top-to-top leading and em
    /// box centre character alignment (#432).
    pub fn japanese_interface(&self) -> bool {
        self.ui_language.as_deref().unwrap_or(&self.prefs.interface_language).eq_ignore_ascii_case("ja")
    }

    /// Record `key: value` in the running top-level command's journal entry (or its interaction's
    /// preview, or its step in a batch) unless its params give `key` (a null gives nothing): a value
    /// it resolved from the preferences or the clock.
    pub fn note_journal(&mut self, key: &str, value: Value) {
        if self.depth == self.note_depth {
            self.journal_note.insert(key.to_string(), value);
        }
    }

    /// Journal the running query command when it is the top-level command: it changed the
    /// selection (`document.find {select: true}`), so an action recorded around it repeats that.
    pub(crate) fn journal_query(&mut self) {
        if self.depth == 1 {
            self.journal_query = true;
        }
    }

    /// Run `id` as a step of the running command, which journals its steps (`command.batch`):
    /// → the step's result and its params with what it noted ([`Session::note_journal`]), for the
    /// step in the running command's journal entry.
    pub(crate) fn execute_step(&mut self, id: &str, params: &Value) -> Result<(Value, Value)> {
        let outer = (std::mem::take(&mut self.journal_note), self.note_depth);
        self.note_depth = self.depth + 1;
        let r = self.execute(id, params);
        let noted = self.noted(params);
        (self.journal_note, self.note_depth) = outer;
        Ok((r?, noted))
    }

    /// [`Session::execute`] for saved steps: a journal entry or an action's steps, recorded by this
    /// version or an older one. Keys a command's params description doesn't name (a key it no longer
    /// reads, an effect parameter it no longer takes) are taken, by the commands it runs too, so what
    /// was recorded still plays (#1442). Everything else is checked as `execute` checks it.
    pub fn replay(&mut self, id: &str, params: &Value) -> Result<Value> {
        let outer = self.set_replaying(true);
        let r = self.execute(id, params);
        self.set_replaying(outer);
        r
    }

    /// Whether [`Session::execute`] plays saved steps as [`Session::replay`] does. A frontend that
    /// runs saved steps through its own path to `execute` sets it around that call, and puts back the
    /// value this returns, which it had before.
    pub fn set_replaying(&mut self, on: bool) -> bool {
        std::mem::replace(&mut self.replaying, on)
    }

    /// Whether saved steps are playing ([`Session::set_replaying`]).
    pub fn replaying(&self) -> bool {
        self.replaying
    }

    /// Note that journal entry `id` with `params` drew a shape ([`DRAWS_SHAPE`], also on the active
    /// perspective plane as `perspective.draw` naming one, and as a step of `command.batch`), unless
    /// saved steps are playing or a script runs.
    pub(crate) fn note_shape_drawn(&mut self, id: &str, params: &Value) {
        let shape = |id: &str| DRAWS_SHAPE.contains(&id);
        let draws = |id: &str, params: Option<&Value>| {
            shape(id) || (id == "perspective.draw" && params.and_then(|p| p.get("command")).and_then(Value::as_str).is_some_and(shape))
        };
        let in_batch = || {
            params.get("commands").and_then(Value::as_array).is_some_and(|steps| {
                steps.iter().any(|step| step.get("command").and_then(Value::as_str).is_some_and(|c| draws(c, step.get("params"))))
            })
        };
        if !self.replaying && !self.script_in_run && (draws(id, Some(params)) || (id == "command.batch" && in_batch())) {
            self.shape_drawn = true;
        }
    }

    /// Whether a shape was drawn since the last call: a drag of a shape tool that was committed, OK
    /// in its dialog, or a [`DRAWS_SHAPE`] command (alone or as a batch step). Saved steps that play
    /// ([`Session::replay`]) and a script's commands do not count. A frontend that shows the
    /// Transform panel after a new shape asks this.
    pub fn take_shape_drawn(&mut self) -> bool {
        std::mem::take(&mut self.shape_drawn)
    }

    /// The journal from entry `start` on, as an action records it: without the params that only
    /// pin a replay to the original run ([`REPLAY_ONLY`]), so playing the action later acts now.
    pub fn journal_for_action(&self, start: usize) -> Vec<(String, Value)> {
        self.journal
            .since(start)
            .iter()
            .cloned()
            .map(|(id, mut p)| {
                strip_replay_only(&id, &mut p);
                (id, p)
            })
            .collect()
    }

    /// `params` with the noted values added (see [`Session::note_journal`]).
    pub(super) fn noted(&mut self, params: &Value) -> Value {
        let mut note = std::mem::take(&mut self.journal_note);
        match params {
            // The params' own values win, except a null: it reads as a key left out, so the
            // noted value is the one the command resolved.
            Value::Object(m) if !note.is_empty() => {
                for (k, v) in m {
                    if !v.is_null() || !note.contains_key(k) {
                        note.insert(k.clone(), v.clone());
                    }
                }
                Value::Object(note)
            }
            Value::Null if !note.is_empty() => Value::Object(note),
            _ => params.clone(),
        }
    }

    pub(crate) fn run_nested(&mut self, f: impl FnOnce(&mut Self) -> Result<Value>) -> Result<Value> {
        self.depth += 1;
        let r = f(self);
        self.depth -= 1;
        r
    }

    /// A top-level command: a panic (a bug) becomes [`EngineError::Internal`] and every open
    /// document goes back to how it was before the command (its art, selection, interaction and
    /// undo history), and the same document stays active, instead of crashing the frontend.
    pub(crate) fn run_guarded(&mut self, id: &str, f: impl FnOnce(&mut Self) -> Result<Value>) -> Result<Value> {
        // In a script's run a panic ends the run, and the run's rollback puts the histories back.
        let in_run = self.script_in_run;
        let snapshot: Vec<_> = self
            .docs
            .iter()
            .map(|d| (d.uid, d.doc.clone(), d.selection.clone(), d.interaction.clone(), (!in_run).then(|| d.history.clone())))
            .collect();
        let active = self.active().map(|d| d.uid);
        let r = match guard::catch_panic(|| self.run_nested(f)) {
            Ok(r) => r,
            Err(msg) => {
                self.depth = 0;
                self.journal_note.clear();
                for (uid, doc, selection, interaction, history) in snapshot {
                    // A document the command closed stays closed.
                    let Some(st) = self.docs.iter_mut().find(|d| d.uid == uid) else { continue };
                    st.doc = doc;
                    st.selection = selection;
                    st.interaction = interaction;
                    if let Some(history) = history {
                        st.history = history;
                    }
                    cmd::globaledit::follow_history(st);
                    st.drop_stale_variables_highlight();
                    st.revision += 1;
                }
                if let Some(i) = active.and_then(|uid| self.docs.iter().position(|d| d.uid == uid)) {
                    self.active = Some(i);
                }
                Err(EngineError::Internal { cmd: id.to_string(), msg })
            }
        };
        // Undo, Redo and a failed batch bring back documents with their selections: each document
        // gets its selection's new art on a locked artboard.
        for st in &mut self.docs {
            st.sync_new_art();
        }
        r
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::with_settled_warnings;

    /// The command's own warning stays the one the status bar shows, and the settled preview's is
    /// kept beside it; a null result holds the preview's; other results are left as they are.
    #[test]
    fn settled_warnings_join_the_result() {
        let settled = ["a".to_string(), "b".to_string()];
        assert_eq!(
            with_settled_warnings(json!({"ran": 1, "warning": "own"}), &settled),
            json!({"ran": 1, "warning": "own", "previewWarning": "a; b"})
        );
        assert_eq!(with_settled_warnings(json!({"warning": null}), &settled), json!({"warning": "a; b", "previewWarning": "a; b"}));
        assert_eq!(with_settled_warnings(json!(null), &settled[..1]), json!({"warning": "a", "previewWarning": "a"}));
        assert_eq!(with_settled_warnings(json!([1]), &settled), json!([1]));
        assert_eq!(with_settled_warnings(json!({"ran": 1}), &[]), json!({"ran": 1}));
    }
}