diff --git a/README.md b/README.md index 91ff478..4cae709 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,7 @@ Deferred manual/runtime verification (implemented after 2026-02-20 while user un - `CreateItems` - `UpdateItems` - `DeleteItems` +- `ParseAndCreateItemsFromString` ## KiCad v10 RC1.1 API Completion Matrix @@ -62,11 +63,11 @@ Legend: | Section | Proto Commands | Implemented | Coverage | | --- | ---: | ---: | ---: | | Common (base) | 6 | 6 | 100% | -| Common editor/document | 23 | 22 | 96% | +| Common editor/document | 23 | 23 | 100% | | Project manager | 5 | 3 | 60% | | Board editor (PCB) | 22 | 20 | 91% | | Schematic editor (dedicated proto commands) | 0 | 0 | n/a | -| **Total** | **56** | **51** | **91%** | +| **Total** | **56** | **52** | **93%** | ### Common (base) @@ -105,7 +106,7 @@ Legend: | `GetTitleBlockInfo` | Implemented | `KiCadClient::get_title_block_info` | | `SaveDocumentToString` | Implemented | `KiCadClient::get_board_as_string` | | `SaveSelectionToString` | Implemented | `KiCadClient::get_selection_as_string` | -| `ParseAndCreateItemsFromString` | Not yet | - | +| `ParseAndCreateItemsFromString` | Implemented | `KiCadClient::parse_and_create_items_from_string_raw`, `KiCadClient::parse_and_create_items_from_string` | ### Project manager diff --git a/docs/TEST_CLI.md b/docs/TEST_CLI.md index d4d4a17..4a9931a 100644 --- a/docs/TEST_CLI.md +++ b/docs/TEST_CLI.md @@ -205,6 +205,12 @@ Delete items by ID: cargo run --bin kicad-ipc-cli -- delete-items --id --id ``` +Parse and create items from s-expression: + +```bash +cargo run --bin kicad-ipc-cli -- parse-create-items --contents "(kicad_pcb (version 20240108))" +``` + Show summary of current PCB selection by item type: ```bash diff --git a/src/client.rs b/src/client.rs index 22182b9..1763d7d 100644 --- a/src/client.rs +++ b/src/client.rs @@ -79,6 +79,8 @@ const CMD_END_COMMIT: &str = "kiapi.common.commands.EndCommit"; const CMD_CREATE_ITEMS: &str = "kiapi.common.commands.CreateItems"; const CMD_UPDATE_ITEMS: &str = "kiapi.common.commands.UpdateItems"; const CMD_DELETE_ITEMS: &str = "kiapi.common.commands.DeleteItems"; +const CMD_PARSE_AND_CREATE_ITEMS_FROM_STRING: &str = + "kiapi.common.commands.ParseAndCreateItemsFromString"; const CMD_GET_ITEMS: &str = "kiapi.common.commands.GetItems"; const CMD_GET_ITEMS_BY_ID: &str = "kiapi.common.commands.GetItemsById"; const CMD_GET_BOUNDING_BOX: &str = "kiapi.common.commands.GetBoundingBox"; @@ -735,6 +737,47 @@ impl KiCadClient { .collect() } + pub async fn parse_and_create_items_from_string_raw( + &self, + contents: impl Into, + ) -> Result { + let command = common_commands::ParseAndCreateItemsFromString { + document: Some(self.current_board_document_proto().await?), + contents: contents.into(), + }; + + let response = self + .send_command(envelope::pack_any( + &command, + CMD_PARSE_AND_CREATE_ITEMS_FROM_STRING, + )) + .await?; + response_payload_as_any(response, RES_CREATE_ITEMS_RESPONSE) + } + + pub async fn parse_and_create_items_from_string( + &self, + contents: impl Into, + ) -> Result, KiCadError> { + let payload = self + .parse_and_create_items_from_string_raw(contents) + .await?; + let response: common_commands::CreateItemsResponse = + decode_any(&payload, RES_CREATE_ITEMS_RESPONSE)?; + ensure_item_request_ok(response.status)?; + + response + .created_items + .into_iter() + .map(|row| { + ensure_item_status_ok(row.status)?; + row.item.ok_or_else(|| KiCadError::InvalidResponse { + reason: "CreateItemsResponse missing created item payload".to_string(), + }) + }) + .collect() + } + pub async fn get_nets(&self) -> Result, KiCadError> { let board = self.current_board_document_proto().await?; let command = board_commands::GetNets { diff --git a/test-scripts/kicad-ipc-cli.rs b/test-scripts/kicad-ipc-cli.rs index 7037f42..fe5edb0 100644 --- a/test-scripts/kicad-ipc-cli.rs +++ b/test-scripts/kicad-ipc-cli.rs @@ -110,6 +110,9 @@ enum Command { DeleteItems { item_ids: Vec, }, + ParseCreateItemsFromString { + contents: String, + }, AddToSelection { item_ids: Vec, }, @@ -516,6 +519,17 @@ async fn run() -> Result<(), KiCadError> { println!("[{index}] id={item_id}"); } } + Command::ParseCreateItemsFromString { contents } => { + let created = client.parse_and_create_items_from_string(contents).await?; + println!("created_item_count={}", created.len()); + for (index, item) in created.iter().enumerate() { + println!( + "[{index}] type_url={} raw_len={}", + item.type_url, + item.value.len() + ); + } + } Command::AddToSelection { item_ids } => { let summary = client.add_to_selection(item_ids).await?; println!("selection_total={}", summary.total_items); @@ -1456,6 +1470,27 @@ fn parse_args_from(mut args: Vec) -> Result<(CliConfig, Command), KiCadE let item_ids = parse_item_ids(&args[1..], "delete-items")?; Command::DeleteItems { item_ids } } + "parse-create-items" => { + let mut contents = None; + let mut i = 1; + while i < args.len() { + if args[i] == "--contents" { + let value = args.get(i + 1).ok_or_else(|| KiCadError::Config { + reason: "missing value for parse-create-items --contents".to_string(), + })?; + contents = Some(value.clone()); + i += 2; + continue; + } + i += 1; + } + + Command::ParseCreateItemsFromString { + contents: contents.ok_or_else(|| KiCadError::Config { + reason: "parse-create-items requires `--contents `".to_string(), + })?, + } + } "add-to-selection" => { let item_ids = parse_item_ids(&args[1..], "add-to-selection")?; Command::AddToSelection { item_ids } @@ -1930,7 +1965,7 @@ fn default_config() -> CliConfig { fn print_help() { println!( - "kicad-ipc-cli\n\nUSAGE:\n cargo run --bin kicad-ipc-cli -- [--socket URI] [--token TOKEN] [--client-name NAME] [--timeout-ms N] [command options]\n\nCOMMANDS:\n ping Check IPC connectivity\n version Fetch KiCad version\n kicad-binary-path [--binary-name ]\n Resolve absolute path for a KiCad binary (default: kicad-cli)\n plugin-settings-path [--identifier ]\n Resolve writeable plugin settings directory (default: kicad-ipc-rust)\n open-docs [--type ] List open docs (default type: pcb)\n project-path Get current project path from open PCB docs\n board-open Exit non-zero if no PCB doc is open\n net-classes List project netclass definitions\n text-variables List text variables for current board document\n expand-text-variables Expand variables in provided text values\n Options: --text (repeatable)\n text-extents Measure text bounding box\n Options: --text \n text-as-shapes Convert text to rendered shapes\n Options: --text (repeatable)\n nets List board nets (requires one open PCB)\n netlist-pads Emit pad-level netlist data (with footprint context)\n items-by-id --id ... Show parsed details for specific item IDs\n item-bbox --id ... Show bounding boxes for item IDs\n hit-test --id --x-nm --y-nm [--tolerance-nm ]\n Hit-test one item at a point\n types-pcb List PCB KiCad object type IDs from proto enum\n items-raw --type-id ... Dump raw Any payloads for requested item type IDs\n items-raw-all-pcb [--debug] Dump all PCB item payloads across all PCB object types\n pad-shape-polygon --pad-id ... --layer-id [--debug]\n Dump pad polygons on a target layer\n padstack-presence --item-id ... --layer-id ... [--debug]\n Check padstack shape presence matrix across layers\n title-block Show title block fields\n board-as-string Dump board as KiCad s-expression text\n selection-as-string Dump current selection as KiCad s-expression text\n stackup Show typed board stackup\n graphics-defaults Show typed graphics defaults\n appearance Show typed editor appearance settings\n set-appearance --inactive-layer-display \n --net-color-display \n --board-flip \n --ratsnest-display \n Set editor appearance settings\n inject-drc-error --severity --message [--x-nm --y-nm ] [--item-id ...]\n Inject a DRC marker (severity: warning|error|exclusion|ignore|info|action|debug|undefined)\n refill-zones [--zone-id ...]\n Refill all zones or a provided subset\n netclass Show typed netclass map for current board nets\n proto-coverage-board-read Print board-read command coverage vs proto\n board-read-report [--out P] Write markdown board reconstruction report\n enabled-layers List enabled board layers\n set-enabled-layers --copper-layer-count [--layer-id ...]\n Set enabled board layer set\n active-layer Show active board layer\n set-active-layer --layer-id \n Set active board layer\n visible-layers Show currently visible board layers\n set-visible-layers --layer-id ...\n Set visible board layers\n board-origin [--type ] Show board origin (`grid` default, or `drill`)\n set-board-origin --type --x-nm --y-nm \n Set board origin (`grid` or `drill`)\n refresh-editor [--frame ] Refresh a specific editor frame (default: pcb)\n begin-commit Start staged commit and print commit ID\n end-commit --id [--action ] [--message ]\n End staged commit with commit/drop action\n save-doc Save current board document\n save-copy --path [--overwrite] [--include-project]\n Save current board document to a new location\n revert-doc Revert current board document from disk\n run-action --action Run a raw KiCad tool action\n create-items --item = ... [--container-id ]\n Create raw Any payload items in current board document\n update-items --item = ...\n Update raw Any payload items in current board document\n delete-items --id ...\n Delete item IDs from current board document\n add-to-selection --id ...\n Add items to current selection\n remove-from-selection --id ...\n Remove items from current selection\n clear-selection Clear current item selection\n selection-summary Show current selection item type counts\n selection-details Show parsed details for selected items\n selection-raw Show raw Any payload bytes for selected items\n smoke ping + version + board-open summary\n help Show help\n\nTYPES:\n schematic | symbol | pcb | footprint | drawing-sheet | project\n" + "kicad-ipc-cli\n\nUSAGE:\n cargo run --bin kicad-ipc-cli -- [--socket URI] [--token TOKEN] [--client-name NAME] [--timeout-ms N] [command options]\n\nCOMMANDS:\n ping Check IPC connectivity\n version Fetch KiCad version\n kicad-binary-path [--binary-name ]\n Resolve absolute path for a KiCad binary (default: kicad-cli)\n plugin-settings-path [--identifier ]\n Resolve writeable plugin settings directory (default: kicad-ipc-rust)\n open-docs [--type ] List open docs (default type: pcb)\n project-path Get current project path from open PCB docs\n board-open Exit non-zero if no PCB doc is open\n net-classes List project netclass definitions\n text-variables List text variables for current board document\n expand-text-variables Expand variables in provided text values\n Options: --text (repeatable)\n text-extents Measure text bounding box\n Options: --text \n text-as-shapes Convert text to rendered shapes\n Options: --text (repeatable)\n nets List board nets (requires one open PCB)\n netlist-pads Emit pad-level netlist data (with footprint context)\n items-by-id --id ... Show parsed details for specific item IDs\n item-bbox --id ... Show bounding boxes for item IDs\n hit-test --id --x-nm --y-nm [--tolerance-nm ]\n Hit-test one item at a point\n types-pcb List PCB KiCad object type IDs from proto enum\n items-raw --type-id ... Dump raw Any payloads for requested item type IDs\n items-raw-all-pcb [--debug] Dump all PCB item payloads across all PCB object types\n pad-shape-polygon --pad-id ... --layer-id [--debug]\n Dump pad polygons on a target layer\n padstack-presence --item-id ... --layer-id ... [--debug]\n Check padstack shape presence matrix across layers\n title-block Show title block fields\n board-as-string Dump board as KiCad s-expression text\n selection-as-string Dump current selection as KiCad s-expression text\n stackup Show typed board stackup\n graphics-defaults Show typed graphics defaults\n appearance Show typed editor appearance settings\n set-appearance --inactive-layer-display \n --net-color-display \n --board-flip \n --ratsnest-display \n Set editor appearance settings\n inject-drc-error --severity --message [--x-nm --y-nm ] [--item-id ...]\n Inject a DRC marker (severity: warning|error|exclusion|ignore|info|action|debug|undefined)\n refill-zones [--zone-id ...]\n Refill all zones or a provided subset\n netclass Show typed netclass map for current board nets\n proto-coverage-board-read Print board-read command coverage vs proto\n board-read-report [--out P] Write markdown board reconstruction report\n enabled-layers List enabled board layers\n set-enabled-layers --copper-layer-count [--layer-id ...]\n Set enabled board layer set\n active-layer Show active board layer\n set-active-layer --layer-id \n Set active board layer\n visible-layers Show currently visible board layers\n set-visible-layers --layer-id ...\n Set visible board layers\n board-origin [--type ] Show board origin (`grid` default, or `drill`)\n set-board-origin --type --x-nm --y-nm \n Set board origin (`grid` or `drill`)\n refresh-editor [--frame ] Refresh a specific editor frame (default: pcb)\n begin-commit Start staged commit and print commit ID\n end-commit --id [--action ] [--message ]\n End staged commit with commit/drop action\n save-doc Save current board document\n save-copy --path [--overwrite] [--include-project]\n Save current board document to a new location\n revert-doc Revert current board document from disk\n run-action --action Run a raw KiCad tool action\n create-items --item = ... [--container-id ]\n Create raw Any payload items in current board document\n update-items --item = ...\n Update raw Any payload items in current board document\n delete-items --id ...\n Delete item IDs from current board document\n parse-create-items --contents \n Parse s-expression and create resulting items\n add-to-selection --id ...\n Add items to current selection\n remove-from-selection --id ...\n Remove items from current selection\n clear-selection Clear current item selection\n selection-summary Show current selection item type counts\n selection-details Show parsed details for selected items\n selection-raw Show raw Any payload bytes for selected items\n smoke ping + version + board-open summary\n help Show help\n\nTYPES:\n schematic | symbol | pcb | footprint | drawing-sheet | project\n" ); } @@ -2789,6 +2824,23 @@ mod tests { } } + #[test] + fn parse_args_parses_parse_create_items() { + let (_, command) = parse_args_from(vec![ + "parse-create-items".to_string(), + "--contents".to_string(), + "(kicad_pcb (version 20240108))".to_string(), + ]) + .expect("parse-create-items args should parse"); + + match command { + Command::ParseCreateItemsFromString { contents } => { + assert_eq!(contents, "(kicad_pcb (version 20240108))"); + } + other => panic!("unexpected command variant: {other:?}"), + } + } + #[test] fn parse_args_parses_set_enabled_layers() { let (_, command) = parse_args_from(vec![