diff --git a/README.md b/README.md index ccee33d..91ff478 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,7 @@ Deferred manual/runtime verification (implemented after 2026-02-20 while user un - `RunAction` - `CreateItems` - `UpdateItems` +- `DeleteItems` ## KiCad v10 RC1.1 API Completion Matrix @@ -61,11 +62,11 @@ Legend: | Section | Proto Commands | Implemented | Coverage | | --- | ---: | ---: | ---: | | Common (base) | 6 | 6 | 100% | -| Common editor/document | 23 | 21 | 91% | +| Common editor/document | 23 | 22 | 96% | | Project manager | 5 | 3 | 60% | | Board editor (PCB) | 22 | 20 | 91% | | Schematic editor (dedicated proto commands) | 0 | 0 | n/a | -| **Total** | **56** | **50** | **89%** | +| **Total** | **56** | **51** | **91%** | ### Common (base) @@ -94,7 +95,7 @@ Legend: | `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` | Implemented | `KiCadClient::update_items_raw`, `KiCadClient::update_items` | -| `DeleteItems` | Not yet | - | +| `DeleteItems` | Implemented | `KiCadClient::delete_items_raw`, `KiCadClient::delete_items` | | `GetBoundingBox` | Implemented | `KiCadClient::get_item_bounding_boxes` | | `GetSelection` | Implemented | `KiCadClient::get_selection_raw`, `KiCadClient::get_selection`, `KiCadClient::get_selection_summary`, `KiCadClient::get_selection_details` | | `AddToSelection` | Implemented | `KiCadClient::add_to_selection_raw`, `KiCadClient::add_to_selection` | diff --git a/docs/TEST_CLI.md b/docs/TEST_CLI.md index 5f4b2f8..d4d4a17 100644 --- a/docs/TEST_CLI.md +++ b/docs/TEST_CLI.md @@ -199,6 +199,12 @@ Update raw Any item payload(s): cargo run --bin kicad-ipc-cli -- update-items --item type.googleapis.com/kiapi.board.types.Text= ``` +Delete items by ID: + +```bash +cargo run --bin kicad-ipc-cli -- delete-items --id --id +``` + Show summary of current PCB selection by item type: ```bash diff --git a/src/client.rs b/src/client.rs index d52b3a7..22182b9 100644 --- a/src/client.rs +++ b/src/client.rs @@ -78,6 +78,7 @@ 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_DELETE_ITEMS: &str = "kiapi.common.commands.DeleteItems"; 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"; @@ -118,6 +119,7 @@ const RES_BEGIN_COMMIT_RESPONSE: &str = "kiapi.common.commands.BeginCommitRespon 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_DELETE_ITEMS_RESPONSE: &str = "kiapi.common.commands.DeleteItemsResponse"; 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"; @@ -695,6 +697,44 @@ impl KiCadClient { .collect() } + pub async fn delete_items_raw( + &self, + item_ids: Vec, + ) -> Result { + let command = common_commands::DeleteItems { + header: Some(self.current_board_item_header().await?), + item_ids: item_ids + .into_iter() + .map(|value| common_types::Kiid { value }) + .collect(), + }; + + let response = self + .send_command(envelope::pack_any(&command, CMD_DELETE_ITEMS)) + .await?; + response_payload_as_any(response, RES_DELETE_ITEMS_RESPONSE) + } + + pub async fn delete_items(&self, item_ids: Vec) -> Result, KiCadError> { + let payload = self.delete_items_raw(item_ids).await?; + let response: common_commands::DeleteItemsResponse = + decode_any(&payload, RES_DELETE_ITEMS_RESPONSE)?; + ensure_item_request_ok(response.status)?; + + response + .deleted_items + .into_iter() + .map(|row| { + ensure_item_deletion_status_ok(row.status)?; + row.id + .map(|id| id.value) + .ok_or_else(|| KiCadError::InvalidResponse { + reason: "DeleteItemsResponse missing deleted item id".to_string(), + }) + }) + .collect() + } + pub async fn get_nets(&self) -> Result, KiCadError> { let board = self.current_board_document_proto().await?; let command = board_commands::GetNets { @@ -2160,6 +2200,19 @@ fn ensure_item_status_ok(status: Option) -> Result< Ok(()) } +fn ensure_item_deletion_status_ok(status: i32) -> Result<(), KiCadError> { + let code = common_commands::ItemDeletionStatus::try_from(status) + .unwrap_or(common_commands::ItemDeletionStatus::IdsUnknown); + + if code != common_commands::ItemDeletionStatus::IdsOk { + return Err(KiCadError::ItemStatus { + code: code.as_str_name().to_string(), + }); + } + + Ok(()) +} + fn map_item_bounding_boxes( item_ids: Vec, boxes: Vec, @@ -3281,13 +3334,13 @@ fn default_client_name() -> String { mod tests { use super::{ any_to_pretty_debug, board_editor_appearance_settings_to_proto, commit_action_to_proto, - drc_severity_to_proto, ensure_item_request_ok, ensure_item_status_ok, layer_to_model, - map_commit_session, map_hit_test_result, map_item_bounding_boxes, map_polygon_with_holes, - map_run_action_status, model_document_to_proto, normalize_socket_uri, - pad_netlist_from_footprint_items, response_payload_as_any, select_single_board_document, - select_single_project_path, selection_item_detail, summarize_item_details, - summarize_selection, text_horizontal_alignment_to_proto, text_spec_to_proto, - PCB_OBJECT_TYPES, + drc_severity_to_proto, ensure_item_deletion_status_ok, ensure_item_request_ok, + ensure_item_status_ok, layer_to_model, map_commit_session, map_hit_test_result, + map_item_bounding_boxes, map_polygon_with_holes, map_run_action_status, + model_document_to_proto, normalize_socket_uri, pad_netlist_from_footprint_items, + response_payload_as_any, select_single_board_document, select_single_project_path, + selection_item_detail, summarize_item_details, summarize_selection, + text_horizontal_alignment_to_proto, text_spec_to_proto, PCB_OBJECT_TYPES, }; use crate::error::KiCadError; use crate::model::common::{ @@ -3713,6 +3766,23 @@ mod tests { } } + #[test] + fn ensure_item_deletion_status_ok_accepts_ok_and_rejects_non_ok() { + assert!(ensure_item_deletion_status_ok( + crate::proto::kiapi::common::commands::ItemDeletionStatus::IdsOk as i32 + ) + .is_ok()); + + let err = ensure_item_deletion_status_ok( + crate::proto::kiapi::common::commands::ItemDeletionStatus::IdsNonexistent as i32, + ) + .expect_err("non-OK item deletion status should fail"); + match err { + KiCadError::ItemStatus { code } => assert_eq!(code, "IDS_NONEXISTENT"), + _ => panic!("expected item status error"), + } + } + #[test] fn summarize_item_details_reports_unknown_payload_as_unparsed() { let items = vec![prost_types::Any { diff --git a/test-scripts/kicad-ipc-cli.rs b/test-scripts/kicad-ipc-cli.rs index 208020e..7037f42 100644 --- a/test-scripts/kicad-ipc-cli.rs +++ b/test-scripts/kicad-ipc-cli.rs @@ -107,6 +107,9 @@ enum Command { UpdateItems { items: Vec, }, + DeleteItems { + item_ids: Vec, + }, AddToSelection { item_ids: Vec, }, @@ -506,6 +509,13 @@ async fn run() -> Result<(), KiCadError> { ); } } + Command::DeleteItems { item_ids } => { + let deleted = client.delete_items(item_ids).await?; + println!("deleted_item_count={}", deleted.len()); + for (index, item_id) in deleted.iter().enumerate() { + println!("[{index}] id={item_id}"); + } + } Command::AddToSelection { item_ids } => { let summary = client.add_to_selection(item_ids).await?; println!("selection_total={}", summary.total_items); @@ -1442,6 +1452,10 @@ fn parse_args_from(mut args: Vec) -> Result<(CliConfig, Command), KiCadE Command::UpdateItems { items } } + "delete-items" => { + let item_ids = parse_item_ids(&args[1..], "delete-items")?; + Command::DeleteItems { item_ids } + } "add-to-selection" => { let item_ids = parse_item_ids(&args[1..], "add-to-selection")?; Command::AddToSelection { item_ids } @@ -1916,7 +1930,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 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 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" ); } @@ -2756,6 +2770,25 @@ mod tests { } } + #[test] + fn parse_args_parses_delete_items() { + let (_, command) = parse_args_from(vec![ + "delete-items".to_string(), + "--id".to_string(), + "item-1".to_string(), + "--id".to_string(), + "item-2".to_string(), + ]) + .expect("delete-items args should parse"); + + match command { + Command::DeleteItems { item_ids } => { + assert_eq!(item_ids, vec!["item-1".to_string(), "item-2".to_string()]); + } + other => panic!("unexpected command variant: {other:?}"), + } + } + #[test] fn parse_args_parses_set_enabled_layers() { let (_, command) = parse_args_from(vec![