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
2 changes: 2 additions & 0 deletions assets/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -572,6 +572,7 @@
"cmd.drawing_dimension_add": "Add Drawing Dimension",
"cmd.drawing_dimension_edit": "Edit Drawing Dimension",
"cmd.drawing_dimension_inspect": "Inspect Drawing Dimension",
"cmd.drawing_export": "Export Sheet",
"cmd.drawing_inspect": "Inspect Drawing",
"cmd.drawing_list": "List Drawings",
"cmd.drawing_open": "Open Drawing",
Expand All @@ -581,6 +582,7 @@
"cmd.drawing_revision_add": "Add Revision",
"cmd.drawing_revision_delete": "Delete Revision",
"cmd.drawing_revision_edit": "Edit Revision",
"cmd.drawing_scene": "Draw Sheet",
"cmd.drawing_set": "Drawing Settings",
"cmd.drawing_sheet_add": "Add Sheet",
"cmd.drawing_sheet_delete": "Delete Sheet",
Expand Down
2 changes: 2 additions & 0 deletions assets/locales/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -572,6 +572,7 @@
"cmd.drawing_dimension_add": "図面寸法を追加",
"cmd.drawing_dimension_edit": "図面寸法を編集",
"cmd.drawing_dimension_inspect": "図面寸法を確認",
"cmd.drawing_export": "シートを書き出す",
"cmd.drawing_inspect": "図面を確認",
"cmd.drawing_list": "図面を一覧表示",
"cmd.drawing_open": "図面を開く",
Expand All @@ -581,6 +582,7 @@
"cmd.drawing_revision_add": "リビジョンを追加",
"cmd.drawing_revision_delete": "リビジョンを削除",
"cmd.drawing_revision_edit": "リビジョンを編集",
"cmd.drawing_scene": "シートを描画",
"cmd.drawing_set": "図面設定",
"cmd.drawing_sheet_add": "シートを追加",
"cmd.drawing_sheet_delete": "シートを削除",
Expand Down
2 changes: 2 additions & 0 deletions assets/locales/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -572,6 +572,7 @@
"cmd.drawing_dimension_add": "添加绘图尺寸",
"cmd.drawing_dimension_edit": "编辑绘图尺寸",
"cmd.drawing_dimension_inspect": "检查绘图尺寸",
"cmd.drawing_export": "导出图纸",
"cmd.drawing_inspect": "检查绘图",
"cmd.drawing_list": "列出绘图",
"cmd.drawing_open": "打开绘图",
Expand All @@ -581,6 +582,7 @@
"cmd.drawing_revision_add": "添加版本",
"cmd.drawing_revision_delete": "删除版本",
"cmd.drawing_revision_edit": "编辑版本",
"cmd.drawing_scene": "绘制图纸",
"cmd.drawing_set": "绘图设置",
"cmd.drawing_sheet_add": "添加图纸",
"cmd.drawing_sheet_delete": "删除图纸",
Expand Down
87 changes: 87 additions & 0 deletions crates/engine/src/cmd/drawing_export.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
//! `drawing.export` (#4890 A7): one sheet of the open drawing written out from its scene
//! ([`crate::drawing_scene::build`]), the scene the sheet page draws, so a file shows what the page
//! does. SVG for now: PNG comes with the sheet PNG writer (#4890 A4) and DXF with the shared DXF
//! writer (#5319). A sheet with a view that failed isn't written; the refusal names the views.

use std::path::Path;

use serde_json::Value;
use solidcraft_doc::ids;

use super::CommandSpec;
use crate::drawing_scene::{Status, sheet_id};
use crate::params::bad;
use crate::schema::drawing_export::{ExportFormat, ExportParams, ExportReport, ExportResult};
use crate::schema::{TypedContract, output_schema_for};
use crate::{EngineError, Result, Session};

const CMD: &str = "drawing.export";
const CONTRACT: TypedContract<ExportParams> = TypedContract::new();
/// The longest path taken, in bytes, as the view DXF's.
const MAX_PATH_BYTES: usize = 4096;

pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new(CMD, "Export Sheet", crate::checked!("drawing.export", CONTRACT, export))
.icon("export")
.in_drawing()
.noundo()
.doc_only()
.contract(&CONTRACT)
.output(output_schema_for::<ExportResult>)
.params("sheet: id or name; format?: svg (default; png and dxf are not supported yet); path?: .svg file (else the reply holds the SVG text) → {sheet, format, bytes, path | svg, report: {widths_snapped, pieces_merged}, views: [{view, status: drawn|placeholder|failed, reason?, stats?}]}. The sheet as drawing.scene draws it: its drawing border, then each view's visible lines. Refused, naming them, while any view on the sheet failed; a placeholder view draws nothing. No model is evaluated.")];

fn export(s: &mut Session, p: &Value) -> Result<Value> {
let request: ExportParams = crate::schema::read(CMD, p)?;
match request.format {
ExportFormat::Svg => {}
ExportFormat::Png => return Err(bad(CMD, "not supported yet: PNG needs the sheet PNG writer (#4890 A4)")),
ExportFormat::Dxf => return Err(bad(CMD, "not supported yet: DXF needs the shared DXF writer (#5319)")),
}
if let Some(path) = &request.path {
let svg = Path::new(path).extension().is_some_and(|e| e.eq_ignore_ascii_case("svg"));
if path.len() > MAX_PATH_BYTES || !svg {
return Err(bad(CMD, "path must be a .svg file"));
}
solidcraft_io::vfs::check(path).map_err(|e| EngineError::Other(e.to_string()))?;
}
let d = s.drawing(CMD)?.clone();
let sheet = sheet_id(&d, &request.sheet, CMD)?;
let built = crate::drawing_scene::build(s, &d, sheet)?;
let failed: Vec<String> = built
.views
.iter()
.filter_map(|v| match &v.status {
Status::Failed(why) => Some(format!("{} ({why})", ids::encode(v.view))),
_ => None,
})
.collect();
if !failed.is_empty() {
return Err(bad(CMD, format!("not written: views on the sheet failed: {}", failed.join(", "))));
}
let prepared = built.scene.prepare().map_err(|e| bad(CMD, e.to_string()))?;
let (svg, written) = solidcraft_io::paper::paper_svg(&prepared).map_err(|e| bad(CMD, e.to_string()))?;
let bytes = svg.len();
let (path, svg) = match request.path {
Some(path) => {
// Checked again just before writing, as the view DXF does.
solidcraft_io::vfs::check(&path).map_err(|e| EngineError::Other(e.to_string()))?;
solidcraft_io::write_atomic(Path::new(&path), &svg, false).map_err(|e| EngineError::Other(e.to_string()))?;
(Some(path), None)
}
None => (None, Some(String::from_utf8(svg).map_err(|e| EngineError::Other(e.to_string()))?)),
};
let reply = ExportResult {
sheet: ids::encode(sheet),
format: request.format,
bytes,
path,
svg,
report: ExportReport { widths_snapped: written.widths_snapped, pieces_merged: written.pieces_merged },
views: built.views.into_iter().map(Into::into).collect(),
param_warnings: Vec::new(),
};
serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string()))
}

#[cfg(test)]
#[path = "drawing_export_tests.rs"]
mod tests;
119 changes: 119 additions & 0 deletions crates/engine/src/cmd/drawing_export_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
use serde_json::{Value, json};
use solidcraft_doc::MAX_PLACEMENT_DEPTH;

use super::*;
use crate::drawing_scene::tests::{front_and_top, nest};
use crate::schema::output_schema_for;
use crate::schema::tests::conforms;
use crate::tests::Folder;

fn run(s: &mut Session, id: &str, p: Value) -> Value {
s.execute(id, &p).unwrap()
}

fn refused(s: &mut Session, p: Value) -> String {
s.execute(CMD, &p).err().map(|e| e.to_string()).unwrap_or_else(|| panic!("accepted: {p}"))
}

/// The SVG of sheet `sheet` of the drawing open, written straight from its built scene.
fn scene_svg(s: &Session, sheet: u64) -> Vec<u8> {
let d = s.drawing("test").unwrap().clone();
let built = crate::drawing_scene::build(s, &d, sheet).unwrap();
solidcraft_io::paper::paper_svg(&built.scene.prepare().unwrap()).unwrap().0
}

