From b26a04e392eb4d7f81992b547a8789a9ede8061e Mon Sep 17 00:00:00 2001 From: Milind Sharma Date: Fri, 20 Feb 2026 18:36:18 +0800 Subject: [PATCH] feat(common): add UpdateItems API and CLI command --- README.md | 7 ++-- docs/TEST_CLI.md | 6 +++ src/client.rs | 38 +++++++++++++++++++ test-scripts/kicad-ipc-cli.rs | 69 ++++++++++++++++++++++++++++++++++- 4 files changed, 116 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 721d1fd..ccee33d 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,7 @@ Deferred manual/runtime verification (implemented after 2026-02-20 while user un - `RevertDocument` - `RunAction` - `CreateItems` +- `UpdateItems` ## KiCad v10 RC1.1 API Completion Matrix @@ -60,11 +61,11 @@ Legend: | Section | Proto Commands | Implemented | Coverage | | --- | ---: | ---: | ---: | | Common (base) | 6 | 6 | 100% | -| Common editor/document | 23 | 20 | 87% | +| Common editor/document | 23 | 21 | 91% | | Project manager | 5 | 3 | 60% | | Board editor (PCB) | 22 | 20 | 91% | | Schematic editor (dedicated proto commands) | 0 | 0 | n/a | -| **Total** | **56** | **49** | **88%** | +| **Total** | **56** | **50** | **89%** | ### Common (base) @@ -92,7 +93,7 @@ Legend: | `CreateItems` | Implemented | `KiCadClient::create_items_raw`, `KiCadClient::create_items` | | `GetItems` | Implemented | `KiCadClient::get_items_raw_by_type_codes`, `KiCadClient::get_items_by_type_codes`, `KiCadClient::get_items_details_by_type_codes`, `KiCadClient::get_all_pcb_items_raw`, `KiCadClient::get_all_pcb_items`, `KiCadClient::get_all_pcb_items_details`, `KiCadClient::get_pad_netlist` | | `GetItemsById` | Implemented | `KiCadClient::get_items_by_id_raw`, `KiCadClient::get_items_by_id`, `KiCadClient::get_items_by_id_details` | -| `UpdateItems` | Not yet | - | +| `UpdateItems` | Implemented | `KiCadClient::update_items_raw`, `KiCadClient::update_items` | | `DeleteItems` | Not yet | - | | `GetBoundingBox` | Implemented | `KiCadClient::get_item_bounding_boxes` | | `GetSelection` | Implemented | `KiCadClient::get_selection_raw`, `KiCadClient::get_selection`, `KiCadClient::get_selection_summary`, `KiCadClient::get_selection_details` | diff --git a/docs/TEST_CLI.md b/docs/TEST_CLI.md index 1d53d60..5f4b2f8 100644 --- a/docs/TEST_CLI.md +++ b/docs/TEST_CLI.md @@ -193,6 +193,12 @@ Create raw Any item payload(s): cargo run --bin kicad-ipc-cli -- create-items --item type.googleapis.com/kiapi.board.types.Text= ``` +Update raw Any item payload(s): + +```bash +cargo run --bin kicad-ipc-cli -- update-items --item type.googleapis.com/kiapi.board.types.Text= +``` + Show summary of current PCB selection by item type: ```bash diff --git a/src/client.rs b/src/client.rs index ba03b73..d52b3a7 100644 --- a/src/client.rs +++ b/src/client.rs @@ -77,6 +77,7 @@ const CMD_CLEAR_SELECTION: &str = "kiapi.common.commands.ClearSelection"; const CMD_BEGIN_COMMIT: &str = "kiapi.common.commands.BeginCommit"; 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_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"; @@ -116,6 +117,7 @@ const RES_SELECTION_RESPONSE: &str = "kiapi.common.commands.SelectionResponse"; const RES_BEGIN_COMMIT_RESPONSE: &str = "kiapi.common.commands.BeginCommitResponse"; const RES_END_COMMIT_RESPONSE: &str = "kiapi.common.commands.EndCommitResponse"; const RES_CREATE_ITEMS_RESPONSE: &str = "kiapi.common.commands.CreateItemsResponse"; +const RES_UPDATE_ITEMS_RESPONSE: &str = "kiapi.common.commands.UpdateItemsResponse"; const RES_GET_ITEMS_RESPONSE: &str = "kiapi.common.commands.GetItemsResponse"; const RES_GET_BOUNDING_BOX_RESPONSE: &str = "kiapi.common.commands.GetBoundingBoxResponse"; const RES_HIT_TEST_RESPONSE: &str = "kiapi.common.commands.HitTestResponse"; @@ -657,6 +659,42 @@ impl KiCadClient { .collect() } + pub async fn update_items_raw( + &self, + items: Vec, + ) -> Result { + let command = common_commands::UpdateItems { + header: Some(self.current_board_item_header().await?), + items, + }; + + let response = self + .send_command(envelope::pack_any(&command, CMD_UPDATE_ITEMS)) + .await?; + response_payload_as_any(response, RES_UPDATE_ITEMS_RESPONSE) + } + + pub async fn update_items( + &self, + items: Vec, + ) -> Result, KiCadError> { + let payload = self.update_items_raw(items).await?; + let response: common_commands::UpdateItemsResponse = + decode_any(&payload, RES_UPDATE_ITEMS_RESPONSE)?; + ensure_item_request_ok(response.status)?; + + response + .updated_items + .into_iter() + .map(|row| { + ensure_item_status_ok(row.status)?; + row.item.ok_or_else(|| KiCadError::InvalidResponse { + reason: "UpdateItemsResponse missing updated 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 05bd803..208020e 100644 --- a/test-scripts/kicad-ipc-cli.rs +++ b/test-scripts/kicad-ipc-cli.rs @@ -104,6 +104,9 @@ enum Command { items: Vec, container_id: Option, }, + UpdateItems { + items: Vec, + }, AddToSelection { item_ids: Vec, }, @@ -492,6 +495,17 @@ async fn run() -> Result<(), KiCadError> { ); } } + Command::UpdateItems { items } => { + let updated = client.update_items(items).await?; + println!("updated_item_count={}", updated.len()); + for (index, item) in updated.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); @@ -1397,6 +1411,37 @@ fn parse_args_from(mut args: Vec) -> Result<(CliConfig, Command), KiCadE container_id, } } + "update-items" => { + let mut items = Vec::new(); + let mut i = 1; + while i < args.len() { + if args[i] == "--item" { + let value = args.get(i + 1).ok_or_else(|| KiCadError::Config { + reason: "missing value for update-items --item".to_string(), + })?; + let (type_url, hex) = + value.split_once('=').ok_or_else(|| KiCadError::Config { + reason: "update-items --item requires `=`".to_string(), + })?; + items.push(prost_types::Any { + type_url: type_url.to_string(), + value: hex_to_bytes(hex).map_err(|reason| KiCadError::Config { reason })?, + }); + i += 2; + continue; + } + i += 1; + } + + if items.is_empty() { + return Err(KiCadError::Config { + reason: "update-items requires one or more `--item =` values" + .to_string(), + }); + } + + Command::UpdateItems { items } + } "add-to-selection" => { let item_ids = parse_item_ids(&args[1..], "add-to-selection")?; Command::AddToSelection { item_ids } @@ -1871,7 +1916,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 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 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" ); } @@ -2689,6 +2734,28 @@ mod tests { } } + #[test] + fn parse_args_parses_update_items() { + let (_, command) = parse_args_from(vec![ + "update-items".to_string(), + "--item".to_string(), + "type.googleapis.com/kiapi.board.types.Text=0a00".to_string(), + ]) + .expect("update-items args should parse"); + + match command { + Command::UpdateItems { items } => { + assert_eq!(items.len(), 1); + assert_eq!( + items[0].type_url, + "type.googleapis.com/kiapi.board.types.Text" + ); + assert_eq!(items[0].value, vec![0x0a, 0x00]); + } + other => panic!("unexpected command variant: {other:?}"), + } + } + #[test] fn parse_args_parses_set_enabled_layers() { let (_, command) = parse_args_from(vec![