Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 23 additions & 7 deletions crates/engine/src/cmd/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ use solidcraft_io::Format;
use super::CommandSpec;
use super::print_face;
use crate::params::{bad, bool_, num, str_, string_list};
use crate::schema::save::{SaveAsParams, SaveParams, SaveResult};
use crate::schema::{TypedContract, output_schema_for};
use crate::{EngineError, Result, Session};

pub static COMMANDS: &[CommandSpec] = &[
Expand All @@ -40,15 +42,19 @@ pub static COMMANDS: &[CommandSpec] = &[
.at("SOLID", "INSERT")
.icon("import")
.params("path: .3mf, .stl, .obj, .ply (with faces), .glb or .gltf file (its meshes join the design as mesh bodies in a new component named after the file → component, component_name, occurrence; a glTF file's node tree becomes nested components held as one rigid group until component.unlock, a mesh placed again another occurrence, its materials the bodies' appearances, and its metres millimetres); name?; up?: z|y for a glTF file (default y: glTF has Y up, so the import's component is turned a quarter turn about X, Y becoming Z → stand_up: its occurrence; z: the file's axes are kept); units?: mm|cm|m|in|ft for an STL or OBJ file, or a PLY file with faces (default mm): the unit its coordinates are in, scaled to millimetres as the file is read (a 3MF or glTF file states its own). The design keeps the millimetre mesh and not the unit, so insert the file again to try another; origin?: bool (default false: the mesh keeps its file's coordinates; true: once read, scaled and stood up, the import's occurrence is moved so the box around its bodies is centred on X and Y of the active component with its lowest point on Z = 0 → moved_to_origin: [x, y, z], the shift made)"),
CommandSpec::new("file.save", "Save", save)
CommandSpec::new("file.save", "Save", crate::checked!("file.save", save))
.icon("save")
.key("Ctrl+S")
.noundo()
.contract(&SAVE_CONTRACT)
.output(output_schema_for::<SaveResult>)
.params("path? (default: current file; a name that opens as another kind of file, such as .step, .stl or .dxf, is refused: file.export writes those); format?: container|json (default: json for .json, otherwise container); compression?: fast|compact (default: fast); cache?: bool (the evaluated model, so the design opens without rebuilding; default: true); preview?: bool (saved display meshes, default: false); overwrite?: bool (replace the design's file even though another program or computer changed it since it was opened or saved; without it that save is refused)"),
CommandSpec::new("file.save_as", "Save As", save_as)
CommandSpec::new("file.save_as", "Save As", crate::checked!("file.save_as", save_as))
.icon("save")
.key("Ctrl+Shift+S")
.noundo()
.contract(&SAVE_AS_CONTRACT)
.output(output_schema_for::<SaveResult>)
.params("path (a design file name, .sc as a rule; one that opens as another kind of file, such as .step, .stl or .dxf, is refused: file.export writes those); format?: container|json (default: json for .json, otherwise container); compression?: fast|compact (default: fast); cache?: bool (the evaluated model, so the design opens without rebuilding; default: true); preview?: bool (saved display meshes, default: false); overwrite?: bool (as file.save, when `path` is the design's own file)"),
CommandSpec::new("doc.recovery_list", "Recoverable Designs", recovery_list).icon("restore")
.noundo()
Expand Down Expand Up @@ -122,6 +128,8 @@ fn new_doc(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"name": name}))
}

const SAVE_CONTRACT: TypedContract<SaveParams> = TypedContract::new();
const SAVE_AS_CONTRACT: TypedContract<SaveAsParams> = TypedContract::new();
const EXPORT_STEP_CONTRACT: crate::schema::TypedContract<crate::schema::file::ExportStepParams> = crate::schema::TypedContract::new();
const EXPORT_STL_CONTRACT: crate::schema::TypedContract<crate::schema::file::ExportMeshParams> = crate::schema::TypedContract::new();
const EXPORT_3MF_CONTRACT: crate::schema::TypedContract<crate::schema::file::Export3mfParams> = crate::schema::TypedContract::new();
Expand Down Expand Up @@ -682,21 +690,29 @@ fn write_bytes(
s.disk = solidcraft_io::design_lock::stamp(path);
s.read_only = false;
s.mark_saved();
let mut out = json!({"path": path, "bytes": bytes.len(), "name": s.doc.name});
let mut out = SaveResult {
path: path.to_string(),
bytes: bytes.len(),
name: s.doc.name.clone(),
kept_format: None,
warnings: None,
not_kept: None,
param_warnings: Vec::new(),
};
// A newer SolidCraft's file keeps what this version can't read, and its format number. What
// couldn't go back, because the design was changed around it, is said.
if s.doc.newer_file.is_some() {
let mut lost = solidcraft_doc::newer_file::not_kept(&s.doc);
if format == "json" && s.doc.newer_file.as_ref().is_some_and(|file| file.needs_container()) {
lost.push("the parts of the file beside the design, which plain JSON has no room for: save as .sc to keep them".to_string());
}
out["kept_format"] = json!(s.doc.format);
out.kept_format = Some(s.doc.format.clone());
if !lost.is_empty() {
out["warnings"] = json!(lost.iter().map(|what| format!("Not kept: {what}. The previous file is `{path}.bak`.")).collect::<Vec<_>>());
out["not_kept"] = json!(lost);
out.warnings = Some(lost.iter().map(|what| format!("Not kept: {what}. The previous file is `{path}.bak`.")).collect());
out.not_kept = Some(lost);
}
}
Ok(out)
serde_json::to_value(out).map_err(|e| bad("file.save", e.to_string()))
}