/// A sheet exports as its scene's SVG, byte for byte, by id or by name: the reply holds it, with
/// its size and each view's status, as its schema says. Nothing changes and no model is evaluated.
#[test]
fn a_sheet_exports_as_its_scenes_svg() {
let (mut s, sheet, [front, top]) = front_and_top();
let (doc, evaluations) = (s.doc.clone(), s.evaluations);
let reply = run(&mut s, CMD, json!({"sheet": ids::encode(sheet)}));
let schema = output_schema_for::<ExportResult>();
assert!(conforms(schema.as_value(), schema.as_value(), &reply), "{reply}");
let svg = scene_svg(&s, sheet);
assert_eq!(reply["svg"].as_str().map(str::as_bytes), Some(svg.as_slice()));
assert_eq!((&reply["format"], reply["bytes"].as_u64(), reply.get("path")), (&json!("svg"), Some(svg.len() as u64), None), "{reply}");
// Each view on the sheet, in id order, as drawing.scene lists them.
let views: Vec<_> = reply["views"].as_array().unwrap().iter().map(|v| (v["view"].clone(), v["status"].clone())).collect();
let mut in_order = [front, top];
in_order.sort_unstable();
assert_eq!(views, in_order.map(|v| (json!(ids::encode(v)), json!("drawn"))));
let name = s.drawing("test").unwrap().sheets[0].name.clone();
assert_eq!(run(&mut s, CMD, json!({"sheet": name, "format": "svg"}))["svg"], reply["svg"]);
assert!(std::sync::Arc::ptr_eq(&doc, &s.doc) && s.evaluations == evaluations);
// The sheet named, not the first: a second sheet, with no views, exports as its own scene.
let added = run(&mut s, "drawing.sheet.add", json!({}));
let second = ids::decode(added["sheet"].as_str().unwrap()).unwrap();
let other = run(&mut s, CMD, json!({"sheet": ids::encode(second)}));
assert_eq!((&other["sheet"], other["views"].as_array().map(Vec::len)), (&json!(ids::encode(second)), Some(0)), "{other}");
assert_eq!(other["svg"].as_str().map(str::as_bytes), Some(scene_svg(&s, second).as_slice()));
assert_ne!(other["svg"], reply["svg"]);
}

/// With a path the file holds the same SVG and the reply names it instead.
#[test]
fn a_path_gets_the_svg_written_to_it() {
let (mut s, sheet, _) = front_and_top();
let folder = Folder::new("drawing-export");
let path = folder.path("Sheet 1.SVG");
let reply = run(&mut s, CMD, json!({"sheet": ids::encode(sheet), "path": path}));
let written = std::fs::read(&path).unwrap();
assert_eq!(written, scene_svg(&s, sheet));
assert_eq!(
(reply["path"].as_str(), reply.get("svg"), reply["bytes"].as_u64()),
(Some(path.as_str()), None, Some(written.len() as u64)),
"{reply}"
);
}

/// A view that failed stops the export, and the refusal names it with why; a placeholder draws
/// nothing and is exported all the same.
#[test]
fn a_failed_view_is_named_and_nothing_is_written() {
let (mut s, sheet, [front, top]) = front_and_top();
let folder = Folder::new("drawing-export-failed");
let path = folder.path("sheet.svg");
run(&mut s, "drawing.view.edit", json!({"view": ids::encode(top), "set": {"display_style": "shaded"}}));
let why = refused(&mut s, json!({"sheet": ids::encode(sheet), "path": path}));
assert!(why.contains(&format!("views on the sheet failed: {} (not supported yet: shaded views", ids::encode(top))), "{why}");
assert!(!why.contains(&ids::encode(front)) && !std::path::Path::new(&path).exists(), "{why}");
run(&mut s, "drawing.view.edit", json!({"view": ids::encode(top), "set": {"display_style": "visible"}}));
for level in 0..=MAX_PLACEMENT_DEPTH as u64 + 1 {
nest(&mut s, level);
}
let reply = run(&mut s, CMD, json!({"sheet": ids::encode(sheet)}));
let statuses: Vec<_> = reply["views"].as_array().unwrap().iter().map(|v| v["status"].clone()).collect();
assert_eq!(statuses, [json!("placeholder"), json!("placeholder")], "{reply}");
assert_eq!(reply["svg"].as_str().map(str::as_bytes), Some(scene_svg(&s, sheet).as_slice()));
}

