#![allow(clippy::print_stdout)]
use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::io::{IsTerminal as _, Write as _};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use cadkit::{Color, Document, DxfVersion, Entity, EntityKind, ReadOptions, SvgOptions};
use clap::{Args, Parser, Subcommand};
#[derive(Parser, Debug)]
#[command(name = "cadkit", version, about, long_about = None)]
struct Cli {
#[arg(long, global = true)]
keep_raw: bool,
#[arg(long, global = true, value_name = "LABEL")]
codepage: Option<String>,
#[arg(long, global = true, value_name = "BYTES")]
max_input_bytes: Option<u64>,
#[arg(long, global = true, value_name = "BYTES")]
max_decompressed_bytes: Option<u64>,
#[arg(long, global = true, value_name = "N")]
max_objects: Option<u64>,
#[arg(long, global = true, value_name = "UNITS", value_parser = parse_tolerance)]
planarity_tolerance: Option<f64>,
#[command(subcommand)]
command: Command,
}
#[derive(Args, Debug, Default)]
struct TransformOptions {
#[arg(long)]
explode_inserts: bool,
#[arg(long, value_name = "UNIT")]
units: Option<String>,
#[arg(long, value_name = "NAME")]
layer: Option<String>,
#[arg(long, value_name = "KIND")]
kind: Option<String>,
}
#[derive(Subcommand, Debug)]
enum Command {
Inspect {
file: PathBuf,
#[arg(long)]
json: bool,
},
Blocks {
file: PathBuf,
#[arg(long)]
json: bool,
},
Completions {
#[arg(value_parser = ["bash", "zsh", "fish", "powershell"])]
shell: String,
},
Info {
file: PathBuf,
#[arg(long)]
warnings: bool,
#[arg(long, default_value_t = 20, value_name = "N")]
max_warnings: usize,
#[arg(long)]
json: bool,
},
Layers {
#[arg(long)]
json: bool,
file: PathBuf,
},
Convert {
input: PathBuf,
output: PathBuf,
#[arg(long, value_parser = ["json", "svg", "dxf", "dgn", "gml"])]
to: Option<String>,
#[arg(long, value_name = "LABEL")]
output_codepage: Option<String>,
#[command(flatten)]
transform: TransformOptions,
#[arg(long, default_value_t = 0, value_name = "N")]
model: usize,
#[arg(long, value_parser = parse_dxf_version, value_name = "VERSION")]
dxf_version: Option<DxfVersion>,
#[arg(long, value_parser = parse_width, value_name = "PX")]
width: Option<f64>,
#[arg(long)]
pretty: bool,
#[arg(long)]
seed: Option<PathBuf>,
#[arg(long)]
clear_seed_model: bool,
#[arg(long)]
crs: Option<String>,
#[arg(long, default_value_t = 1)]
lod: u8,
#[arg(long)]
preserve_invalid_geometry: bool,
#[arg(long)]
gml_metadata_only: bool,
},
ValidateGml {
file: PathBuf,
#[arg(long)]
tkgm_profile: Option<cadkit::gml::tkgm::Profile>,
},
RepackDgn {
input: PathBuf,
output: PathBuf,
},
Dump {
#[command(flatten)]
transform: TransformOptions,
file: PathBuf,
#[arg(long)]
json: bool,
},
}
fn parse_dxf_version(s: &str) -> Result<DxfVersion, String> {
match s.to_ascii_lowercase().as_str() {
"r12" => Ok(DxfVersion::R12),
"r2000" => Ok(DxfVersion::R2000),
"r2004" => Ok(DxfVersion::R2004),
"r2007" => Ok(DxfVersion::R2007),
"r2010" => Ok(DxfVersion::R2010),
"r2013" => Ok(DxfVersion::R2013),
"r2018" => Ok(DxfVersion::R2018),
_ => Err(format!(
"unknown DXF version `{s}` (expected r12, r2000, r2004, r2007, r2010, r2013 or r2018)"
)),
}
}
fn parse_width(s: &str) -> Result<f64, String> {
match s.parse::<f64>() {
Ok(v) if v.is_finite() && v > 0.0 => Ok(v),
_ => Err(format!(
"invalid width `{s}` (expected a positive number of pixels)"
)),
}
}
fn parse_tolerance(s: &str) -> Result<f64, String> {
match s.parse::<f64>() {
Ok(v) if v.is_finite() && v > 0.0 => Ok(v),
_ => Err(format!(
"invalid tolerance `{s}` (expected a positive number of coordinate units)"
)),
}
}
#[derive(Debug)]
enum CliError {
Usage(String),
Failure(String),
}
fn main() -> ExitCode {
let cli = match Cli::try_parse() {
Ok(cli) => cli,
Err(e) => {
let code = if e.use_stderr() { 2 } else { 0 };
let _ = e.print();
return ExitCode::from(code);
}
};
match run(&cli) {
Ok(()) => ExitCode::SUCCESS,
Err(CliError::Usage(msg)) => {
eprintln!("error: {}", clean(&msg));
ExitCode::from(2)
}
Err(CliError::Failure(msg)) => {
eprintln!("error: {}", clean(&msg));
ExitCode::from(1)
}
}
}
fn run(cli: &Cli) -> Result<(), CliError> {
match &cli.command {
Command::Inspect { file, json } => {
let options = read_options(cli);
let summary = if file == Path::new("-") {
let bytes = load_bytes(file, options.limits.max_input_bytes)?;
cadkit::inspect_with(&bytes, &options)
} else {
cadkit::inspect_file_with(file, &options)
}
.map_err(|e| failure(file, &e))?;
if *json {
print_json(&serde_json::json!(summary))?;
} else {
print_out(&strip_controls(&format!(
"Format: {:?}\nVersion: {}\n3D: {:?}\nUnits: {:?}\nCodepage: {}\nApplication: {}\n",
summary.format,
summary.version,
summary.is_3d,
summary.units,
summary.codepage.as_deref().unwrap_or("-"),
summary.application.as_deref().unwrap_or("-")
)));
}
}
Command::Blocks { file, json } => {
let doc = load(cli, file)?;
if *json {
print_json(&serde_json::json!(doc.blocks))?;
} else {
for block in &doc.blocks {
print_out(&format!(
"{}\t{} entities\n",
clean(&block.name),
block.entities.len()
));
}
}
}
Command::Completions { shell } => print_out(&completions(shell)),
Command::Info {
file,
warnings,
max_warnings,
json,
} => {
let doc = load(cli, file)?;
if *json {
print_json(&info_json(&doc))?;
} else {
print_out(&strip_controls(&info_text(
file,
&doc,
*warnings,
*max_warnings,
)));
}
}
Command::Layers { file, json } => {
let doc = load(cli, file)?;
if *json {
print_json(&serde_json::json!(doc.layers))?;
} else {
print_out(&strip_controls(&layers_text(&doc)));
}
}
Command::Convert {
input,
output,
to,
output_codepage,
transform,
model,
dxf_version,
width,
pretty,
seed,
clear_seed_model,
crs,
lod,
preserve_invalid_geometry,
gml_metadata_only,
} => {
let target = if let Some(to) = to {
OutputKind::from_path(Path::new(&format!("out.{to}")))?
} else {
OutputKind::from_path(output)?
};
if input == Path::new("-") && seed.as_deref() == Some(Path::new("-")) {
return Err(CliError::Usage(
"input and seed cannot both use stdin".into(),
));
}
if output_codepage.is_some() && !matches!(target, OutputKind::Dxf) {
return Err(CliError::Usage(
"--output-codepage requires DXF output".into(),
));
}
let options = read_options(cli);
if matches!(target, OutputKind::Gml) {
let bytes = load_bytes(input, options.limits.max_input_bytes)?;
let output_bytes = if cadkit::gml::sniff(&bytes) {
if transform.active() {
return Err(CliError::Usage(
"native GML-to-GML preservation does not support document transforms"
.into(),
));
}
if *gml_metadata_only {
return Err(CliError::Usage(
"--gml-metadata-only requires CAD input".into(),
));
}
let native = cadkit::gml::read_native(&bytes, &options)
.map_err(|e| failure(input, &e))?;
cadkit::gml::write(
&native,
&gml_validation(cli, &options, !preserve_invalid_geometry),
)
.map_err(|e| failure(output, &e))?
} else {
if *preserve_invalid_geometry {
return Err(CliError::Usage(
"--preserve-invalid-geometry requires CityGML input".into(),
));
}
let mut doc =
cadkit::read_with(&bytes, &options).map_err(|e| failure(input, &e))?;
apply_transforms(&mut doc, transform)?;
let srs_name = crs.clone().ok_or_else(|| {
CliError::Usage("new CityGML output requires --crs".into())
})?;
let (native, report) = cadkit::gml::from_document_with_report(
&doc,
&cadkit::gml::ExportOptions::new(srs_name, *lod)
.with_limits(options.limits),
if *gml_metadata_only {
cadkit::gml::UnsupportedGeometry::MetadataOnly
} else {
cadkit::gml::UnsupportedGeometry::Reject
},
)
.map_err(|e| failure(output, &e))?;
let bytes = cadkit::gml::write(&native, &gml_validation(cli, &options, true))
.map_err(|e| failure(output, &e))?;
if *gml_metadata_only {
let json =
serde_json::to_string(&report).map_err(|e| failure(output, &e))?;
eprintln!("{json}");
}
bytes
};
write_output(output, &output_bytes)?;
return Ok(());
}
if *gml_metadata_only {
return Err(CliError::Usage(
"--gml-metadata-only requires GML output".into(),
));
}
let mut doc = load(cli, input)?;
apply_transforms(&mut doc, transform)?;
if matches!(target, OutputKind::Dgn) {
let seed = seed
.as_ref()
.ok_or_else(|| CliError::Usage("DGN V8 output requires --seed".into()))?;
let bytes = load_bytes(seed, options.limits.max_input_bytes)?;
let mut options = {
let mut new_options = cadkit::dgn::WriteOptions::default()
.with_limits(options.limits)
.with_clear_seed_model(*clear_seed_model);
new_options.codepage = cli.codepage.clone();
new_options
};
if let Some(t) = cli.planarity_tolerance {
options.planarity_tolerance = t;
}
let bytes =
cadkit::to_dgn(&doc, &bytes, &options).map_err(|e| failure(output, &e))?;
write_output(output, &bytes)?;
return Ok(());
}
if matches!(target, OutputKind::Dxf) {
let opts = cadkit::dxf::WriteOptions::new(dxf_version.unwrap_or_default())
.with_codepage(output_codepage.clone());
let bytes = cadkit::to_dxf_bytes(&doc, &opts).map_err(|e| failure(output, &e))?;
write_output(output, &bytes)?;
return Ok(());
}
let text = match target {
OutputKind::Json => {
let json = cadkit::to_json(&doc, *pretty).map_err(|e| failure(output, &e))?;
if output == Path::new("-") && std::io::stdout().is_terminal() {
json_for_terminal(&json)
} else {
json
}
}
OutputKind::Svg => {
if *model >= doc.models.len() {
return Err(CliError::Usage(format!(
"model {model} does not exist (the drawing has {} models)",
doc.models.len()
)));
}
let mut options = SvgOptions::default().with_model(*model);
if let Some(w) = width {
options.width_px = *w;
}
cadkit::to_svg(&doc, &options)
}
OutputKind::Dxf => cadkit::to_dxf(&doc, dxf_version.unwrap_or_default())
.map_err(|e| failure(output, &e))?,
OutputKind::Dgn | OutputKind::Gml => {
return Err(CliError::Failure(
"unexpected binary output dispatch".into(),
));
}
};
write_output(output, text.as_bytes())?;
}
Command::ValidateGml { file, tkgm_profile } => {
let options = read_options(cli);
let bytes = load_bytes(file, options.limits.max_input_bytes)?;
let doc = cadkit::gml::read_native(&bytes, &options).map_err(|e| failure(file, &e))?;
let validation = gml_validation(cli, &options, false);
let structure =
cadkit::gml::validate(&doc, &validation).map_err(|e| failure(file, &e))?;
let issues =
cadkit::gml::geometry_issues(&doc, &validation).map_err(|e| failure(file, &e))?;
let profile = if let Some(profile) = tkgm_profile {
Some(
cadkit::gml::tkgm::preflight(&doc, *profile, &options.limits)
.map_err(|e| failure(file, &e))?,
)
} else {
None
};
let text = serde_json::to_string_pretty(
&serde_json::json!({"structure":structure,"geometry_issues":issues,"tkgm_preflight":profile}),
)
.map_err(|e| failure(file, &e))?;
print_out(&format!("{}\n", json_for_terminal(&text)));
if !issues.is_empty()
|| profile
.as_ref()
.is_some_and(|r| !r.issues.is_empty() || r.truncated)
{
return Err(CliError::Failure(
"CityGML geometry or requested profile preflight failed".into(),
));
}
}
Command::RepackDgn { input, output } => {
let options = read_options(cli);
let bytes = load_bytes(input, options.limits.max_input_bytes)?;
let bytes = cadkit::dgn::repack_v8(&bytes, &options).map_err(|e| failure(input, &e))?;
std::fs::write(output, bytes).map_err(|e| failure(output, &e))?;
}
Command::Dump {
file,
json,
transform,
} => {
let mut doc = load(cli, file)?;
apply_transforms(&mut doc, transform)?;
if *json {
let text = cadkit::to_json(&doc, true).map_err(|e| failure(file, &e))?;
print_out(&format!("{}\n", json_for_terminal(&text)));
} else {
print_out(&strip_controls(&dump_text(&doc)));
}
}
}
Ok(())
}
fn failure(path: &Path, e: &dyn std::fmt::Display) -> CliError {
CliError::Failure(format!("{}: {e}", path.display()))
}
fn load(cli: &Cli, path: &Path) -> Result<Document, CliError> {
let options = read_options(cli);
if path == Path::new("-") {
cadkit::read_from(std::io::stdin().lock(), &options).map_err(|e| failure(path, &e))
} else {
cadkit::open_with(path, &options).map_err(|e| failure(path, &e))
}
}
fn load_bytes(path: &Path, max: u64) -> Result<Vec<u8>, CliError> {
use std::io::Read;
if path == Path::new("-") {
let mut bytes = Vec::new();
std::io::stdin()
.lock()
.take(max.saturating_add(1))
.read_to_end(&mut bytes)
.map_err(|e| failure(path, &e))?;
if bytes.len() as u64 > max {
return Err(CliError::Failure("input byte limit exceeded".into()));
}
return Ok(bytes);
}
let file = std::fs::File::open(path).map_err(|e| failure(path, &e))?;
if file.metadata().map_err(|e| failure(path, &e))?.len() > max {
return Err(CliError::Failure("input byte limit exceeded".into()));
}
let mut bytes = vec![];
file.take(max.saturating_add(1))
.read_to_end(&mut bytes)
.map_err(|e| failure(path, &e))?;
if bytes.len() as u64 > max {
return Err(CliError::Failure("input byte limit exceeded".into()));
}
Ok(bytes)
}
fn gml_validation(
cli: &Cli,
options: &ReadOptions,
geometry: bool,
) -> cadkit::gml::ValidationOptions {
let mut validation = cadkit::gml::ValidationOptions::default()
.with_limits(options.limits)
.with_geometry(geometry);
if let Some(t) = cli.planarity_tolerance {
validation.planarity_tolerance = t;
}
validation
}
fn read_options(cli: &Cli) -> ReadOptions {
let mut options = {
let mut options = ReadOptions::default().with_keep_raw(cli.keep_raw);
options.fallback_codepage = cli.codepage.clone();
options
};
if let Some(v) = cli.max_input_bytes {
options.limits.max_input_bytes = v;
}
if let Some(v) = cli.max_decompressed_bytes {
options.limits.max_decompressed_bytes = v;
}
if let Some(v) = cli.max_objects {
options.limits.max_objects = v;
}
options
}
fn print_out(text: &str) {
let _ = std::io::stdout().write_all(text.as_bytes());
}
fn clean(s: &str) -> String {
s.chars()
.map(|c| if c.is_control() { '?' } else { c })
.collect()
}
fn strip_controls(text: &str) -> String {
text.chars()
.map(|c| {
if c.is_control() && c != '\n' && c != '\t' {
'?'
} else {
c
}
})
.collect()
}
fn json_for_terminal(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for c in text.chars() {
if c.is_control() && c != '\n' && c != '\t' {
let _ = write!(out, "\\u{:04x}", c as u32);
} else {
out.push(c);
}
}
out
}
#[derive(Debug, Clone, Copy)]
enum OutputKind {
Json,
Svg,
Dxf,
Dgn,
Gml,
}
impl OutputKind {
fn from_path(path: &Path) -> Result<Self, CliError> {
let ext = path
.extension()
.and_then(|e| e.to_str())
.map(str::to_ascii_lowercase);
match ext.as_deref() {
Some("json") => Ok(Self::Json),
Some("svg") => Ok(Self::Svg),
Some("dxf") => Ok(Self::Dxf),
Some("dgn") => Ok(Self::Dgn),
Some("gml") | Some("citygml") => Ok(Self::Gml),
_ => Err(CliError::Usage(format!(
"cannot choose an output format for `{}`: use .json, .svg, .dxf, .dgn or .gml (stdout requires --to)",
path.display()
))),
}
}
}
fn for_each_entity<'a>(list: &'a [Entity], depth: usize, f: &mut dyn FnMut(&'a Entity, usize)) {
for e in list {
f(e, depth);
if let EntityKind::Group { children, .. } = &e.kind {
for_each_entity(children, depth + 1, f);
}
}
}
fn num(v: f64) -> String {
if !v.is_finite() {
return "nan".to_owned();
}
let s = format!("{v:.4}");
let s = s.trim_end_matches('0').trim_end_matches('.');
if s.is_empty() || s == "-0" {
"0".to_owned()
} else {
s.to_owned()
}
}
fn color_text(c: Color) -> String {
match c {
Color::ByLayer => "bylayer".to_owned(),
Color::ByBlock => "byblock".to_owned(),
Color::Aci { index } => format!("aci {index}"),
Color::Rgb { r, g, b } => format!("#{r:02x}{g:02x}{b:02x}"),
}
}
fn info_text(file: &Path, doc: &Document, show_warnings: bool, max_warnings: usize) -> String {
let mut out = String::new();
let src = &doc.source;
let _ = writeln!(out, "File: {}", clean(&file.display().to_string()));
let _ = writeln!(out, "Format: {:?}", src.format);
let _ = writeln!(
out,
"Version: {}",
if src.version.is_empty() {
"-".to_owned()
} else {
clean(&src.version)
}
);
let _ = writeln!(
out,
"Application: {}",
clean(src.application.as_deref().unwrap_or("-"))
);
let _ = writeln!(
out,
"Codepage: {}",
clean(src.codepage.as_deref().unwrap_or("-"))
);
let meters = doc
.units
.meters_per_unit()
.map_or_else(|| "unknown".to_owned(), |m| format!("{m} m/unit"));
let _ = writeln!(out, "Units: {:?} ({meters})", doc.units.unit);
let _ = writeln!(out, "Layers: {}", doc.layers.len());
let _ = writeln!(out, "Blocks: {}", doc.blocks.len());
let _ = writeln!(out, "Models: {}", doc.models.len());
let mut histogram: BTreeMap<&'static str, usize> = BTreeMap::new();
for (i, m) in doc.models.iter().enumerate() {
let mut count = 0usize;
for_each_entity(&m.entities, 0, &mut |e, _| {
count += 1;
*histogram.entry(e.kind.type_name()).or_insert(0) += 1;
});
let _ = writeln!(
out,
" [{i}] {} ({:?}{}): {count} entities",
clean(&m.name),
m.kind,
if m.is_3d { ", 3D" } else { "" }
);
}
let _ = writeln!(out, "Entity types:");
if histogram.is_empty() {
let _ = writeln!(out, " (none)");
}
let mut rows: Vec<(&&str, &usize)> = histogram.iter().collect();
rows.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0)));
for (name, n) in rows {
let _ = writeln!(out, " {name:<10} {n}");
}
let _ = writeln!(out, "Warnings: {}", doc.warnings.len());
if show_warnings {
for w in doc.warnings.iter().take(max_warnings) {
let at = w.offset.map_or_else(String::new, |o| format!(" @0x{o:x}"));
let _ = writeln!(out, " [{}]{at} {}", clean(&w.code), clean(&w.message));
}
if doc.warnings.len() > max_warnings {
let _ = writeln!(out, " ... {} more", doc.warnings.len() - max_warnings);
}
}
out
}
fn layers_text(doc: &Document) -> String {
let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
for m in &doc.models {
for_each_entity(&m.entities, 0, &mut |e, _| {
*counts.entry(e.layer.as_deref().unwrap_or("0")).or_insert(0) += 1;
});
}
let mut rows: Vec<[String; 6]> = Vec::new();
for l in &doc.layers {
let yes = |b: bool| if b { "yes" } else { "no" }.to_owned();
rows.push([
clean(&l.name),
color_text(l.color),
yes(l.visible),
yes(l.frozen),
yes(l.locked),
counts.remove(l.name.as_str()).unwrap_or(0).to_string(),
]);
}
for (name, n) in counts {
rows.push([
format!("{} (undefined)", clean(name)),
"-".into(),
"-".into(),
"-".into(),
"-".into(),
n.to_string(),
]);
}
let head = ["NAME", "COLOR", "VISIBLE", "FROZEN", "LOCKED", "ENTITIES"].map(str::to_owned);
let mut widths = head.clone().map(|h| h.chars().count());
for r in &rows {
for (w, c) in widths.iter_mut().zip(r.iter()) {
*w = (*w).max(c.chars().count());
}
}
let mut out = String::new();
let mut line = |cells: &[String; 6]| {
let mut parts = Vec::new();
for (c, w) in cells.iter().zip(widths.iter()) {
parts.push(format!("{c:<w$}"));
}
let _ = writeln!(out, "{}", parts.join(" ").trim_end());
};
line(&head);
for r in &rows {
line(r);
}
out
}
fn pt(p: &cadkit::Point3) -> String {
format!("({}, {}, {})", num(p.x), num(p.y), num(p.z))
}
fn summary(kind: &EntityKind) -> String {
match kind {
EntityKind::Point { position } => pt(position),
EntityKind::Line { start, end } => format!("{} -> {}", pt(start), pt(end)),
EntityKind::Polyline {
vertices, closed, ..
} => {
format!(
"{} vertices{}",
vertices.len(),
if *closed { ", closed" } else { "" }
)
}
EntityKind::Circle { center, radius, .. } => {
format!("center {} r {}", pt(center), num(*radius))
}
EntityKind::Arc {
center,
radius,
start_angle,
end_angle,
..
} => format!(
"center {} r {} {}..{} deg",
pt(center),
num(*radius),
num(start_angle.to_degrees()),
num(end_angle.to_degrees())
),
EntityKind::Ellipse {
center,
major_axis,
ratio,
..
} => {
format!(
"center {} major ({}, {}) ratio {}",
pt(center),
num(major_axis.x),
num(major_axis.y),
num(*ratio)
)
}
EntityKind::Spline {
degree,
control_points,
fit_points,
..
} => {
format!(
"degree {degree}, {} control, {} fit points",
control_points.len(),
fit_points.len()
)
}
EntityKind::Text {
position,
height,
value,
..
} => {
format!(
"at {} h {} {:?}",
pt(position),
num(*height),
shorten(value)
)
}
EntityKind::MText {
position,
height,
plain,
value,
..
} => {
let text = if plain.is_empty() { value } else { plain };
format!("at {} h {} {:?}", pt(position), num(*height), shorten(text))
}
EntityKind::Insert {
block,
position,
scale,
rotation,
columns,
rows,
..
} => {
let array = if *columns > 1 || *rows > 1 {
format!(" array {columns}x{rows}")
} else {
String::new()
};
format!(
"block {:?} at {} scale ({}, {}) rot {} deg{array}",
clean(block),
pt(position),
num(scale.x),
num(scale.y),
num(rotation.to_degrees())
)
}
EntityKind::Hatch {
loops,
solid,
pattern,
..
} => {
let fill = if *solid {
"solid".to_owned()
} else {
clean(pattern.as_deref().unwrap_or("pattern"))
};
format!("{} loops, {fill}", loops.len())
}
EntityKind::Dimension {
dimension_type,
points,
measurement,
..
} => {
let m = measurement.map_or_else(String::new, |m| format!(" = {}", num(m)));
format!("{dimension_type:?}, {} points{m}", points.len())
}
EntityKind::Face { points, filled } => format!(
"{} points{}",
points.len(),
if *filled { ", filled" } else { "" }
),
EntityKind::Leader { vertices, .. } => format!("{} vertices", vertices.len()),
EntityKind::Image { path, position, .. } => format!(
"{:?} at {}",
clean(path.as_deref().unwrap_or("-")),
pt(position)
),
EntityKind::Viewport {
center,
width,
height,
..
} => {
format!("center {} {}x{}", pt(center), num(*width), num(*height))
}
EntityKind::Mesh { vertices, faces } => {
format!("{} vertices, {} faces", vertices.len(), faces.len())
}
EntityKind::Group {
group_kind,
name,
children,
..
} => {
format!(
"{group_kind:?} {:?} with {} children",
clean(name.as_deref().unwrap_or("")),
children.len()
)
}
EntityKind::Unknown { type_name } => clean(type_name),
EntityKind::Polygon {
exterior,
interiors,
} => format!(
"{} exterior positions, {} holes",
exterior.len(),
interiors.len()
),
_ => String::new(),
}
}
fn shorten(s: &str) -> String {
let flat: String = s
.chars()
.map(|c| if c.is_control() { ' ' } else { c })
.collect();
if flat.chars().count() > 40 {
let cut: String = flat.chars().take(40).collect();
format!("{cut}...")
} else {
flat
}
}
fn dump_text(doc: &Document) -> String {
let mut out = String::new();
for (i, m) in doc.models.iter().enumerate() {
let _ = writeln!(
out,
"# model {i} {:?} ({} top-level entities)",
clean(&m.name),
m.entities.len()
);
for_each_entity(&m.entities, 0, &mut |e, depth| {
let id = e.id.map_or_else(|| "-".to_owned(), |id| id.to_string());
let _ = writeln!(
out,
"{}{id}\t{}\t{}\t{}",
" ".repeat(depth),
clean(e.layer.as_deref().unwrap_or("0")),
e.kind.type_name(),
summary(&e.kind)
);
});
}
out
}
fn print_json(value: &serde_json::Value) -> Result<(), CliError> {
let text = serde_json::to_string_pretty(value).map_err(|e| CliError::Failure(e.to_string()))?;
std::io::stdout()
.lock()
.write_all(format!("{}\n", json_for_terminal(&text)).as_bytes())
.map_err(|e| CliError::Failure(e.to_string()))
}
fn info_json(doc: &Document) -> serde_json::Value {
let mut kinds = BTreeMap::<&str, usize>::new();
for model in &doc.models {
for_each_entity(&model.entities, 0, &mut |e, _| {
*kinds.entry(e.kind.type_name()).or_default() += 1;
});
}
serde_json::json!({"source":doc.source, "units":doc.units, "models":doc.models.len(),
"layers":doc.layers.len(), "blocks":doc.blocks.len(), "entity_kinds":kinds, "warnings":doc.warnings})
}
fn write_output(path: &Path, bytes: &[u8]) -> Result<(), CliError> {
if path != Path::new("-") {
return std::fs::write(path, bytes).map_err(|e| failure(path, &e));
}
let stdout = std::io::stdout();
if stdout.is_terminal() {
let text = std::str::from_utf8(bytes)
.map_err(|_| CliError::Usage("redirect binary output to a file or pipe".into()))?;
stdout
.lock()
.write_all(strip_controls(text).as_bytes())
.map_err(|e| failure(path, &e))
} else {
stdout
.lock()
.write_all(bytes)
.map_err(|e| failure(path, &e))
}
}
impl TransformOptions {
fn active(&self) -> bool {
self.explode_inserts || self.units.is_some() || self.layer.is_some() || self.kind.is_some()
}
}
fn apply_transforms(doc: &mut Document, options: &TransformOptions) -> Result<(), CliError> {
if let Some(unit) = &options.units {
let target = cadkit::LengthUnit::from_name(unit)
.ok_or_else(|| CliError::Usage(format!("unknown length unit {unit:?}")))?;
doc.convert_units(target)
.map_err(|e| CliError::Failure(e.to_string()))?;
}
if options.explode_inserts {
let stats = doc.explode_inserts(32);
if stats.truncated {
return Err(CliError::Failure(
"block expansion work limit exceeded".into(),
));
}
}
if let Some(layer) = &options.layer {
doc.retain_layers(|name| name == layer);
}
if let Some(kind) = &options.kind {
fn retain(entities: &mut Vec<Entity>, kind: &str) {
entities.retain_mut(|e| {
if let EntityKind::Group { children, .. } = &mut e.kind {
retain(children, kind);
if !children.is_empty() {
return true;
}
}
e.kind.type_name() == kind
});
}
for model in &mut doc.models {
retain(&mut model.entities, kind);
}
for block in &mut doc.blocks {
retain(&mut block.entities, kind);
}
}
Ok(())
}
fn completions(shell: &str) -> String {
let commands =
"inspect info layers blocks convert dump validate-gml repack-dgn completions help";
let flags = "--help --version --keep-raw --codepage --max-input-bytes --max-decompressed-bytes --max-objects --planarity-tolerance --json --warnings --max-warnings --to --output-codepage --explode-inserts --units --layer --kind --model --dxf-version --width --pretty --seed --clear-seed-model --crs --lod --preserve-invalid-geometry --gml-metadata-only --tkgm-profile";
match shell {
"bash" => format!(
"_cadkit() {{ local cur=\"${{COMP_WORDS[COMP_CWORD]}}\"; COMPREPLY=( $(compgen -W '{commands} {flags}' -- \"$cur\") ); if [[ $cur != -* ]]; then COMPREPLY+=( $(compgen -f -- \"$cur\") ); fi; }}\ncomplete -F _cadkit cadkit\n"
),
"zsh" => format!(
"#compdef cadkit\n_arguments '*:argument:(({commands} {flags}))' '*:file:_files'\n"
),
"fish" => format!(
"complete -c cadkit -f -a '{commands}'\n{}",
flags
.split_whitespace()
.map(|f| format!("complete -c cadkit -l {}\n", f.trim_start_matches('-')))
.collect::<String>()
),
"powershell" => format!(
"Register-ArgumentCompleter -Native -CommandName cadkit -ScriptBlock {{ param($wordToComplete, $commandAst, $cursorPosition)\n'{commands} {flags}'.Split(' ') | Where-Object {{ $_ -like \"$wordToComplete*\" }} | ForEach-Object {{ [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }}\n}}\n"
),
_ => String::new(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use cadkit::{Layer, Model, Point3};
fn sample() -> Document {
let mut line = Entity::new(EntityKind::Line {
start: Point3::xy(0.0, 0.0),
end: Point3::xy(10.0, 5.5),
});
line.id = Some(42);
line.layer = Some("walls".into());
{
let mut doc = Document::default();
doc.layers = vec![{
let mut layer = Layer::new("walls");
layer.plottable = false;
layer
}];
doc.models = vec![{
let mut model = Model::default().with_entities(vec![line]);
model.name = "Model".into();
model
}];
doc
}
}
#[test]
fn number_formatting() {
assert_eq!(num(1.0), "1");
assert_eq!(num(-0.00001), "0");
assert_eq!(num(2.50), "2.5");
assert_eq!(num(f64::NAN), "nan");
}
#[test]
fn dump_and_layers_text() {
let d = sample();
let dump = dump_text(&d);
assert!(
dump.contains("42\twalls\tline\t(0, 0, 0) -> (10, 5.5, 0)"),
"{dump}"
);
let layers = layers_text(&d);
assert!(
layers.contains("walls") && layers.lines().count() == 2,
"{layers}"
);
let info = info_text(Path::new("x.dxf"), &d, true, 5);
assert!(
info.contains("line 1") && info.contains("Warnings: 0"),
"{info}"
);
}
#[test]
fn terminal_output_is_sanitized() {
assert_eq!(clean("a\u{1b}[31mb\nc\u{9b}"), "a?[31mb?c?");
assert_eq!(strip_controls("ok\tx\n\u{1b}y"), "ok\tx\n?y");
assert_eq!(
json_for_terminal("{\"a\":\"\u{9b}\"}"),
"{\"a\":\"\\u009b\"}"
);
let mut d = sample();
d.source.application = Some("evil\u{1b}]0;title\u{7}".into());
d.layers[0].name = "la\nyer".into();
let text = strip_controls(&info_text(Path::new("x"), &d, false, 0));
assert!(
!text.contains('\u{1b}') && text.contains("evil?]0;title?"),
"{text}"
);
assert!(layers_text(&d).contains("la?yer"));
}
#[test]
fn version_and_width_parsing() {
assert_eq!(parse_dxf_version("R2000"), Ok(DxfVersion::R2000));
assert!(parse_dxf_version("r13").is_err());
assert!(parse_width("0").is_err());
assert_eq!(parse_width("800"), Ok(800.0));
}
}