impl Session {
Expand Down
1 change: 1 addition & 0 deletions crates/engine/src/schema/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ pub mod render_shots;
pub mod render_stage;
pub mod render_surface_resources;
pub mod render_ui;
pub mod save;
pub mod section;
pub mod sheet;
pub mod silhouette;
Expand Down
139 changes: 139 additions & 0 deletions crates/engine/src/schema/save.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
//! Contracts and result types for the commands in `cmd/file.rs` that save the design:
//! `file.save` and `file.save_as` (#13307).
//!
//! The handlers read their parameters from the raw JSON, so each key here reads as its handler
//! reads it. `file.save_as` refuses a missing, blank or over-long `path` with its own message,
//! so there `path` is optional in the type and required in the schema. `format` and
//! `compression` are text in the type: the handler refuses a word it doesn't know, whichever of
//! the two commands was called, with a message that names `file.save` (kept as it is), so the
//! schema lists the words and the handler stays the one to refuse them. Whether the path can be
//! written, or the design has moved or changed on disk, stays the handler's to check.

use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value;

use super::check::whole;
use super::motion::require;
use super::types::not_blank_pattern;

/// `file.save_as`' `path` as `path_arg` reads it: text with something in it, under 4096 bytes;
/// anything else, `null` included, is refused with the handler's message.
fn save_as_path<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
match Value::deserialize(d)? {
Value::String(s) if !s.trim().is_empty() && s.len() < 4096 => Ok(Some(s)),
_ => Err(D::Error::custom(whole("`path` is required"))),
}
}

fn save_as_path_schema(_: &mut SchemaGenerator) -> Schema {
json_schema!({"type": "string", "pattern": not_blank_pattern(), "maxLength": 4095})
}

fn path_required(schema: &mut Schema) {
require(schema, "path");
}

fn format_schema(_: &mut SchemaGenerator) -> Schema {
json_schema!({"type": "string", "enum": ["container", "json"]})
}

fn compression_schema(_: &mut SchemaGenerator) -> Schema {
json_schema!({"type": "string", "enum": ["fast", "compact"]})
}

/// Write the design to a file and make that file the design's own: the next `file.save` writes
/// it again. With no `path`, the design's current file is written; a design that has none yet
/// needs a `path`. A name that opens as another kind of file (`.step`, `.stl`, `.dxf` and the
/// like) is refused: `file.export` writes those. Not an undo step.
#[derive(Debug, Deserialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct SaveParams {
/// The design file to write. Default: the design's current file. A blank value counts as
/// left out.
#[serde(default)]
pub path: Option<String>,
/// container (`.sc`) or json. Default: json for a path ending in `.json`, otherwise
/// container. The handler refuses any other word.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(schema_with = "format_schema")]
pub format: Option<String>,
/// fast or compact. Default: fast. The handler refuses any other word.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(schema_with = "compression_schema")]
pub compression: Option<String>,
/// Keep the evaluated model in the file, so the design opens without rebuilding. Default:
/// true. Plain json has no room for it.
#[serde(default)]
pub cache: Option<bool>,
/// Keep the display meshes in the file. Default: false.
#[serde(default)]
pub preview: Option<bool>,
/// Replace the design's file even though another program or computer changed it since it was
/// opened or saved; without it that save is refused. Only matters when the path is the
/// design's own file. Default: false.
#[serde(default)]
pub overwrite: Option<bool>,
}

/// Write the design to a new file (a design file name, `.sc` as a rule) and make that file the
/// design's own. A name that opens as another kind of file (`.step`, `.stl`, `.dxf` and the like)
/// is refused: `file.export` writes those. A design with no name of its own, or one borrowed from
/// the file it was saved as before, takes the new file's name. Not an undo step.
#[derive(Debug, Deserialize, JsonSchema)]
#[schemars(deny_unknown_fields, transform = path_required)]
pub struct SaveAsParams {
// Optional in the type and required in the schema (`path_required`).
/// The design file to write: text, not blank, under 4096 bytes.
#[serde(default, deserialize_with = "save_as_path", skip_serializing_if = "Option::is_none")]
#[schemars(schema_with = "save_as_path_schema")]
pub path: Option<String>,
/// container (`.sc`) or json. Default: json for a path ending in `.json`, otherwise
/// container. The handler refuses any other word.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(schema_with = "format_schema")]
pub format: Option<String>,
/// fast or compact. Default: fast. The handler refuses any other word.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(schema_with = "compression_schema")]
pub compression: Option<String>,
/// Keep the evaluated model in the file, so the design opens without rebuilding. Default:
/// true. Plain json has no room for it.
#[serde(default)]
pub cache: Option<bool>,
/// Keep the display meshes in the file. Default: false.
#[serde(default)]
pub preview: Option<bool>,
/// As for `file.save`, when `path` is the design's own file: replace it even though another
/// program or computer changed it. Default: false.
#[serde(default)]
pub overwrite: Option<bool>,
}

/// What `file.save` and `file.save_as` return.
#[derive(Debug, Serialize, JsonSchema)]
pub struct SaveResult {
/// The file written.
pub path: String,
/// Its size in bytes.
pub bytes: usize,
/// The design's name once saved (a design with no name of its own takes the file's).
pub name: String,
/// A file a newer SolidCraft saved: the format number it keeps.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kept_format: Option<String>,
/// A newer file: what could not be kept, in sentences, when something could not.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub warnings: Option<Vec<String>>,
/// A newer file: what could not be kept, one item each, when something could not.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub not_kept: Option<Vec<String>>,
/// In the warn parameter-check mode: what the call's parameters got wrong.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub param_warnings: Vec<String>,
}

#[cfg(test)]
#[path = "save_tests.rs"]
mod tests;
Loading
Loading