/// PNG and DXF aren't supported yet; a path that isn't a `.svg` file, an unknown sheet, an unknown
/// key and no drawing open are refused, and nothing is written.
#[test]
fn what_it_cant_write_is_refused() {
let (mut s, sheet, _) = front_and_top();
let folder = Folder::new("drawing-export-refused");
let id = ids::encode(sheet);
let long = format!("{}.svg", "a".repeat(MAX_PATH_BYTES));
for (p, why) in [
(json!({"sheet": id, "format": "png"}), "not supported yet: PNG"),
(json!({"sheet": id, "format": "dxf"}), "not supported yet: DXF"),
(json!({"sheet": id, "format": "pdf"}), "format"),
(json!({"sheet": id, "path": folder.path("sheet.png")}), "path must be a .svg file"),
(json!({"sheet": id, "path": folder.path("sheet")}), "path must be a .svg file"),
(json!({"sheet": id, "path": " "}), "path must be a .svg file"),
(json!({"sheet": id, "path": long}), "path must be a .svg file"),
(json!({"sheet": id, "path": null}), "path"),
(json!({"sheet": "Sheet 9"}), "no sheet `Sheet 9`"),
(json!({"sheet": 5}), "sheet"),
(json!({}), "sheet"),
(json!({"sheet": id, "dpi": 300}), "dpi"),
] {
let message = refused(&mut s, p.clone());
assert!(message.contains(why), "{p}: {message}");
}
assert_eq!(std::fs::read_dir(&folder.0).unwrap().count(), 0);
run(&mut s, "drawing.close", json!({}));
assert!(refused(&mut s, json!({"sheet": id})).contains("open a drawing first"));
}
33 changes: 33 additions & 0 deletions crates/engine/src/cmd/drawing_scene.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
//! `drawing.scene` (#4890 W10): one sheet of the open drawing as one paper scene, drawn at once
//! ([`crate::drawing_scene::build`]): its drawing border, then each view on it by id. The sheet
//! page draws the same scene through the provider, and the drawing export (A7) writes it.

use serde_json::Value;
use solidcraft_doc::ids;

use super::CommandSpec;
use crate::drawing_scene::CMD;
use crate::schema::drawing_scene::{SheetPaperScene, SheetSceneParams, SheetSceneResult};
use crate::schema::{TypedContract, output_schema_for};
use crate::{EngineError, Result, Session};

const CONTRACT: TypedContract<SheetSceneParams> = TypedContract::new();

pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new(CMD, "Draw Sheet", crate::checked!("drawing.scene", CONTRACT, scene))
.icon("export")
.in_drawing()
.noundo()
.doc_only()
.contract(&CONTRACT)
.output(output_schema_for::<SheetSceneResult>)
.params("sheet: id or name → {sheet, scene: {size_mm, groups: [{object, kind: drawing_border|view, items: [{kind: stroke, path, closed, width_mm} or {kind: fill, region}]}]} in paint order: the sheet's drawing border (object: the sheet), then each view on it by id (object: the view; its visible lines only for now), views: [{view, status: drawn|placeholder|failed, reason?, stats?}]}. A view with nothing to measure, or one that can't be drawn yet, is left out and says why. Read-only; no model is evaluated.")];

