use clap::{CommandFactory, Parser, Subcommand, ValueEnum};
use layouttk::file_workflows::{self, ClipOptions, Window};
use layouttk::{DEFAULT_OAS_BUDGET, Layer, Point, ReadOptions};
use std::collections::BTreeSet;
use std::fs::File;
use std::io::{self, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
#[path = "layouttk/create.rs"]
mod create;
#[path = "layouttk/edit.rs"]
mod edit;
#[path = "layouttk/font.rs"]
mod font;
#[path = "layouttk/gds.rs"]
mod gds;
#[path = "layouttk/geometry.rs"]
mod geometry;
#[path = "layouttk/query.rs"]
mod query;
#[path = "layouttk/raster.rs"]
mod raster;
#[path = "layouttk/view.rs"]
mod view;
#[derive(Parser)]
#[command(
version,
about = "Create, inspect, edit, compare and convert GDSII and OASIS layouts",
after_help = "Examples:\n layouttk inventory chip.oas\n layouttk extract chip.oas metal.gds --top TOP --layer 7/0\n layouttk clip chip.oas roi.oas --top TOP --layer 7/0 --window=0,0,100,40\n\nRead top_cells and shape_layers from inventory before choosing a cell and layer.\n7/0 means layer 7, datatype 0. DBU is one grid step. Multiply coordinates by dbu_nm to get nanometres.\n\nUse layouttk <command> --help for examples and options.\nUse layouttk guide --lang zh-CN for the built-in Chinese guide, or guide --lang en for English.\nUse layouttk describe --json for the complete command index, or describe --json query bounds for one command."
)]
struct Cli {
/// Budget in bytes for retained OASIS data, independent of compressed file size.
#[arg(long, global = true, default_value_t = DEFAULT_OAS_BUDGET)]
oas_budget_bytes: usize,
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
/// Create a layout from a versioned JSON specification. Use - to read stdin.
#[command(after_help = create::EXAMPLE, after_long_help = create::HELP)]
Create {
/// JSON layout specification. Pass - to read it from stdin.
#[arg(value_name = "SPEC.json|-")]
spec: PathBuf,
/// Layout to write. Use a .gds or .oas suffix.
output: PathBuf,
/// Exact integer grid refinement. 2 halves the physical DBU and doubles all coordinates.
#[arg(long, default_value_t = 1)]
regrid_factor: u32,
},
/// Print library metadata, top cells, layers and stored element counts as JSON.
#[command(
after_help = "Example: layouttk inspect chip.oas\nStdout is JSON with top_cells, layers, cell_count, element_counts and dbu_meters (metres per grid step). Counts are stored records, so one compact array counts once. Use inventory for per-cell and repetition counts."
)]
Inspect {
/// GDSII or OASIS file to inspect.
input: PathBuf,
},
/// Scan a file for cell definitions, dependencies, layer pairs and repetition counts.
#[command(
after_help = "Examples: layouttk inventory chip.oas\n layouttk inventory chip.oas --top TOP --layer 7/0\nRead report.top_cells, report.shape_layers, report.text_layers and report.dbu_nm first. Shape layers have number and datatype. Text layers use texttype in the datatype field. Per-cell counts describe stored records and local repetitions. They do not expand every placement from the top cell."
)]
Inventory {
/// GDSII or OASIS file to scan.
input: PathBuf,
/// Include only this cell and its dependencies. Omit to scan every cell.
#[arg(long)]
top: Option<String>,
/// Select a layer/type pair such as 7/0. Repeat to keep several pairs.
#[arg(long = "layer", value_parser = parse_layer, value_name = "LAYER/DATATYPE")]
layers: Vec<Layer>,
},
/// Verify stored records and placed layer geometry of two files on the same grid.
#[command(
after_help = "Example: layouttk verify source.gds copy.oas --left-top TOP --right-top TOP\nInputs must use matching grids. If needed, use resample first.\nRead report.geometry_equal for placed material and report.stored_equal for stored cells, placements, text and properties. Use report.cell_differences and report.layer_differences to locate changes. Status equal returns exit 0. Status different or a processing error returns exit 1."
)]
Verify {
/// First layout file, typically the reference.
left: PathBuf,
/// Second layout file, typically the candidate.
right: PathBuf,
/// Cell to compare in LEFT. Omit if LEFT has exactly one top cell.
#[arg(long)]
left_top: Option<String>,
/// Cell to compare in RIGHT. Omit if RIGHT has exactly one top cell.
#[arg(long)]
right_top: Option<String>,
/// Compare only this layer/type pair. Repeat to select several pairs.
#[arg(long = "layer", value_parser = parse_layer, value_name = "LAYER/DATATYPE")]
layers: Vec<Layer>,
/// Maximum expanded placements and elements per input.
#[arg(long, default_value_t = layouttk::hierarchy::DEFAULT_EXPANSION_LIMIT)]
limit: usize,
/// Outline tolerance for paths and circles in DBU. This is not an XOR area threshold.
#[arg(long, default_value_t = 0.25)]
tolerance_dbu: f64,
},
/// Scan a file twice and write one flat geometry cell per requested window.
#[command(
after_help = "Example: layouttk clip chip.oas roi.oas --top TOP --layer 7/0 --window=0,0,1000,800\nRepeat --window for multiple windows. Each produces a cell named WIN_1, WIN_2 and so on, including empty windows. The JSON report maps windows to cells. Output is flat filled polygons in the original top-cell coordinates. For labels, properties and hierarchy, use extract to preserve the selected layer records."
)]
Clip {
/// GDSII or OASIS input file. The command scans it twice.
input: PathBuf,
/// Layout to write. Use a .gds or .oas suffix.
output: PathBuf,
/// Cell whose coordinate system defines all windows.
#[arg(long)]
top: String,
/// Lower-left and upper-right corners in integer DBU. Use --window=-10,0,100,40 for negatives.
#[arg(long = "window", value_parser = parse_window, value_name = "X0,Y0,X1,Y1", required = true, allow_hyphen_values = true)]
windows: Vec<Window>,
/// Keep a layer/datatype pair. Repeat to select several pairs. Omit to keep all shape layers.
#[arg(long = "layer", value_parser = parse_layer, value_name = "LAYER/DATATYPE")]
layers: Vec<Layer>,
/// Maximum number of placements to expand.
#[arg(long, default_value_t = layouttk::hierarchy::DEFAULT_EXPANSION_LIMIT)]
placement_limit: usize,
/// Maximum total polygon vertices written across all windows.
#[arg(long, default_value_t = 4_000_000)]
output_vertex_limit: usize,
/// Outline tolerance for paths and circles in DBU.
#[arg(long, default_value_t = 0.25)]
tolerance_dbu: f64,
},
/// Check that a target format can encode the source, without creating an output.
#[command(
after_help = "Example: layouttk check chip.oas --to gds --json\nRead can_write and diagnostics. Each diagnostic identifies a field and can identify a cell, element or layer. Exit 0 means the target can be written. Exit 1 means an error occurred. Without --json, success is quiet and the first error goes to stderr."
)]
Check {
/// GDSII or OASIS file to check.
input: PathBuf,
/// Output format to check, gds for GDSII or oas for OASIS.
#[arg(long, value_name = "gds|oas")]
to: layouttk::Format,
/// Print all destination constraints and metadata normalizations as JSON.
#[arg(long)]
json: bool,
/// Exact integer grid refinement. 2 halves the physical DBU and doubles all coordinates.
#[arg(long, default_value_t = 1)]
regrid_factor: u32,
},
/// Read and rewrite a layout. The output suffix selects the format.
#[command(
after_help = "Example: layouttk convert chip.oas chip.gds\nRun layouttk check chip.oas --to gds --json to see conversion diagnostics first. Successful conversion writes OUTPUT and is quiet. If encoding fails, an existing OUTPUT stays intact."
)]
Convert {
/// GDSII or OASIS file to read.
input: PathBuf,
/// Destination layout. Use a .gds or .oas suffix.
output: PathBuf,
/// Exact grid refinement. 2 halves the physical DBU and doubles coordinates.
#[arg(long, default_value_t = 1)]
regrid_factor: u32,
},
/// Select layers during read and optionally retain one cell with its dependencies.
#[command(
after_help = "Example: layouttk extract chip.oas metal.gds --top TOP --layer 7/0\nFirst run layouttk inventory chip.oas to find cell names and layer pairs. Repeat --layer to keep several pairs. Kept cells retain their hierarchy and representable properties, and some definitions may be empty. Successful extraction is quiet. Run layouttk inventory metal.gds to check the result."
)]
Extract {
/// GDSII or OASIS file to read.
input: PathBuf,
/// Layout to write. Use a .gds or .oas suffix.
output: PathBuf,
/// Keep this cell and its dependencies. Omit to keep every definition.
#[arg(long)]
top: Option<String>,
/// Keep a layer/type pair. Repeat to keep several pairs. Omit to keep all layers.
#[arg(long = "layer", value_parser = parse_layer, value_name = "LAYER/DATATYPE")]
layers: Vec<Layer>,
/// Exact grid refinement. 2 halves the physical DBU and doubles coordinates.
#[arg(long, default_value_t = 1)]
regrid_factor: u32,
},
/// Calculate polygon and path geometry from JSON without opening a layout file.
#[command(
subcommand,
after_help = "Run layouttk geometry <method> --help for its JSON example, fields and result. Save the example JSON in a file and pass its filename, or pass - and send JSON on stdin. Read report.result on success. A ring is a list of [x,y] points with an implicit closing edge. For filled regions, use counterclockwise outer rings and clockwise holes. Lengths use grid steps (DBU). Continuous DBU accept fractional values."
)]
Geometry(geometry::Command),
/// Compute a Boolean operation on two placed layers and write the result.
#[command(
after_help = "Example: layouttk boolean a.oas b.oas result.gds --op difference --left-top TOP --right-top TOP --left-layer 7/0 --right-layer 8/0 --output-layer 7/0\nInputs must have the same grid. Both layers are resolved into their respective top-cell coordinates. Difference subtracts RIGHT from LEFT. The result is a flat TOP cell, with holes split into independently filled polygons. Empty results are valid and contain an empty TOP cell. Read report.file and report.polygons."
)]
Boolean {
/// Layout supplying the first layer.
left: PathBuf,
/// Layout supplying the second layer. It may be the same file as LEFT.
right: PathBuf,
/// Layout to write. Use a .gds or .oas suffix.
output: PathBuf,
/// Choose union, intersection, difference, or xor.
#[arg(long)]
op: layouttk::geometry::BooleanOp,
/// Cell whose placed shapes supply the first layer.
#[arg(long)]
left_top: String,
/// Cell whose placed shapes supply the second layer.
#[arg(long)]
right_top: String,
/// Shape layer/datatype to use from LEFT.
#[arg(long, value_parser = parse_layer, value_name = "LAYER/DATATYPE")]
left_layer: Layer,
/// Shape layer/datatype to use from RIGHT.
#[arg(long, value_parser = parse_layer, value_name = "LAYER/DATATYPE")]
right_layer: Layer,
/// Layer/datatype for the resulting polygons in TOP.
#[arg(long, value_parser = parse_layer, value_name = "LAYER/DATATYPE")]
output_layer: Layer,
/// Outline tolerance for paths and circles in DBU.
#[arg(long, default_value_t = 0.25)]
tolerance_dbu: f64,
/// Maximum expanded placements and elements per input.
#[arg(long, default_value_t = layouttk::hierarchy::DEFAULT_EXPANSION_LIMIT)]
limit: usize,
},
/// Get placed shapes, bounds, areas, labels, or cell information as JSON.
#[command(
subcommand,
after_help = "Example: layouttk query bounds chip.oas --cell TOP\nFind an exact cell name with layouttk inventory. Run layouttk query <method> --help for the result fields, units and a command example."
)]
Query(query::Command),
/// Apply a versioned set of cell, layer, or element edits in one file write.
#[command(after_help = edit::EXAMPLE, after_long_help = edit::HELP)]
Edit {
/// GDSII or OASIS file to edit.
input: PathBuf,
/// JSON list of operations. Pass - to read it from stdin.
#[arg(value_name = "EDITS.json|-")]
spec: PathBuf,
/// Layout to write after all edits succeed. Use a .gds or .oas suffix.
output: PathBuf,
/// Exact grid refinement when encoding the edited layout.
#[arg(long, default_value_t = 1)]
regrid_factor: u32,
},
/// Re-express the layout on a new grid while preserving physical dimensions.
#[command(
after_help = "Example: layouttk resample chip.oas fine.oas --dbu-nm 0.5\nThe default exact mode fails if any dimension falls between points on the target grid. Use --rounding nearest to allow rounding. It rounds half-grid ties away from zero. The output file is written only after validation succeeds."
)]
Resample {
/// GDSII or OASIS file on the original grid.
input: PathBuf,
/// Layout to write on the target grid. Use a .gds or .oas suffix.
output: PathBuf,
/// Physical size of one new grid step in nanometres.
#[arg(long)]
dbu_nm: f64,
/// Use nearest-grid rounding when an exact conversion is unavailable.
#[arg(long, value_enum, default_value = "exact")]
rounding: Rounding,
},
/// Change the physical size of a grid step, keeping stored coordinates unchanged.
#[command(
after_help = "Example: layouttk reinterpret-dbu chip.oas scaled.oas --dbu-nm 2\nA length of 100 DBU stays 100 DBU. On a 2 nm grid it measures 200 nm. Use resample to preserve physical dimensions while changing the stored coordinates."
)]
ReinterpretDbu {
/// GDSII or OASIS file to rescale.
input: PathBuf,
/// Layout to write with the new units. Use a .gds or .oas suffix.
output: PathBuf,
/// Physical size of one new grid step in nanometres.
#[arg(long)]
dbu_nm: f64,
},
/// Inspect GDSII units and records, hash content, or work with raw cells.
#[command(
subcommand,
after_help = "Example: layouttk gds index chip.gds\nUse layouttk gds <method> --help for the input format, output and options. Use inventory for GDSII or OASIS layout content."
)]
Gds(gds::Command),
/// Exchange binary masks with layout layers, or export a window as PNG.
#[command(
subcommand,
after_help = "Example: layouttk raster png chip.oas roi.png --cell TOP --layer 7/0 --window=0,0,100,40 --pixel-size 5\nRow 0 is the top row. Use layouttk raster <method> --help for pixel sizes and examples."
)]
Raster(raster::Command),
/// Export layer drawings as SVG or a self-contained HTML preview.
#[command(
subcommand,
after_help = "Example: layouttk view html chip.oas preview.html --cell TOP\nOpen the result in a browser on the same machine. It uses no network assets."
)]
View(view::Command),
/// Export or import the stored model as versioned JSON, including properties.
#[command(
after_help = "Example: layouttk model export chip.oas --output chip.json\n layouttk model import chip.json restored.oas\nThe JSON includes stored records, properties and repetitions. Use create for a shorter input format for simple layouts."
)]
Model {
#[command(subcommand)]
command: edit::Model,
},
/// List the commands and parameters supported by this binary.
#[command(
after_help = "Examples: layouttk describe --json\n layouttk describe --json geometry offset\nWith no command path, the JSON contains the full command tree. Supplying a path returns only that command or group and its arguments. Without --json, this prints help text."
)]
Describe {
/// Print the command index as JSON on stdout.
#[arg(long)]
json: bool,
/// Optional command path, for example query bounds.
#[arg(value_name = "COMMAND")]
command: Vec<String>,
},
/// Print the built-in command-line guide in English or Simplified Chinese.
#[command(
after_help = "Example: layouttk guide --lang zh-CN\nStdout is a Markdown guide with examples for extracting, checking and processing layouts. It is built into the binary."
)]
Guide {
/// Language of the guide.
#[arg(long, value_enum, default_value = "en")]
lang: Language,
},
}
#[derive(Clone, Copy, ValueEnum)]
enum Language {
En,
#[value(name = "zh-CN", aliases = ["zh-cn", "zh"])]
ZhCn,
}
#[derive(Clone, Copy, ValueEnum)]
enum Rounding {
Exact,
Nearest,
}
type CliResult<T> = Result<T, Box<dyn std::error::Error>>;
fn read_json<T: serde::de::DeserializeOwned>(path: &Path) -> CliResult<T> {
Ok(if path.as_os_str() == "-" {
serde_json::from_reader(io::stdin().lock())?
} else {
serde_json::from_reader(BufReader::new(File::open(path)?))?
})
}
fn write_file(path: &Path, write: impl FnOnce(&mut File) -> CliResult<()>) -> CliResult<()> {
let dir = path
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or(Path::new("."));
let mut temp = tempfile::NamedTempFile::new_in(dir)?;
write(temp.as_file_mut())?;
temp.as_file_mut().flush()?;
temp.persist(path).map_err(|e| e.error)?;
Ok(())
}
fn command_index(command: &clap::Command) -> serde_json::Value {
serde_json::json!({
"name": command.get_name(),
"about": command.get_about().map(ToString::to_string),
"details": command.get_after_long_help().or_else(|| command.get_after_help()).map(ToString::to_string),
"arguments": command.get_arguments().map(|arg| serde_json::json!({
"id": arg.get_id().as_str(),
"long": arg.get_long(),
"short": arg.get_short(),
"position": arg.get_index(),
"required": arg.is_required_set(),
"help": arg.get_help().map(ToString::to_string),
"value_names": arg.get_value_names().into_iter().flatten().map(|name| name.as_str()).collect::<Vec<_>>(),
"defaults": arg.get_default_values().iter().map(|v| v.to_string_lossy()).collect::<Vec<_>>(),
"takes_values": arg.get_action().takes_values(),
"repeatable": matches!(arg.get_action(), clap::ArgAction::Append | clap::ArgAction::Count),
"choices": arg.get_possible_values().iter().map(|v| v.get_name()).collect::<Vec<_>>(),
})).collect::<Vec<_>>(),
"commands": command.get_subcommands().filter(|sub| sub.get_name() != "help").map(command_index).collect::<Vec<_>>(),
})
}
fn describe(json: bool, path: &[String]) -> CliResult<()> {
let mut root = Cli::command();
root.build();
let mut command = &mut root;
for (index, name) in path.iter().enumerate() {
command = command.find_subcommand_mut(name).ok_or_else(|| {
format!(
"unknown command path {:?}. Use layouttk --help",
path[..=index].join(" ")
)
})?;
}
if json {
print_report(
"ok",
serde_json::json!({"version": env!("CARGO_PKG_VERSION"), "cli": command_index(command)}),
)?;
} else {
command.print_long_help()?;
}
Ok(())
}
fn parse_layer(value: &str) -> Result<Layer, String> {
let (number, datatype) = value.split_once('/').ok_or("expected LAYER/DATATYPE")?;
Ok(Layer {
number: number.parse().map_err(|_| "invalid layer number")?,
datatype: datatype.parse().map_err(|_| "invalid datatype")?,
})
}
fn parse_window(value: &str) -> Result<Window, String> {
let error = "expected four signed integers X0,Y0,X1,Y1";
let coords = value
.split(',')
.map(str::parse::<i64>)
.collect::<Result<Vec<_>, _>>()
.map_err(|_| error)?;
let [x0, y0, x1, y1] = coords.as_slice() else {
return Err(error.into());
};
Window::new(Point { x: *x0, y: *y0 }, Point { x: *x1, y: *y1 }).map_err(|e| e.to_string())
}
fn selection<'a>(layers: &'a BTreeSet<Layer>, options: ReadOptions<'a>) -> ReadOptions<'a> {
ReadOptions {
layers: (!layers.is_empty()).then_some(layers),
..options
}
}
fn print_report(status: &str, data: impl serde::Serialize) -> CliResult<()> {
#[derive(serde::Serialize)]
struct Report<'a, T> {
schema_version: u32,
status: &'a str,
report: T,
}
let mut stdout = io::stdout().lock();
serde_json::to_writer_pretty(
&mut stdout,
&Report {
schema_version: 1,
status,
report: data,
},
)?;
stdout.write_all(b"\n")?;
Ok(())
}
fn report<T>(result: layouttk::Result<T>) -> layouttk::Result<T> {
result.inspect_err(|err| {
let _ = print_report("error", serde_json::json!({"message":err.to_string()}));
})
}
fn run(cli: Cli) -> Result<(), Box<dyn std::error::Error>> {
let options = ReadOptions {
oas_budget_bytes: cli.oas_budget_bytes,
..Default::default()
};
match cli.command {
Command::Create {
spec,
output,
regrid_factor,
} => {
let layout = if spec.as_os_str() == "-" {
create::read(io::stdin().lock())?
} else {
create::read(BufReader::new(File::open(spec)?))?
};
layouttk::write(layout.with_regrid(regrid_factor)?.as_ref(), output)?;
}
Command::Check {
input,
to,
json,
regrid_factor,
} => {
if !json {
let layout = options.read(input)?;
layouttk::check_write(layout.with_regrid(regrid_factor)?.as_ref(), to)?;
} else {
use layouttk::conversion::{Diagnostic, Severity};
let report = options
.read(&input)
.map_err(|e| ("input", e))
.and_then(|layout| {
let target = layout
.with_regrid(regrid_factor)
.map_err(|e| ("regrid_factor", e))?;
Ok(target.conversion_diagnostics(to))
});
let rows = report.unwrap_or_else(|(field, err)| {
vec![Diagnostic {
severity: Severity::Error,
cell: None,
element: None,
layer: None,
field: field.into(),
reason: err.to_string(),
}]
});
let can_write = rows.iter().all(|row| row.severity != Severity::Error);
let target = match to {
layouttk::Format::Gdsii => "gds",
layouttk::Format::Oasis => "oas",
};
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"file":input, "target_format":target,"regrid_factor":regrid_factor,
"can_write":can_write,"diagnostics":rows,
}))?
);
if !can_write {
return Err("conversion preflight failed".into());
}
}
}
Command::Inspect { input } => {
let layout = options.read(input)?;
println!("{}", serde_json::to_string_pretty(&layout.summary())?);
}
Command::Inventory { input, top, layers } => {
let layers = layers.into_iter().collect();
let inventory = report(file_workflows::inventory(
selection(&layers, options),
input,
top.as_deref(),
))?;
print_report("ok", inventory)?;
}
Command::Verify {
left,
right,
left_top,
right_top,
layers,
limit,
tolerance_dbu,
} => {
let layers: BTreeSet<_> = layers.into_iter().collect();
let comparison = report(file_workflows::verify(
selection(&layers, options),
left,
right,
left_top.as_deref(),
right_top.as_deref(),
limit,
tolerance_dbu,
))?;
let equal = comparison.geometry_equal && comparison.stored_equal;
print_report(if equal { "equal" } else { "different" }, comparison)?;
if !equal {
return Err("verification found differences".into());
}
}
Command::Clip {
input,
output,
top,
windows,
layers,
placement_limit,
output_vertex_limit,
tolerance_dbu,
} => {
let layers = layers.into_iter().collect();
let layout = report(file_workflows::clip_file(
input,
&top,
&windows,
ClipOptions {
read: selection(&layers, options),
placement_limit,
output_vertex_limit,
tolerance_dbu,
},
))?;
report(layouttk::write(&layout, &output))?;
let rows: Vec<_> = windows.iter().zip(&layout.cells).map(|(window, cell)|
serde_json::json!({"cell": cell.name, "window": window, "polygons": cell.elements.len()})
).collect();
print_report(
"ok",
serde_json::json!({
"file": output, "top": top, "dbu_nm": layout.dbu_meters * 1e9,
"dbu_meters": layout.dbu_meters, "output_kind": "flat_polygons",
"tolerance_dbu": tolerance_dbu, "windows": rows,
}),
)?;
}
Command::Convert {
input,
output,
regrid_factor,
} => {
let layout = options.read(input)?;
layouttk::write(layout.with_regrid(regrid_factor)?.as_ref(), output)?;
}
Command::Extract {
input,
output,
top,
layers,
regrid_factor,
} => {
let layers: BTreeSet<_> = layers.into_iter().collect();
let mut layout = selection(&layers, options).read(input)?;
if let Some(top) = top {
layout.retain_tree(&top)?;
}
layouttk::write(layout.with_regrid(regrid_factor)?.as_ref(), output)?;
}
Command::Geometry(command) => command.run()?,
Command::Boolean {
left,
right,
output,
op,
left_top,
right_top,
left_layer,
right_layer,
output_layer,
tolerance_dbu,
limit,
} => {
if !tolerance_dbu.is_finite() || tolerance_dbu <= 0.0 || limit == 0 {
return Err("use a positive tolerance and expansion limit".into());
}
let a = selection(&BTreeSet::from([left_layer]), options).read(left)?;
let b = selection(&BTreeSet::from([right_layer]), options).read(right)?;
if a.dbu_meters != b.dbu_meters {
return Err("input grids differ; use layouttk resample to match them".into());
}
let left = file_workflows::placed_rings(&a, &left_top, limit, tolerance_dbu)?;
let right = file_workflows::placed_rings(&b, &right_top, limit, tolerance_dbu)?;
let subject = left.get(&left_layer).map(Vec::as_slice).unwrap_or_default();
let clip = right
.get(&right_layer)
.map(Vec::as_slice)
.unwrap_or_default();
let rings = layouttk::geometry::boolean(subject, clip, op)?;
let polygons = layouttk::geometry::fracture(&rings, 8_190)?;
let mut layout = layouttk::Layout::new("BOOLEAN", a.dbu_meters)?;
let top = layout.add_cell("TOP")?;
top.elements.extend(
polygons
.into_iter()
.map(|points| layouttk::Element::Polygon {
layer: output_layer,
points,
}),
);
let count = top.elements.len();
layouttk::write(&layout, &output)?;
print_report(
"ok",
serde_json::json!({"file": output, "top": "TOP", "polygons": count}),
)?;
}
Command::Query(command) => command.run(options)?,
Command::Edit {
input,
spec,
output,
regrid_factor,
} => {
edit::run(input, spec, output, regrid_factor, options)?;
}
Command::Resample {
input,
output,
dbu_nm,
rounding,
} => {
let rounding = match rounding {
Rounding::Exact => layouttk::GridRounding::Exact,
Rounding::Nearest => layouttk::GridRounding::Nearest,
};
let layout = options.read(input)?.resample(dbu_nm / 1e9, rounding)?;
layouttk::write(&layout, output)?;
}
Command::ReinterpretDbu {
input,
output,
dbu_nm,
} => {
let layout = options.read(input)?.reinterpret_dbu(dbu_nm / 1e9)?;
layouttk::write(&layout, output)?;
}
Command::Gds(command) => command.run(options)?,
Command::Raster(command) => command.run(options)?,
Command::View(command) => command.run(options)?,
Command::Model { command } => command.run(options)?,
Command::Describe { json, command } => describe(json, &command)?,
Command::Guide { lang } => {
let guide = match lang {
Language::En => include_str!("../../docs/en/command-line.md"),
Language::ZhCn => include_str!("../../docs/zh-CN/command-line.md"),
};
io::stdout().lock().write_all(guide.as_bytes())?;
}
}
Ok(())
}
fn main() -> ExitCode {
let cli = Cli::parse();
let structured_error = matches!(
cli.command,
Command::Boolean { .. }
| Command::Geometry(_)
| Command::Query(_)
| Command::Edit { .. }
| Command::Resample { .. }
| Command::ReinterpretDbu { .. }
| Command::Gds(_)
| Command::Model { .. }
| Command::Raster(_)
| Command::View(_)
| Command::Describe { json: true, .. }
);
match run(cli) {
Ok(()) => ExitCode::SUCCESS,
Err(err) => {
if structured_error {
let _ = print_report("error", serde_json::json!({"message": err.to_string()}));
}
eprintln!("layouttk: {err}");
ExitCode::FAILURE
}
}
}