fn scene(s: &mut Session, p: &Value) -> Result<Value> {
let request: SheetSceneParams = crate::schema::read(CMD, p)?;
let d = s.drawing(CMD)?.clone();
let sheet = crate::drawing_scene::sheet_id(&d, &request.sheet, CMD)?;
let built = crate::drawing_scene::build(s, &d, sheet)?;
let views = built.views.into_iter().map(Into::into).collect();
let reply = SheetSceneResult { sheet: ids::encode(sheet), scene: SheetPaperScene(built.scene), views, param_warnings: Vec::new() };
serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string()))
}
21 changes: 5 additions & 16 deletions crates/engine/src/cmd/drawing_view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ use crate::drawing_view::{CHORD_RANGE, Extents, Lines, MAX_PATH_IDS, MAX_PATHS,
use crate::params::bad;
use crate::schema::drawing_view::{
AccuracyResult, BoxResult, ChoicesResult, CopyParams, DPI_RANGE, EditParams, EditResult, ExtentsResult, FromResult, InspectParams, InspectResult,
LineResult, LineSourceResult, LinesStatsResult, LinesStatusResult, MoveParams, OutsideResult, PathSegResult, PieceResult, PlaceParam,
ScaleResult, SceneResult, SettingResult, SettingsResult, SnapshotParams, SnapshotResult, SourceResult, ToSheetResult, ViewResult, ViewSet,
LineResult, LineSourceResult, LinesStatusResult, MoveParams, OutsideResult, PathSegResult, PieceResult, PlaceParam, ScaleResult, SceneResult,
SettingResult, SettingsResult, SnapshotParams, SnapshotResult, SourceResult, ToSheetResult, ViewResult, ViewSet,
};
use crate::schema::{TypedContract, output_schema_for};
use crate::{Result, Session};
Expand Down Expand Up @@ -97,11 +97,8 @@ fn snapshot(s: &mut Session, p: &Value) -> Result<Value> {
let request: SnapshotParams = crate::schema::read(CMD, p)?;
let settings = request.settings();
let basis = settings.validate().map_err(|e| bad(CMD, e.to_string()))?;
if settings.display_style.is_shaded() || settings.reference_style.is_shaded() {
return Err(bad(CMD, "not supported yet: shaded views need the drawing renderer (#5624)"));
}
if request.scene && settings.display_style == VisualStyle::VisibleHidden {
return Err(bad(CMD, "not supported yet: hidden lines in the paper scene need dashed lines (#4890 A5)"));
if let Some(why) = crate::drawing_view::not_drawable(settings.display_style, settings.reference_style, request.scene) {
return Err(bad(CMD, why));
}
if !(request.sheet.dpi.is_finite() && DPI_RANGE.contains(&request.sheet.dpi)) {
return Err(bad(CMD, format!("sheet.dpi is a number from {} to {}", DPI_RANGE.start(), DPI_RANGE.end())));
Expand Down Expand Up @@ -178,15 +175,7 @@ fn snapshot(s: &mut Session, p: &Value) -> Result<Value> {
uncertain_pieces: 0,
covered_pieces: drawn.covered,
},
stats: LinesStatsResult {
bodies: drawn.stats.bodies,
shared_meshes: drawn.stats.shared_meshes,
triangles: drawn.stats.triangles,
segments: drawn.stats.segments,
prepare_ms: drawn.stats.prepare_ms,
projection_ms: drawn.stats.projection_ms,
occlusion_ms: drawn.stats.occlusion_ms,
},
stats: drawn.stats.into(),
scene,
source: SourceResult { bodies: extents.bodies, timeline_at_end: s.doc.marker.is_none() },
param_warnings: Vec::new(),
Expand Down
4 changes: 4 additions & 0 deletions crates/engine/src/cmd/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ mod diagnostics;
mod drawing;
mod drawing_balloon;
mod drawing_dimension;
mod drawing_export;
mod drawing_revision;
mod drawing_scene;
mod drawing_sheet;
mod drawing_view;
mod edit;
Expand Down Expand Up @@ -344,7 +346,9 @@ pub fn command_specs() -> Vec<&'static CommandSpec> {
v.extend(drawing::COMMANDS.iter());
v.extend(drawing_balloon::COMMANDS.iter());
v.extend(drawing_dimension::COMMANDS.iter());
v.extend(drawing_export::COMMANDS.iter());
v.extend(drawing_revision::COMMANDS.iter());
v.extend(drawing_scene::COMMANDS.iter());
v.extend(drawing_sheet::COMMANDS.iter());
v.extend(drawing_view::COMMANDS.iter());
v.extend(diagnostics::COMMANDS.iter());
Expand Down
Loading