forked from 1b-agent/opencadstudio-upstream
Merge pull request #1423 from felixriestra:pr/python-host-model
The bundled `opencad.python` plugin drives OCS through plugin API v7: all 43 canvas entity kinds, the drawing tables, and OCS's own commands run step by step. RustPython stays in the plugin process — the plugin crate is outside the workspace with its own lock file, so the application's own dependencies are unchanged. Reconciled with the plugin command work that landed as #1425, which the branch was written before: - Both added `impl Drop for PluginProcessInteractiveAdapter`, which git merges silently into two impls that do not compile. One body now cancels the command and then drops it from the runner, in that order: a plugin waiting on a step has to be released before the runner forgets the command. - `execute_command` (#1425) and `run_command` (#1423) are both routes from a script to the command line, and only the second was guarded. The SCRIPTCOMMANDS switch and the denylist are shared now, so neither route is the unguarded one. - `run_command` dispatched with plugin dispatch still enabled, so a script naming a plugin command re-entered the plugin that was blocked waiting for it. It sets the suppression flag for the length of the dispatch, as `execute_command` does. The denylist read the command as typed, while the dispatcher resolves aliases: a user-defined `Q` for `QUIT` (ALIASEDIT writes those) walked past it. It resolves the alias first. Also: the active-command comparison ran on every message, a mouse move included, allocating two strings for names that are already `&'static str`; SCRIPTCOMMANDS' own messages go through the translation macros; and `docs/.DS_Store` (now ignored) and an unrelated RTF note about constraint commands are out of the tree. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
commit
41ecc0c458
72 files changed
+30614
-91
No files matched your search
@@ -0,0 +1,93 @@
|
|||||||
|
name: Python host check
|
||||||
|
|
||||||
|
# Checks the scripting host API and the bundled Python plugin on Linux and Windows,
|
||||||
|
# where the plugin is loaded from `plugins/opencad.python` next to the executable.
|
||||||
|
# The plugin tests talk to a real plugin process over IPC. They are skipped, and
|
||||||
|
# report success, unless OCS_TEST_PYTHON_PLUGIN and OCS_PLUGIN_RUNNER_EXE are set,
|
||||||
|
# so this workflow sets both to the freshly built plugin and executable.
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
paths:
|
||||||
|
- 'crates/ocs_plugin_api/**'
|
||||||
|
- 'plugins/opencad-python/**'
|
||||||
|
- 'src/app/plugin_host.rs'
|
||||||
|
- 'src/app/control/**'
|
||||||
|
- 'src/app/commands/**'
|
||||||
|
- 'src/app/settings.rs'
|
||||||
|
- 'Cargo.toml'
|
||||||
|
- 'Cargo.lock'
|
||||||
|
- '.github/workflows/python-host-check.yml'
|
||||||
|
push:
|
||||||
|
tags: ['pr-check-*']
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
env:
|
||||||
|
CARGO_TERM_COLOR: always
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
check:
|
||||||
|
name: ${{ matrix.name }}
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- name: linux
|
||||||
|
os: ubuntu-22.04
|
||||||
|
library: libopencad_python.so
|
||||||
|
exe: OpenCADStudio
|
||||||
|
- name: windows
|
||||||
|
os: windows-latest
|
||||||
|
library: opencad_python.dll
|
||||||
|
exe: OpenCADStudio.exe
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
shell: bash
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- uses: dtolnay/rust-toolchain@stable
|
||||||
|
|
||||||
|
- uses: Swatinem/rust-cache@v2
|
||||||
|
with:
|
||||||
|
key: python-host-check
|
||||||
|
workspaces: |
|
||||||
|
.
|
||||||
|
plugins/opencad-python
|
||||||
|
|
||||||
|
- name: Install dependencies (Linux)
|
||||||
|
if: runner.os == 'Linux'
|
||||||
|
run: |
|
||||||
|
sudo apt-get update -q
|
||||||
|
sudo apt-get install -y \
|
||||||
|
libgl1-mesa-dev libx11-dev libxcursor-dev libxi-dev libxrandr-dev \
|
||||||
|
libxkbcommon-dev libwayland-dev libfontconfig1-dev libfreetype6-dev
|
||||||
|
|
||||||
|
- name: Plugin API tests
|
||||||
|
run: cargo test --locked -p ocs_plugin_api --features host
|
||||||
|
|
||||||
|
- name: Stage the bundled plugin
|
||||||
|
run: bash plugins/opencad-python/tools/stage-bundled.sh "$PWD/work/plugin" --debug
|
||||||
|
|
||||||
|
- name: Build the application (the plugin runner)
|
||||||
|
run: cargo build --locked --bin OpenCADStudio
|
||||||
|
|
||||||
|
- name: Plugin crate tests
|
||||||
|
working-directory: plugins/opencad-python
|
||||||
|
run: cargo test --locked
|
||||||
|
|
||||||
|
- name: Python model unit tests
|
||||||
|
working-directory: plugins/opencad-python
|
||||||
|
run: python3 -m unittest discover -s tests
|
||||||
|
|
||||||
|
- name: Host tests over real IPC
|
||||||
|
env:
|
||||||
|
OCS_TEST_PYTHON_PLUGIN: ${{ github.workspace }}/work/plugin/${{ matrix.library }}
|
||||||
|
OCS_PLUGIN_RUNNER_EXE: ${{ github.workspace }}/target/debug/${{ matrix.exe }}
|
||||||
|
run: |
|
||||||
|
test -f "$OCS_TEST_PYTHON_PLUGIN" || { echo "staged plugin missing: $OCS_TEST_PYTHON_PLUGIN"; exit 1; }
|
||||||
|
test -f "$OCS_PLUGIN_RUNNER_EXE" || { echo "runner missing: $OCS_PLUGIN_RUNNER_EXE"; exit 1; }
|
||||||
|
cargo test --locked --lib -- --test-threads=1 python
|
||||||
@@ -478,6 +478,11 @@ jobs:
|
|||||||
chmod +x "$APP/Contents/MacOS/OpenCADStudio" "$APP/Contents/MacOS/OpenCADStudio-App"
|
chmod +x "$APP/Contents/MacOS/OpenCADStudio" "$APP/Contents/MacOS/OpenCADStudio-App"
|
||||||
cp AppIcon.icns "$APP/Contents/Resources/AppIcon.icns"
|
cp AppIcon.icns "$APP/Contents/Resources/AppIcon.icns"
|
||||||
cp DWG.icns DXF.icns "$APP/Contents/Resources/"
|
cp DWG.icns DXF.icns "$APP/Contents/Resources/"
|
||||||
|
# First-party Python scripting plugin. It remains out of process and
|
||||||
|
# uses the same API/toolchain as this host build.
|
||||||
|
bash plugins/opencad-python/tools/stage-bundled.sh \
|
||||||
|
"$APP/Contents/Resources/plugins/opencad.python" \
|
||||||
|
--target aarch64-apple-darwin
|
||||||
# QuickLook thumbnail extension.
|
# QuickLook thumbnail extension.
|
||||||
cp -R DWGThumbnail.appex "$APP/Contents/PlugIns/"
|
cp -R DWGThumbnail.appex "$APP/Contents/PlugIns/"
|
||||||
# Substitute version into Info.plist.
|
# Substitute version into Info.plist.
|
||||||
|
|||||||
@@ -41,3 +41,6 @@ __pycache__/
|
|||||||
|
|
||||||
# Single-instance lock files the app writes next to an open drawing
|
# Single-instance lock files the app writes next to an open drawing
|
||||||
*.ocs.lock
|
*.ocs.lock
|
||||||
|
|
||||||
|
# macOS Finder metadata
|
||||||
|
.DS_Store
|
||||||
@@ -44,12 +44,14 @@ The host and each plugin run in separate OS processes. The host re-executes itse
|
|||||||
|
|
||||||
## Versioning and ABI stability
|
## Versioning and ABI stability
|
||||||
|
|
||||||
- `API_VERSION` (currently `5`) is the host's advertised major.
|
- `API_VERSION` (currently `6`) is the host's advertised major.
|
||||||
- `API_VERSION_MIN_SUPPORTED` (currently `2`) is the oldest plugin major the host loads.
|
- `API_VERSION_MIN_SUPPORTED` (currently `2`) is the oldest plugin major the host loads.
|
||||||
- `OCS_PLUGIN_MAX_API_VERSION` can cap the accepted major at runtime (e.g. `4` to disable V5).
|
- `OCS_PLUGIN_MAX_API_VERSION` can cap the accepted major at runtime (e.g. `5` to disable V6).
|
||||||
- A plugin built against major `N` runs on a host whose major is `>= N` because new vtable entries and enum variants are appended at the end.
|
- A plugin built against major `N` runs on a host whose major is `>= N` because new vtable entries and enum variants are appended at the end.
|
||||||
- V4 introduces the **acadrust gate**: plugins targeting API v4 or later must resolve the same `acadrust` source as the host (see [`src/version_info.rs`](src/version_info.rs)).
|
- V4 introduces the **acadrust gate**: plugins targeting API v4 or later must resolve the same `acadrust` source as the host (see [`src/version_info.rs`](src/version_info.rs)).
|
||||||
- V5 introduces `BuiltinPlugin::on_load` and tab-keyed document paths.
|
- V5 introduces `BuiltinPlugin::on_load` and tab-keyed document paths.
|
||||||
|
- V6 appends typed system-variable access to `HostApi`; the host currently
|
||||||
|
supports `CLAYER` and `SNAPANG` (plus a read-only `CTAB`).
|
||||||
|
|
||||||
The runtime enforces three gates:
|
The runtime enforces three gates:
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ license = "GPL-3.0-only"
|
|||||||
# registry types (`type_registry_types.rs`). The host feature no longer needs
|
# registry types (`type_registry_types.rs`). The host feature no longer needs
|
||||||
# to enable it explicitly.
|
# to enable it explicitly.
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
serde_json = { version = "1", optional = true }
|
||||||
|
|
||||||
# Pulled in only by the `host` feature, which adds the `acadrust`-typed
|
# Pulled in only by the `host` feature, which adds the `acadrust`-typed
|
||||||
# `HostApi` runtime surface. The default crate stays dependency-free so engine
|
# `HostApi` runtime surface. The default crate stays dependency-free so engine
|
||||||
@@ -30,7 +31,7 @@ getrandom = { version = "0.2", optional = true }
|
|||||||
# Enables the runtime host surface (`HostApi` trait) and the out-of-process
|
# Enables the runtime host surface (`HostApi` trait) and the out-of-process
|
||||||
# plugin runtime. The OpenCADStudio binary turns this on; pure-data consumers
|
# plugin runtime. The OpenCADStudio binary turns this on; pure-data consumers
|
||||||
# leave it off.
|
# leave it off.
|
||||||
host = ["dep:acadrust", "dep:interprocess", "dep:bincode", "dep:serde_bytes", "dep:thiserror", "dep:libloading", "dep:memmap2", "dep:rkyv", "dep:getrandom"]
|
host = ["dep:acadrust", "dep:serde_json", "dep:interprocess", "dep:bincode", "dep:serde_bytes", "dep:thiserror", "dep:libloading", "dep:memmap2", "dep:rkyv", "dep:getrandom"]
|
||||||
|
|
||||||
[build-dependencies]
|
[build-dependencies]
|
||||||
serde-reflection = "0.6"
|
serde-reflection = "0.6"
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ cheaply. The runtime host surface is enabled by the `host` feature.
|
|||||||
## Plugin Architecture
|
## Plugin Architecture
|
||||||
|
|
||||||
OCS is scriptable and extensible through a versioned plugin API. The API
|
OCS is scriptable and extensible through a versioned plugin API. The API
|
||||||
supports four major generations: **V2**, **V3**, **V4**, and **V5**. Each
|
supports five major generations: **V2**, **V3**, **V4**, **V5**, and **V6**. Each
|
||||||
generation keeps the previous ABI stable by appending new vtable entries and new
|
generation keeps the previous ABI stable by appending new vtable entries and new
|
||||||
enum variants at the end, so older plugins continue to load on newer hosts.
|
enum variants at the end, so older plugins continue to load on newer hosts.
|
||||||
|
|
||||||
@@ -19,10 +19,11 @@ enum variants at the end, so older plugins continue to load on newer hosts.
|
|||||||
| **V3** | Out-of-process runner | Local cached `document()`/`document_mut()` + shared-memory `DocumentReader`/`document_view` for large reads | New vtable entries appended; new `PluginRequest`/`PluginResponse` variants appended |
|
| **V3** | Out-of-process runner | Local cached `document()`/`document_mut()` + shared-memory `DocumentReader`/`document_view` for large reads | New vtable entries appended; new `PluginRequest`/`PluginResponse` variants appended |
|
||||||
| **V4** | Out-of-process runner over a multiplexed local socket | Full-duplex notifications + asynchronous REPL `ExecuteCode` | New `HostToPluginV4`/`PluginToHostV4` frame layer; `BuiltinPlugin::on_notification` and `start_execute_code` appended to trait |
|
| **V4** | Out-of-process runner over a multiplexed local socket | Full-duplex notifications + asynchronous REPL `ExecuteCode` | New `HostToPluginV4`/`PluginToHostV4` frame layer; `BuiltinPlugin::on_notification` and `start_execute_code` appended to trait |
|
||||||
| **V5** | V4 multiplexed runner | One-shot initialization + tab-keyed document paths | `BuiltinPlugin::on_load` and `HostApi::document_path` appended to the traits |
|
| **V5** | V4 multiplexed runner | One-shot initialization + tab-keyed document paths | `BuiltinPlugin::on_load` and `HostApi::document_path` appended to the traits |
|
||||||
|
| **V6** | V4 multiplexed runner | Read and write supported host system variables | `HostApi::system_variable` and `HostApi::set_system_variable` appended to the trait; request/response variants appended |
|
||||||
|
|
||||||
The host controls which generations are accepted at runtime through
|
The host controls which generations are accepted at runtime through
|
||||||
`OCS_PLUGIN_MAX_API_VERSION` (e.g. `2` for V2-only mode, `4` to disable V5). The
|
`OCS_PLUGIN_MAX_API_VERSION` (e.g. `2` for V2-only mode, `5` to disable V6). The
|
||||||
current host advertises [`API_VERSION = 5`](src/manifest.rs) and supports plugins
|
current host advertises [`API_VERSION = 6`](src/manifest.rs) and supports plugins
|
||||||
back to `API_VERSION_MIN_SUPPORTED = 2`.
|
back to `API_VERSION_MIN_SUPPORTED = 2`.
|
||||||
|
|
||||||
V5 calls `BuiltinPlugin::on_load` once after the runner connects and before the
|
V5 calls `BuiltinPlugin::on_load` once after the runner connects and before the
|
||||||
@@ -30,6 +31,10 @@ first user command. Plugins can cache `HostApi::plugin_request_sender()` there
|
|||||||
for worker-thread access. A panic in the callback fails plugin loading.
|
for worker-thread access. A panic in the callback fails plugin loading.
|
||||||
`HostApi::document_path(tab_id)` returns the saved path for a document tab.
|
`HostApi::document_path(tab_id)` returns the saved path for a document tab.
|
||||||
|
|
||||||
|
V6 adds a typed system-variable interface. This fork currently implements
|
||||||
|
`CLAYER` (current drawing layer) and `SNAPANG` (snap-angle degrees). Unknown
|
||||||
|
variables return an error rather than silently accepting a value.
|
||||||
|
|
||||||
### High-level layout
|
### High-level layout
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
|
|||||||
@@ -14,6 +14,32 @@ use serde_reflection::{
|
|||||||
// Include the stable schema types so the same definitions are used at build
|
// Include the stable schema types so the same definitions are used at build
|
||||||
// time and at runtime. The file is self-contained and only depends on serde.
|
// time and at runtime. The file is self-contained and only depends on serde.
|
||||||
include!("src/type_registry_types.rs");
|
include!("src/type_registry_types.rs");
|
||||||
|
mod entity_coverage_schema {
|
||||||
|
include!("src/entity_coverage_types.rs");
|
||||||
|
}
|
||||||
|
use entity_coverage_schema::{
|
||||||
|
EntityCoverageCatalog, EntityKindCoverage, EntityScope, ModelAccess, PropertyCoverage,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
struct SyntheticProperty {
|
||||||
|
name: String,
|
||||||
|
type_id: String,
|
||||||
|
access: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
struct EntityCoveragePolicy {
|
||||||
|
internal_kinds: Vec<String>,
|
||||||
|
opaque_kinds: Vec<String>,
|
||||||
|
editable: BTreeMap<String, Vec<String>>,
|
||||||
|
readable: BTreeMap<String, Vec<String>>,
|
||||||
|
aliases: BTreeMap<String, BTreeMap<String, String>>,
|
||||||
|
/// Properties for kinds whose payload is a nested enum (Dimension), where
|
||||||
|
/// the traced variant has no single field list to map.
|
||||||
|
#[serde(default)]
|
||||||
|
synthetic: BTreeMap<String, Vec<SyntheticProperty>>,
|
||||||
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
|
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
|
||||||
@@ -23,6 +49,8 @@ fn main() {
|
|||||||
"cargo:rerun-if-changed={}",
|
"cargo:rerun-if-changed={}",
|
||||||
workspace_cargo_lock_path().display()
|
workspace_cargo_lock_path().display()
|
||||||
);
|
);
|
||||||
|
println!("cargo:rerun-if-changed=entity_coverage_policy.json");
|
||||||
|
println!("cargo:rerun-if-changed=src/entity_coverage_types.rs");
|
||||||
}
|
}
|
||||||
|
|
||||||
// ════════════════════════════════════════════════════════════════════════════
|
// ════════════════════════════════════════════════════════════════════════════
|
||||||
@@ -486,6 +514,353 @@ fn generate_type_registry(out_dir: &Path) {
|
|||||||
);
|
);
|
||||||
let json = serde_json::to_string_pretty(®istry).unwrap();
|
let json = serde_json::to_string_pretty(®istry).unwrap();
|
||||||
fs::write(out_dir.join("type_registry.json"), json).unwrap();
|
fs::write(out_dir.join("type_registry.json"), json).unwrap();
|
||||||
|
generate_entity_coverage(out_dir, ®istry);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn generate_entity_coverage(out_dir: &Path, registry: &TypeRegistry) {
|
||||||
|
use std::collections::HashSet;
|
||||||
|
let policy: EntityCoveragePolicy =
|
||||||
|
serde_json::from_str(include_str!("entity_coverage_policy.json"))
|
||||||
|
.expect("valid entity coverage policy");
|
||||||
|
let variants = ®istry.types[&TypeId::new("EntityType")].variants;
|
||||||
|
let variant_names: HashSet<&str> = variants.iter().map(|v| v.name.as_str()).collect();
|
||||||
|
for name in policy
|
||||||
|
.internal_kinds
|
||||||
|
.iter()
|
||||||
|
.chain(&policy.opaque_kinds)
|
||||||
|
.chain(policy.editable.keys())
|
||||||
|
.chain(policy.readable.keys())
|
||||||
|
{
|
||||||
|
assert!(
|
||||||
|
variant_names.contains(name.as_str()),
|
||||||
|
"coverage policy names unknown kind: {name}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for name in &policy.internal_kinds {
|
||||||
|
assert!(
|
||||||
|
!policy.opaque_kinds.contains(name) && !policy.editable.contains_key(name),
|
||||||
|
"internal kind has conflicting coverage: {name}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for name in &policy.opaque_kinds {
|
||||||
|
assert!(
|
||||||
|
!policy.editable.contains_key(name),
|
||||||
|
"opaque kind is editable: {name}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for name in policy.aliases.keys() {
|
||||||
|
assert!(
|
||||||
|
policy.editable.contains_key(name),
|
||||||
|
"aliases for non-editable kind: {name}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let common = ®istry.types[&TypeId::new("EntityCommon")];
|
||||||
|
let mut entity_kinds = Vec::with_capacity(variants.len());
|
||||||
|
for variant in variants {
|
||||||
|
let kind = &variant.name;
|
||||||
|
let scope = if policy.internal_kinds.contains(kind) {
|
||||||
|
EntityScope::Internal
|
||||||
|
} else if policy.opaque_kinds.contains(kind) {
|
||||||
|
EntityScope::Opaque
|
||||||
|
} else {
|
||||||
|
EntityScope::Canvas
|
||||||
|
};
|
||||||
|
let editable = policy.editable.get(kind).cloned().unwrap_or_default();
|
||||||
|
let readable = policy.readable.get(kind).cloned().unwrap_or_default();
|
||||||
|
let mut unresolved: HashSet<String> = editable.iter().chain(&readable).cloned().collect();
|
||||||
|
assert_eq!(
|
||||||
|
unresolved.len(),
|
||||||
|
editable.len() + readable.len(),
|
||||||
|
"duplicate mapped property in {kind}"
|
||||||
|
);
|
||||||
|
let aliases = policy.aliases.get(kind);
|
||||||
|
let mut properties = vec![PropertyCoverage {
|
||||||
|
name: "kind".into(),
|
||||||
|
source_path: "<variant>".into(),
|
||||||
|
type_id: "String".into(),
|
||||||
|
optional: false,
|
||||||
|
is_sequence: false,
|
||||||
|
snapshot_readable: true,
|
||||||
|
model_access: ModelAccess::ReadOnly,
|
||||||
|
validation: "none".into(),
|
||||||
|
}];
|
||||||
|
for field in &common.fields {
|
||||||
|
let (name, access) = match field.name.as_str() {
|
||||||
|
"handle" => ("handle".to_owned(), ModelAccess::ReadOnly),
|
||||||
|
"owner_handle" => ("owner_handle".to_owned(), ModelAccess::ReadOnly),
|
||||||
|
"layer" if scope == EntityScope::Canvas => {
|
||||||
|
unresolved.remove("layer");
|
||||||
|
("layer".to_owned(), ModelAccess::ReadWrite)
|
||||||
|
}
|
||||||
|
"layer" => ("layer".to_owned(), ModelAccess::ReadOnly),
|
||||||
|
other => (format!("common.{other}"), ModelAccess::Unmapped),
|
||||||
|
};
|
||||||
|
properties.push(PropertyCoverage {
|
||||||
|
name,
|
||||||
|
source_path: format!("common.{}", field.name),
|
||||||
|
type_id: field.type_id.as_str().to_owned(),
|
||||||
|
optional: field.optional,
|
||||||
|
is_sequence: field.is_sequence,
|
||||||
|
snapshot_readable: true,
|
||||||
|
validation: if access == ModelAccess::ReadWrite && field.name == "layer" {
|
||||||
|
"transaction_nonempty"
|
||||||
|
} else if access == ModelAccess::ReadWrite {
|
||||||
|
"type_conversion_only"
|
||||||
|
} else {
|
||||||
|
"none"
|
||||||
|
}
|
||||||
|
.into(),
|
||||||
|
model_access: access,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let shape_type = variant
|
||||||
|
.fields
|
||||||
|
.first()
|
||||||
|
.expect("entity variant payload")
|
||||||
|
.type_id
|
||||||
|
.clone();
|
||||||
|
let shape = ®istry.types[&shape_type];
|
||||||
|
for field in &shape.fields {
|
||||||
|
if field.name == "common" {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let exposed = editable.iter().chain(&readable).find(|name| {
|
||||||
|
aliases
|
||||||
|
.and_then(|map| map.get(*name))
|
||||||
|
.map_or(name.as_str(), String::as_str)
|
||||||
|
== field.name
|
||||||
|
});
|
||||||
|
let (name, access) = match exposed {
|
||||||
|
Some(name) => {
|
||||||
|
unresolved.remove(name);
|
||||||
|
(
|
||||||
|
(*name).clone(),
|
||||||
|
if editable.contains(name) {
|
||||||
|
ModelAccess::ReadWrite
|
||||||
|
} else {
|
||||||
|
ModelAccess::ReadOnly
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
None => (field.name.clone(), ModelAccess::Unmapped),
|
||||||
|
};
|
||||||
|
let validation = if access != ModelAccess::ReadWrite {
|
||||||
|
"none"
|
||||||
|
} else if matches!(
|
||||||
|
(kind.as_str(), name.as_str()),
|
||||||
|
("Point", "location")
|
||||||
|
| ("Line", "start" | "end")
|
||||||
|
| ("Circle" | "Arc", "center" | "radius")
|
||||||
|
| ("Ray" | "XLine", "base_point" | "direction")
|
||||||
|
| (
|
||||||
|
"Solid",
|
||||||
|
"first_corner"
|
||||||
|
| "second_corner"
|
||||||
|
| "third_corner"
|
||||||
|
| "fourth_corner"
|
||||||
|
| "normal"
|
||||||
|
| "thickness"
|
||||||
|
)
|
||||||
|
| (
|
||||||
|
"Face3D",
|
||||||
|
"first_corner"
|
||||||
|
| "second_corner"
|
||||||
|
| "third_corner"
|
||||||
|
| "fourth_corner"
|
||||||
|
| "invisible_edges"
|
||||||
|
)
|
||||||
|
| (
|
||||||
|
"Insert",
|
||||||
|
"insert_point"
|
||||||
|
| "x_scale"
|
||||||
|
| "y_scale"
|
||||||
|
| "z_scale"
|
||||||
|
| "rotation"
|
||||||
|
| "normal"
|
||||||
|
| "column_count"
|
||||||
|
| "row_count"
|
||||||
|
| "column_spacing"
|
||||||
|
| "row_spacing"
|
||||||
|
)
|
||||||
|
| (
|
||||||
|
"Tolerance",
|
||||||
|
"insertion_point"
|
||||||
|
| "direction"
|
||||||
|
| "normal"
|
||||||
|
| "text"
|
||||||
|
| "dimension_style_name"
|
||||||
|
| "text_height"
|
||||||
|
| "dimension_gap"
|
||||||
|
)
|
||||||
|
| (
|
||||||
|
"Shape",
|
||||||
|
"insertion_point"
|
||||||
|
| "size"
|
||||||
|
| "shape_name"
|
||||||
|
| "shape_number"
|
||||||
|
| "rotation"
|
||||||
|
| "relative_x_scale"
|
||||||
|
| "oblique_angle"
|
||||||
|
| "normal"
|
||||||
|
| "thickness"
|
||||||
|
| "style_name"
|
||||||
|
)
|
||||||
|
| (
|
||||||
|
"AttributeDefinition",
|
||||||
|
"tag"
|
||||||
|
| "prompt"
|
||||||
|
| "default_value"
|
||||||
|
| "insertion_point"
|
||||||
|
| "alignment_point"
|
||||||
|
| "height"
|
||||||
|
| "rotation"
|
||||||
|
| "width_factor"
|
||||||
|
| "oblique_angle"
|
||||||
|
| "text_style"
|
||||||
|
| "text_generation_flags"
|
||||||
|
| "horizontal_alignment"
|
||||||
|
| "vertical_alignment"
|
||||||
|
| "flags"
|
||||||
|
| "field_length"
|
||||||
|
| "normal"
|
||||||
|
| "mtext_flag"
|
||||||
|
| "is_multiline"
|
||||||
|
| "line_count"
|
||||||
|
| "lock_position"
|
||||||
|
)
|
||||||
|
| (
|
||||||
|
"AttributeEntity",
|
||||||
|
"tag"
|
||||||
|
| "value"
|
||||||
|
| "insertion_point"
|
||||||
|
| "alignment_point"
|
||||||
|
| "height"
|
||||||
|
| "rotation"
|
||||||
|
| "width_factor"
|
||||||
|
| "oblique_angle"
|
||||||
|
| "text_style"
|
||||||
|
| "text_generation_flags"
|
||||||
|
| "horizontal_alignment"
|
||||||
|
| "vertical_alignment"
|
||||||
|
| "flags"
|
||||||
|
| "field_length"
|
||||||
|
| "normal"
|
||||||
|
| "mtext_flag"
|
||||||
|
| "is_multiline"
|
||||||
|
| "line_count"
|
||||||
|
| "lock_position"
|
||||||
|
)
|
||||||
|
| (
|
||||||
|
"Hatch",
|
||||||
|
"elevation"
|
||||||
|
| "normal"
|
||||||
|
| "is_solid"
|
||||||
|
| "pattern"
|
||||||
|
| "pattern_angle"
|
||||||
|
| "pattern_scale"
|
||||||
|
| "pattern_type"
|
||||||
|
| "is_double"
|
||||||
|
| "style"
|
||||||
|
| "is_associative"
|
||||||
|
| "pixel_size"
|
||||||
|
| "paths"
|
||||||
|
| "seed_points"
|
||||||
|
)
|
||||||
|
| (
|
||||||
|
"Leader",
|
||||||
|
"dimension_style"
|
||||||
|
| "arrow_enabled"
|
||||||
|
| "path_type"
|
||||||
|
| "creation_type"
|
||||||
|
| "hookline_direction"
|
||||||
|
| "hookline_enabled"
|
||||||
|
| "text_height"
|
||||||
|
| "text_width"
|
||||||
|
| "vertices"
|
||||||
|
| "override_color"
|
||||||
|
| "annotation_handle"
|
||||||
|
| "normal"
|
||||||
|
| "horizontal_direction"
|
||||||
|
| "block_offset"
|
||||||
|
| "annotation_offset"
|
||||||
|
)
|
||||||
|
| ("MultiLeader", _)
|
||||||
|
| ("Table", _)
|
||||||
|
| ("PolygonMesh", _)
|
||||||
|
| ("PolyfaceMesh", _)
|
||||||
|
| ("Mesh", _)
|
||||||
|
| ("Helix", _)
|
||||||
|
| ("RasterImage", _)
|
||||||
|
| ("Wipeout", _)
|
||||||
|
| ("SectionSymbol", _)
|
||||||
|
| ("Surface", "u_isolines" | "v_isolines")
|
||||||
|
| ("Ole2Frame", _)
|
||||||
|
| ("Underlay", _)
|
||||||
|
| ("Viewport", _)
|
||||||
|
| ("ViewBorder", _)
|
||||||
|
| ("Light", _)
|
||||||
|
| (
|
||||||
|
"MLine",
|
||||||
|
"flags"
|
||||||
|
| "justification"
|
||||||
|
| "normal"
|
||||||
|
| "scale_factor"
|
||||||
|
| "style_name"
|
||||||
|
| "vertices"
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
"transaction_geometry"
|
||||||
|
} else {
|
||||||
|
"type_conversion_only"
|
||||||
|
};
|
||||||
|
properties.push(PropertyCoverage {
|
||||||
|
name,
|
||||||
|
source_path: field.name.clone(),
|
||||||
|
type_id: if exposed.is_some_and(|name| name == "closed") {
|
||||||
|
"bool".into()
|
||||||
|
} else {
|
||||||
|
field.type_id.as_str().to_owned()
|
||||||
|
},
|
||||||
|
optional: field.optional,
|
||||||
|
is_sequence: field.is_sequence,
|
||||||
|
snapshot_readable: true,
|
||||||
|
validation: validation.into(),
|
||||||
|
model_access: access,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
for synthetic in policy.synthetic.get(kind).into_iter().flatten() {
|
||||||
|
let writable = synthetic.access == "read_write";
|
||||||
|
properties.push(PropertyCoverage {
|
||||||
|
name: synthetic.name.clone(),
|
||||||
|
source_path: format!("<subtype>.{}", synthetic.name),
|
||||||
|
type_id: synthetic.type_id.clone(),
|
||||||
|
optional: false,
|
||||||
|
is_sequence: false,
|
||||||
|
snapshot_readable: true,
|
||||||
|
validation: if writable { "transaction_geometry" } else { "none" }.into(),
|
||||||
|
model_access: if writable { ModelAccess::ReadWrite } else { ModelAccess::ReadOnly },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
unresolved.is_empty(),
|
||||||
|
"{kind} has coverage keys absent from registry: {unresolved:?}"
|
||||||
|
);
|
||||||
|
entity_kinds.push(EntityKindCoverage {
|
||||||
|
kind: kind.clone(),
|
||||||
|
scope,
|
||||||
|
properties,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let catalog = EntityCoverageCatalog {
|
||||||
|
schema_version: 1,
|
||||||
|
entity_kinds,
|
||||||
|
};
|
||||||
|
fs::write(
|
||||||
|
out_dir.join("entity_coverage.json"),
|
||||||
|
serde_json::to_string_pretty(&catalog).unwrap(),
|
||||||
|
)
|
||||||
|
.expect("write entity coverage");
|
||||||
}
|
}
|
||||||
|
|
||||||
fn trace<T>(tracer: &mut Tracer, samples: &Samples)
|
fn trace<T>(tracer: &mut Tracer, samples: &Samples)
|
||||||
@@ -908,7 +1283,7 @@ fn generate_version_info(out_dir: &Path) {
|
|||||||
"acadrust_version": acadrust.version.to_string(),
|
"acadrust_version": acadrust.version.to_string(),
|
||||||
"acadrust_source": acadrust.source.as_ref().map(|s| s.to_string()),
|
"acadrust_source": acadrust.source.as_ref().map(|s| s.to_string()),
|
||||||
"rustc_version": rustc_version,
|
"rustc_version": rustc_version,
|
||||||
"api_version": 5,
|
"api_version": 7,
|
||||||
"api_version_min_supported": 2,
|
"api_version_min_supported": 2,
|
||||||
"build_timestamp": build_timestamp,
|
"build_timestamp": build_timestamp,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,866 @@
|
|||||||
|
{
|
||||||
|
"internal_kinds": [
|
||||||
|
"Block",
|
||||||
|
"BlockEnd",
|
||||||
|
"Seqend"
|
||||||
|
],
|
||||||
|
"opaque_kinds": [
|
||||||
|
"Extended",
|
||||||
|
"Unknown"
|
||||||
|
],
|
||||||
|
"editable": {
|
||||||
|
"Point": [
|
||||||
|
"layer",
|
||||||
|
"location",
|
||||||
|
"thickness",
|
||||||
|
"normal",
|
||||||
|
"x_axis_angle"
|
||||||
|
],
|
||||||
|
"Line": [
|
||||||
|
"layer",
|
||||||
|
"start",
|
||||||
|
"end",
|
||||||
|
"thickness",
|
||||||
|
"normal"
|
||||||
|
],
|
||||||
|
"Circle": [
|
||||||
|
"layer",
|
||||||
|
"center",
|
||||||
|
"radius",
|
||||||
|
"thickness",
|
||||||
|
"normal"
|
||||||
|
],
|
||||||
|
"Arc": [
|
||||||
|
"layer",
|
||||||
|
"center",
|
||||||
|
"radius",
|
||||||
|
"start_angle",
|
||||||
|
"end_angle",
|
||||||
|
"thickness",
|
||||||
|
"normal"
|
||||||
|
],
|
||||||
|
"Ellipse": [
|
||||||
|
"layer",
|
||||||
|
"center",
|
||||||
|
"major_axis",
|
||||||
|
"minor_axis_ratio",
|
||||||
|
"start_parameter",
|
||||||
|
"end_parameter",
|
||||||
|
"normal"
|
||||||
|
],
|
||||||
|
"Polyline": [
|
||||||
|
"layer",
|
||||||
|
"closed",
|
||||||
|
"vertices"
|
||||||
|
],
|
||||||
|
"Polyline2D": [
|
||||||
|
"layer",
|
||||||
|
"closed",
|
||||||
|
"smooth_surface",
|
||||||
|
"start_width",
|
||||||
|
"end_width",
|
||||||
|
"thickness",
|
||||||
|
"elevation",
|
||||||
|
"normal",
|
||||||
|
"vertices"
|
||||||
|
],
|
||||||
|
"Polyline3D": [
|
||||||
|
"layer",
|
||||||
|
"flags",
|
||||||
|
"default_start_width",
|
||||||
|
"default_end_width",
|
||||||
|
"mesh_m_count",
|
||||||
|
"mesh_n_count",
|
||||||
|
"smooth_m_density",
|
||||||
|
"smooth_n_density",
|
||||||
|
"elevation",
|
||||||
|
"normal",
|
||||||
|
"vertices"
|
||||||
|
],
|
||||||
|
"LwPolyline": [
|
||||||
|
"layer",
|
||||||
|
"vertices",
|
||||||
|
"is_closed",
|
||||||
|
"plinegen",
|
||||||
|
"constant_width",
|
||||||
|
"elevation",
|
||||||
|
"thickness",
|
||||||
|
"normal"
|
||||||
|
],
|
||||||
|
"Spline": [
|
||||||
|
"layer",
|
||||||
|
"degree",
|
||||||
|
"flags",
|
||||||
|
"knots",
|
||||||
|
"control_points",
|
||||||
|
"weights",
|
||||||
|
"fit_points",
|
||||||
|
"normal",
|
||||||
|
"knot_tolerance",
|
||||||
|
"control_tolerance",
|
||||||
|
"fit_tolerance",
|
||||||
|
"begin_tangent",
|
||||||
|
"end_tangent",
|
||||||
|
"knot_parameterization",
|
||||||
|
"cv_frame_visible",
|
||||||
|
"dwg_flags1",
|
||||||
|
"dxf_flags"
|
||||||
|
],
|
||||||
|
"Text": [
|
||||||
|
"layer",
|
||||||
|
"text",
|
||||||
|
"insertion",
|
||||||
|
"alignment_point",
|
||||||
|
"height",
|
||||||
|
"rotation",
|
||||||
|
"width_factor",
|
||||||
|
"oblique_angle",
|
||||||
|
"style",
|
||||||
|
"horizontal_alignment",
|
||||||
|
"vertical_alignment",
|
||||||
|
"normal",
|
||||||
|
"thickness",
|
||||||
|
"generation_flags"
|
||||||
|
],
|
||||||
|
"MText": [
|
||||||
|
"layer",
|
||||||
|
"text",
|
||||||
|
"insertion",
|
||||||
|
"height",
|
||||||
|
"rectangle_width",
|
||||||
|
"rectangle_height",
|
||||||
|
"rotation",
|
||||||
|
"dwg_x_direction",
|
||||||
|
"style",
|
||||||
|
"attachment_point",
|
||||||
|
"drawing_direction",
|
||||||
|
"line_spacing_factor",
|
||||||
|
"line_spacing_style",
|
||||||
|
"normal",
|
||||||
|
"background_fill_flags",
|
||||||
|
"background_scale",
|
||||||
|
"background_transparency",
|
||||||
|
"is_annotative",
|
||||||
|
"column_data",
|
||||||
|
"extents_width",
|
||||||
|
"extents_height"
|
||||||
|
],
|
||||||
|
"Ray": [
|
||||||
|
"layer",
|
||||||
|
"base_point",
|
||||||
|
"direction"
|
||||||
|
],
|
||||||
|
"XLine": [
|
||||||
|
"layer",
|
||||||
|
"base_point",
|
||||||
|
"direction"
|
||||||
|
],
|
||||||
|
"Solid": [
|
||||||
|
"layer",
|
||||||
|
"first_corner",
|
||||||
|
"second_corner",
|
||||||
|
"third_corner",
|
||||||
|
"fourth_corner",
|
||||||
|
"normal",
|
||||||
|
"thickness",
|
||||||
|
"is_trace"
|
||||||
|
],
|
||||||
|
"Face3D": [
|
||||||
|
"layer",
|
||||||
|
"first_corner",
|
||||||
|
"second_corner",
|
||||||
|
"third_corner",
|
||||||
|
"fourth_corner",
|
||||||
|
"invisible_edges"
|
||||||
|
],
|
||||||
|
"Insert": [
|
||||||
|
"layer",
|
||||||
|
"block_name",
|
||||||
|
"insert_point",
|
||||||
|
"x_scale",
|
||||||
|
"y_scale",
|
||||||
|
"z_scale",
|
||||||
|
"rotation",
|
||||||
|
"normal",
|
||||||
|
"column_count",
|
||||||
|
"row_count",
|
||||||
|
"column_spacing",
|
||||||
|
"row_spacing"
|
||||||
|
],
|
||||||
|
"Tolerance": [
|
||||||
|
"layer",
|
||||||
|
"insertion_point",
|
||||||
|
"direction",
|
||||||
|
"normal",
|
||||||
|
"text",
|
||||||
|
"dimension_style_name",
|
||||||
|
"text_height",
|
||||||
|
"dimension_gap"
|
||||||
|
],
|
||||||
|
"Shape": [
|
||||||
|
"layer",
|
||||||
|
"insertion_point",
|
||||||
|
"size",
|
||||||
|
"shape_name",
|
||||||
|
"shape_number",
|
||||||
|
"rotation",
|
||||||
|
"relative_x_scale",
|
||||||
|
"oblique_angle",
|
||||||
|
"normal",
|
||||||
|
"thickness",
|
||||||
|
"style_name"
|
||||||
|
],
|
||||||
|
"AttributeDefinition": [
|
||||||
|
"layer",
|
||||||
|
"tag",
|
||||||
|
"prompt",
|
||||||
|
"default_value",
|
||||||
|
"insertion_point",
|
||||||
|
"alignment_point",
|
||||||
|
"height",
|
||||||
|
"rotation",
|
||||||
|
"width_factor",
|
||||||
|
"oblique_angle",
|
||||||
|
"text_style",
|
||||||
|
"text_generation_flags",
|
||||||
|
"horizontal_alignment",
|
||||||
|
"vertical_alignment",
|
||||||
|
"flags",
|
||||||
|
"field_length",
|
||||||
|
"normal",
|
||||||
|
"mtext_flag",
|
||||||
|
"is_multiline",
|
||||||
|
"line_count",
|
||||||
|
"lock_position"
|
||||||
|
],
|
||||||
|
"AttributeEntity": [
|
||||||
|
"layer",
|
||||||
|
"tag",
|
||||||
|
"value",
|
||||||
|
"insertion_point",
|
||||||
|
"alignment_point",
|
||||||
|
"height",
|
||||||
|
"rotation",
|
||||||
|
"width_factor",
|
||||||
|
"oblique_angle",
|
||||||
|
"text_style",
|
||||||
|
"text_generation_flags",
|
||||||
|
"horizontal_alignment",
|
||||||
|
"vertical_alignment",
|
||||||
|
"flags",
|
||||||
|
"field_length",
|
||||||
|
"normal",
|
||||||
|
"mtext_flag",
|
||||||
|
"is_multiline",
|
||||||
|
"line_count",
|
||||||
|
"lock_position"
|
||||||
|
],
|
||||||
|
"Hatch": [
|
||||||
|
"layer",
|
||||||
|
"elevation",
|
||||||
|
"normal",
|
||||||
|
"is_solid",
|
||||||
|
"pattern",
|
||||||
|
"pattern_angle",
|
||||||
|
"pattern_scale",
|
||||||
|
"pattern_type",
|
||||||
|
"is_double",
|
||||||
|
"style",
|
||||||
|
"is_associative",
|
||||||
|
"pixel_size",
|
||||||
|
"paths",
|
||||||
|
"seed_points"
|
||||||
|
],
|
||||||
|
"Leader": [
|
||||||
|
"layer",
|
||||||
|
"dimension_style",
|
||||||
|
"arrow_enabled",
|
||||||
|
"path_type",
|
||||||
|
"creation_type",
|
||||||
|
"hookline_direction",
|
||||||
|
"hookline_enabled",
|
||||||
|
"text_height",
|
||||||
|
"text_width",
|
||||||
|
"vertices",
|
||||||
|
"override_color",
|
||||||
|
"annotation_handle",
|
||||||
|
"normal",
|
||||||
|
"horizontal_direction",
|
||||||
|
"block_offset",
|
||||||
|
"annotation_offset"
|
||||||
|
],
|
||||||
|
"MLine": [
|
||||||
|
"layer",
|
||||||
|
"flags",
|
||||||
|
"justification",
|
||||||
|
"normal",
|
||||||
|
"scale_factor",
|
||||||
|
"style_name",
|
||||||
|
"vertices"
|
||||||
|
],
|
||||||
|
"MultiLeader": [
|
||||||
|
"layer",
|
||||||
|
"content_type",
|
||||||
|
"path_type",
|
||||||
|
"line_color",
|
||||||
|
"line_weight",
|
||||||
|
"enable_landing",
|
||||||
|
"enable_dogleg",
|
||||||
|
"dogleg_length",
|
||||||
|
"arrowhead_size",
|
||||||
|
"text_color",
|
||||||
|
"text_frame",
|
||||||
|
"text_left_attachment",
|
||||||
|
"text_right_attachment",
|
||||||
|
"text_top_attachment",
|
||||||
|
"text_bottom_attachment",
|
||||||
|
"text_attachment_direction",
|
||||||
|
"text_attachment_point",
|
||||||
|
"text_alignment",
|
||||||
|
"text_angle_type",
|
||||||
|
"text_direction_negative",
|
||||||
|
"scale_factor",
|
||||||
|
"enable_annotation_scale",
|
||||||
|
"extend_leader_to_text",
|
||||||
|
"block_content_color",
|
||||||
|
"block_connection_type",
|
||||||
|
"block_rotation",
|
||||||
|
"block_scale",
|
||||||
|
"context",
|
||||||
|
"style_handle",
|
||||||
|
"text_style_handle",
|
||||||
|
"arrowhead_handle",
|
||||||
|
"line_type_handle",
|
||||||
|
"block_content_handle"
|
||||||
|
],
|
||||||
|
"Table": [
|
||||||
|
"layer",
|
||||||
|
"insertion_point",
|
||||||
|
"horizontal_direction",
|
||||||
|
"normal",
|
||||||
|
"table_style_handle",
|
||||||
|
"rows",
|
||||||
|
"columns",
|
||||||
|
"merged_ranges",
|
||||||
|
"break_spacing",
|
||||||
|
"break_flow_direction",
|
||||||
|
"break_options"
|
||||||
|
],
|
||||||
|
"PolygonMesh": [
|
||||||
|
"layer",
|
||||||
|
"flags",
|
||||||
|
"m_vertex_count",
|
||||||
|
"n_vertex_count",
|
||||||
|
"m_smooth_density",
|
||||||
|
"n_smooth_density",
|
||||||
|
"smooth_type",
|
||||||
|
"elevation",
|
||||||
|
"normal",
|
||||||
|
"vertices"
|
||||||
|
],
|
||||||
|
"PolyfaceMesh": [
|
||||||
|
"layer",
|
||||||
|
"elevation",
|
||||||
|
"flags",
|
||||||
|
"normal",
|
||||||
|
"start_width",
|
||||||
|
"end_width",
|
||||||
|
"smooth_surface",
|
||||||
|
"thickness",
|
||||||
|
"vertices",
|
||||||
|
"faces"
|
||||||
|
],
|
||||||
|
"Mesh": [
|
||||||
|
"layer",
|
||||||
|
"blend_crease",
|
||||||
|
"subdivision_level",
|
||||||
|
"vertices",
|
||||||
|
"faces",
|
||||||
|
"edges",
|
||||||
|
"override_option"
|
||||||
|
],
|
||||||
|
"Helix": [
|
||||||
|
"layer",
|
||||||
|
"axis_base_point",
|
||||||
|
"start_point",
|
||||||
|
"axis_vector",
|
||||||
|
"radius",
|
||||||
|
"turns",
|
||||||
|
"turn_height",
|
||||||
|
"handedness",
|
||||||
|
"constraint"
|
||||||
|
],
|
||||||
|
"RasterImage": [
|
||||||
|
"layer",
|
||||||
|
"insertion_point",
|
||||||
|
"u_vector",
|
||||||
|
"v_vector",
|
||||||
|
"flags",
|
||||||
|
"clipping_enabled",
|
||||||
|
"brightness",
|
||||||
|
"contrast",
|
||||||
|
"fade",
|
||||||
|
"clip_boundary",
|
||||||
|
"file_path"
|
||||||
|
],
|
||||||
|
"Wipeout": [
|
||||||
|
"layer",
|
||||||
|
"insertion_point",
|
||||||
|
"u_vector",
|
||||||
|
"v_vector",
|
||||||
|
"size",
|
||||||
|
"flags",
|
||||||
|
"clipping_enabled",
|
||||||
|
"brightness",
|
||||||
|
"contrast",
|
||||||
|
"fade",
|
||||||
|
"clip_mode",
|
||||||
|
"clip_type",
|
||||||
|
"clip_boundary_vertices"
|
||||||
|
],
|
||||||
|
"Underlay": [
|
||||||
|
"layer",
|
||||||
|
"underlay_type",
|
||||||
|
"definition_handle",
|
||||||
|
"insertion_point",
|
||||||
|
"x_scale",
|
||||||
|
"y_scale",
|
||||||
|
"z_scale",
|
||||||
|
"rotation",
|
||||||
|
"normal",
|
||||||
|
"flags",
|
||||||
|
"contrast",
|
||||||
|
"fade",
|
||||||
|
"clip_boundary_vertices",
|
||||||
|
"clip_inverted"
|
||||||
|
],
|
||||||
|
"Viewport": [
|
||||||
|
"layer",
|
||||||
|
"center",
|
||||||
|
"width",
|
||||||
|
"height",
|
||||||
|
"status",
|
||||||
|
"view_center",
|
||||||
|
"view_direction",
|
||||||
|
"view_target",
|
||||||
|
"lens_length",
|
||||||
|
"front_clip_z",
|
||||||
|
"back_clip_z",
|
||||||
|
"view_height",
|
||||||
|
"twist_angle",
|
||||||
|
"frozen_layers",
|
||||||
|
"render_mode",
|
||||||
|
"circle_sides",
|
||||||
|
"ucs_icon_visible"
|
||||||
|
],
|
||||||
|
"ViewBorder": [
|
||||||
|
"layer",
|
||||||
|
"min",
|
||||||
|
"max",
|
||||||
|
"center",
|
||||||
|
"scale",
|
||||||
|
"rotation_angle",
|
||||||
|
"active_viewport",
|
||||||
|
"scale_handle"
|
||||||
|
],
|
||||||
|
"Light": [
|
||||||
|
"layer",
|
||||||
|
"name",
|
||||||
|
"light_type",
|
||||||
|
"position",
|
||||||
|
"target",
|
||||||
|
"status",
|
||||||
|
"light_color",
|
||||||
|
"plot_glyph",
|
||||||
|
"intensity",
|
||||||
|
"attenuation_type",
|
||||||
|
"use_attenuation_limits",
|
||||||
|
"attenuation_start_limit",
|
||||||
|
"attenuation_end_limit",
|
||||||
|
"hotspot_angle",
|
||||||
|
"falloff_angle",
|
||||||
|
"cast_shadows",
|
||||||
|
"shadow_type",
|
||||||
|
"shadow_map_size",
|
||||||
|
"shadow_map_softness",
|
||||||
|
"photometric_mode",
|
||||||
|
"photometric_data"
|
||||||
|
],
|
||||||
|
"Ole2Frame": [
|
||||||
|
"layer",
|
||||||
|
"upper_left_corner",
|
||||||
|
"lower_right_corner",
|
||||||
|
"lock_aspect",
|
||||||
|
"is_paper_space"
|
||||||
|
],
|
||||||
|
"Solid3D": [
|
||||||
|
"layer"
|
||||||
|
],
|
||||||
|
"Body": [
|
||||||
|
"layer"
|
||||||
|
],
|
||||||
|
"Region": [
|
||||||
|
"layer"
|
||||||
|
],
|
||||||
|
"Surface": [
|
||||||
|
"layer",
|
||||||
|
"u_isolines",
|
||||||
|
"v_isolines"
|
||||||
|
],
|
||||||
|
"SectionSymbol": [
|
||||||
|
"layer",
|
||||||
|
"symbol_scale",
|
||||||
|
"points",
|
||||||
|
"style_handle",
|
||||||
|
"view_rep_handle"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"readable": {
|
||||||
|
"Tolerance": [
|
||||||
|
"dimension_style_handle"
|
||||||
|
],
|
||||||
|
"Shape": [
|
||||||
|
"style_handle"
|
||||||
|
],
|
||||||
|
"MLine": [
|
||||||
|
"start_point",
|
||||||
|
"style_handle",
|
||||||
|
"style_element_count"
|
||||||
|
],
|
||||||
|
"Leader": [
|
||||||
|
"origin",
|
||||||
|
"dimension_gap",
|
||||||
|
"arrowhead_type",
|
||||||
|
"arrow_size",
|
||||||
|
"byblock_color"
|
||||||
|
],
|
||||||
|
"AttributeEntity": [
|
||||||
|
"attdef_handle"
|
||||||
|
],
|
||||||
|
"MultiLeader": [
|
||||||
|
"dwg_version",
|
||||||
|
"property_override_flags",
|
||||||
|
"text_align_in_ipe",
|
||||||
|
"text_height"
|
||||||
|
],
|
||||||
|
"Table": [
|
||||||
|
"block_name",
|
||||||
|
"block_record_handle",
|
||||||
|
"data_version",
|
||||||
|
"value_flags",
|
||||||
|
"override_flag",
|
||||||
|
"override_border_color",
|
||||||
|
"override_border_line_weight",
|
||||||
|
"override_border_visibility",
|
||||||
|
"legacy_style_override",
|
||||||
|
"name",
|
||||||
|
"description",
|
||||||
|
"field_handles",
|
||||||
|
"base_style",
|
||||||
|
"break_data",
|
||||||
|
"break_ranges"
|
||||||
|
],
|
||||||
|
"PolyfaceMesh": [
|
||||||
|
"seqend_handle"
|
||||||
|
],
|
||||||
|
"Mesh": [
|
||||||
|
"version"
|
||||||
|
],
|
||||||
|
"Helix": [
|
||||||
|
"spline",
|
||||||
|
"major_version",
|
||||||
|
"maintenance_version"
|
||||||
|
],
|
||||||
|
"RasterImage": [
|
||||||
|
"class_version",
|
||||||
|
"definition_handle",
|
||||||
|
"definition_reactor_handle",
|
||||||
|
"size"
|
||||||
|
],
|
||||||
|
"Wipeout": [
|
||||||
|
"class_version",
|
||||||
|
"definition_handle",
|
||||||
|
"definition_reactor_handle"
|
||||||
|
],
|
||||||
|
"Viewport": [
|
||||||
|
"id",
|
||||||
|
"snap_base",
|
||||||
|
"snap_spacing",
|
||||||
|
"grid_spacing",
|
||||||
|
"snap_angle",
|
||||||
|
"clip_boundary_handle",
|
||||||
|
"style_sheet",
|
||||||
|
"ucs_at_origin",
|
||||||
|
"ucs_per_viewport",
|
||||||
|
"ucs_origin",
|
||||||
|
"ucs_x_axis",
|
||||||
|
"ucs_y_axis",
|
||||||
|
"ucs_handle",
|
||||||
|
"base_ucs_handle",
|
||||||
|
"ucs_ortho_type",
|
||||||
|
"elevation",
|
||||||
|
"shade_plot_mode",
|
||||||
|
"grid_flags",
|
||||||
|
"grid_major",
|
||||||
|
"background_handle",
|
||||||
|
"shade_plot_handle",
|
||||||
|
"visual_style_handle",
|
||||||
|
"sun_handle",
|
||||||
|
"default_lighting",
|
||||||
|
"default_lighting_type",
|
||||||
|
"brightness",
|
||||||
|
"contrast",
|
||||||
|
"ambient_color",
|
||||||
|
"custom_scale"
|
||||||
|
],
|
||||||
|
"ViewBorder": [
|
||||||
|
"version"
|
||||||
|
],
|
||||||
|
"Light": [
|
||||||
|
"class_version"
|
||||||
|
],
|
||||||
|
"Ole2Frame": [
|
||||||
|
"version",
|
||||||
|
"source_application",
|
||||||
|
"ole_object_type",
|
||||||
|
"dwg_mode"
|
||||||
|
],
|
||||||
|
"Solid3D": [
|
||||||
|
"uid",
|
||||||
|
"point_of_reference",
|
||||||
|
"history_handle"
|
||||||
|
],
|
||||||
|
"Body": [
|
||||||
|
"uid",
|
||||||
|
"point_of_reference",
|
||||||
|
"history_handle"
|
||||||
|
],
|
||||||
|
"Region": [
|
||||||
|
"uid",
|
||||||
|
"point_of_reference",
|
||||||
|
"history_handle"
|
||||||
|
],
|
||||||
|
"Surface": [
|
||||||
|
"surface_kind",
|
||||||
|
"modeler_format_version",
|
||||||
|
"point_of_reference",
|
||||||
|
"history_handle"
|
||||||
|
],
|
||||||
|
"SectionSymbol": [
|
||||||
|
"view_symbol_version",
|
||||||
|
"raw_view_symbol_70",
|
||||||
|
"version",
|
||||||
|
"raw_point_count_90",
|
||||||
|
"raw_flags_90",
|
||||||
|
"raw_point_record_count",
|
||||||
|
"end_a",
|
||||||
|
"end_b",
|
||||||
|
"tick_a",
|
||||||
|
"tick_b",
|
||||||
|
"label"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"aliases": {
|
||||||
|
"Polyline": {
|
||||||
|
"closed": "flags"
|
||||||
|
},
|
||||||
|
"Polyline2D": {
|
||||||
|
"closed": "flags"
|
||||||
|
},
|
||||||
|
"Text": {
|
||||||
|
"text": "value",
|
||||||
|
"insertion": "insertion_point"
|
||||||
|
},
|
||||||
|
"MText": {
|
||||||
|
"text": "value",
|
||||||
|
"insertion": "insertion_point"
|
||||||
|
},
|
||||||
|
"Surface": {
|
||||||
|
"surface_kind": "kind"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"synthetic": {
|
||||||
|
"Dimension": [
|
||||||
|
{
|
||||||
|
"name": "subtype",
|
||||||
|
"type_id": "String",
|
||||||
|
"access": "read_only"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "actual_measurement",
|
||||||
|
"type_id": "f64",
|
||||||
|
"access": "read_only"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "text",
|
||||||
|
"type_id": "String",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "style_name",
|
||||||
|
"type_id": "String",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "normal",
|
||||||
|
"type_id": "Vector3",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "text_middle_point",
|
||||||
|
"type_id": "Vector3",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "attachment_point",
|
||||||
|
"type_id": "AttachmentPointType",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "text_rotation",
|
||||||
|
"type_id": "f64",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "horizontal_direction",
|
||||||
|
"type_id": "f64",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "flip_arrow1",
|
||||||
|
"type_id": "bool",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "flip_arrow2",
|
||||||
|
"type_id": "bool",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "text_user_positioned",
|
||||||
|
"type_id": "bool",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "definition_point",
|
||||||
|
"type_id": "Vector3",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "first_point",
|
||||||
|
"type_id": "Vector3",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "second_point",
|
||||||
|
"type_id": "Vector3",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "angle_vertex",
|
||||||
|
"type_id": "Vector3",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "dimension_arc",
|
||||||
|
"type_id": "Vector3",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "feature_location",
|
||||||
|
"type_id": "Vector3",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "leader_endpoint",
|
||||||
|
"type_id": "Vector3",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "first_extension_point",
|
||||||
|
"type_id": "Vector3",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "second_extension_point",
|
||||||
|
"type_id": "Vector3",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "center_point",
|
||||||
|
"type_id": "Vector3",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "first_leader_point",
|
||||||
|
"type_id": "Vector3",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "second_leader_point",
|
||||||
|
"type_id": "Vector3",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "chord_point",
|
||||||
|
"type_id": "Vector3",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "override_center",
|
||||||
|
"type_id": "Vector3",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "jog_point",
|
||||||
|
"type_id": "Vector3",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "rotation",
|
||||||
|
"type_id": "f64",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "ext_line_rotation",
|
||||||
|
"type_id": "f64",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "leader_length",
|
||||||
|
"type_id": "f64",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "arc_start_parameter",
|
||||||
|
"type_id": "f64",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "arc_end_parameter",
|
||||||
|
"type_id": "f64",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "jog_angle",
|
||||||
|
"type_id": "f64",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "is_ordinate_type_x",
|
||||||
|
"type_id": "bool",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "is_partial",
|
||||||
|
"type_id": "bool",
|
||||||
|
"access": "read_write"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "has_leader",
|
||||||
|
"type_id": "bool",
|
||||||
|
"access": "read_write"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,52 @@
|
|||||||
|
/// Stable, language-neutral entity capability schema.
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum EntityScope {
|
||||||
|
Canvas,
|
||||||
|
Internal,
|
||||||
|
Opaque,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum ModelAccess {
|
||||||
|
ReadWrite,
|
||||||
|
ReadOnly,
|
||||||
|
Unmapped,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct PropertyCoverage {
|
||||||
|
/// Name shown in the document model, or source name when unmapped.
|
||||||
|
pub name: String,
|
||||||
|
/// Field in the acadrust snapshot; `kind` is synthesized from the variant.
|
||||||
|
pub source_path: String,
|
||||||
|
pub type_id: String,
|
||||||
|
pub optional: bool,
|
||||||
|
pub is_sequence: bool,
|
||||||
|
/// Whether the serialized host snapshot carries this property.
|
||||||
|
pub snapshot_readable: bool,
|
||||||
|
/// `unmapped` means no normalized Python property or setter; the raw
|
||||||
|
/// snapshot can still expose its serialized value.
|
||||||
|
pub model_access: ModelAccess,
|
||||||
|
/// Write validation applied by the v7 transaction path. Currently
|
||||||
|
/// `transaction_geometry` for selected primitive geometry, otherwise
|
||||||
|
/// `type_conversion_only` for writable properties or `none`.
|
||||||
|
pub validation: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct EntityKindCoverage {
|
||||||
|
pub kind: String,
|
||||||
|
pub scope: EntityScope,
|
||||||
|
pub properties: Vec<PropertyCoverage>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct EntityCoverageCatalog {
|
||||||
|
pub schema_version: u32,
|
||||||
|
pub entity_kinds: Vec<EntityKindCoverage>,
|
||||||
|
}
|
||||||
@@ -60,6 +60,243 @@ pub enum LogLevel {
|
|||||||
Error,
|
Error,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A solid primitive the host can build with its geometry kernel. Lengths are
|
||||||
|
/// in drawing units; `center`/`origin` are world coordinates.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub enum SolidPrimitive {
|
||||||
|
/// Axis-aligned box from its center and full extents.
|
||||||
|
Box { center: [f64; 3], size: [f64; 3] },
|
||||||
|
/// Right triangular prism from its minimum corner and extents.
|
||||||
|
Wedge { origin: [f64; 3], size: [f64; 3] },
|
||||||
|
/// Cylinder standing on the plane through `center`.
|
||||||
|
Cylinder { center: [f64; 3], radius: f64, height: f64 },
|
||||||
|
Sphere { center: [f64; 3], radius: f64 },
|
||||||
|
Torus { center: [f64; 3], major: f64, minor: f64 },
|
||||||
|
/// Regular pyramid with `sides` base edges.
|
||||||
|
Pyramid { center: [f64; 3], radius: f64, height: f64, sides: u32 },
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How two solids combine.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub enum SolidBoolean {
|
||||||
|
Union,
|
||||||
|
/// Remove the second solid from the first.
|
||||||
|
Subtract,
|
||||||
|
Intersect,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One step of driving an OCS command from a script (API v7, additive). The
|
||||||
|
/// host runs the real command, so every tool behaves exactly as at the command
|
||||||
|
/// line, and answers with where the command stands.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub enum CommandRequest {
|
||||||
|
/// Run a whole command line (`OFFSET 5 ...`): the tokens after the name
|
||||||
|
/// answer the prompts in order and a final Enter finishes the command.
|
||||||
|
Run { line: String },
|
||||||
|
/// Start a command and leave it waiting for its first input.
|
||||||
|
Start { name: String },
|
||||||
|
/// Answer the current prompt with a world-coordinate point.
|
||||||
|
Point { point: [f64; 3] },
|
||||||
|
/// Answer with typed text (a distance, an angle, a name).
|
||||||
|
Text { text: String },
|
||||||
|
/// Answer with a keyword option.
|
||||||
|
Token { text: String },
|
||||||
|
/// Pick an entity at a point.
|
||||||
|
Entity { handle: Handle, point: [f64; 3] },
|
||||||
|
/// Complete an object-selection prompt with the current selection.
|
||||||
|
Selection,
|
||||||
|
/// Press Enter.
|
||||||
|
Enter,
|
||||||
|
/// Cancel the running command and close anything it left open.
|
||||||
|
Cancel,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a command stands after a [`CommandRequest`].
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
|
||||||
|
pub struct CommandOutcome {
|
||||||
|
/// `completed` when nothing is waiting, `waiting_input` when the command
|
||||||
|
/// (or an editor or dialog it opened) needs more.
|
||||||
|
pub status: String,
|
||||||
|
/// What is still open: `command`, `text_editor`, `mtext_editor` or `modal:<kind>`.
|
||||||
|
pub blocked_by: Option<String>,
|
||||||
|
/// The waiting command's name and prompt (empty when none).
|
||||||
|
pub command: String,
|
||||||
|
pub prompt: String,
|
||||||
|
/// The kinds of input the prompt accepts (`point`, `entity`, `selection`,
|
||||||
|
/// `text`, `token`, `enter`) and its keyword options.
|
||||||
|
pub accepts: Vec<String>,
|
||||||
|
pub options: Vec<String>,
|
||||||
|
/// Entities in the drawing after the step, and the change.
|
||||||
|
pub entities: u64,
|
||||||
|
pub added: i64,
|
||||||
|
/// Typed tokens no prompt asked for.
|
||||||
|
pub unconsumed: Vec<String>,
|
||||||
|
/// The command line's error message when the step failed.
|
||||||
|
pub error: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A change to a drawing table record (API v7, additive). The host validates
|
||||||
|
/// the request, records one undo step and refuses without changing anything
|
||||||
|
/// when it cannot honour it; the result is the record's handle.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub enum TableOperation {
|
||||||
|
/// Create a layer. `config.name` must be unused and valid.
|
||||||
|
LayerCreate { config: LayerConfig },
|
||||||
|
/// Change only the properties `config` sets on an existing layer.
|
||||||
|
LayerModify { config: LayerConfig },
|
||||||
|
/// Rename a layer; entities on it follow. Layer `0` and `Defpoints` stay.
|
||||||
|
LayerRename { from: String, to: String },
|
||||||
|
/// Delete a layer. A layer that still holds objects is refused unless
|
||||||
|
/// `erase_objects` is set, which erases them with the layer. Layer `0`,
|
||||||
|
/// `Defpoints` and the current layer are never deleted.
|
||||||
|
LayerDelete { name: String, erase_objects: bool },
|
||||||
|
/// Make an existing layer current.
|
||||||
|
LayerSetCurrent { name: String },
|
||||||
|
/// Create a text style; unset properties take the AutoCAD defaults.
|
||||||
|
TextStyleCreate { config: TextStyleConfig },
|
||||||
|
/// Change only the properties `config` sets on an existing text style.
|
||||||
|
TextStyleModify { config: TextStyleConfig },
|
||||||
|
/// Create a dimension style, optionally copying an existing one first.
|
||||||
|
/// `properties` is a JSON object of DimStyle fields (see the Python docs);
|
||||||
|
/// handles and xref fields are managed by the host and refused.
|
||||||
|
DimStyleCreate { name: String, copy_from: Option<String>, properties: String },
|
||||||
|
/// Change only the DimStyle fields the JSON object `properties` names.
|
||||||
|
DimStyleModify { name: String, properties: String },
|
||||||
|
/// Rename a text or dimension style; references to it follow. `Standard`
|
||||||
|
/// is never renamed and a case-only change is refused.
|
||||||
|
StyleRename { kind: TableStyleKind, from: String, to: String },
|
||||||
|
/// Delete a text or dimension style that is neither current nor in use.
|
||||||
|
/// `Standard` is never deleted.
|
||||||
|
StyleDelete { kind: TableStyleKind, name: String },
|
||||||
|
/// Make a text or dimension style current.
|
||||||
|
StyleSetCurrent { kind: TableStyleKind, name: String },
|
||||||
|
/// Define a block from existing drawing entities. The entities are copied
|
||||||
|
/// into the definition shifted by `-base_point` (the block's origin);
|
||||||
|
/// `erase_originals` then removes them from the drawing. No insert is
|
||||||
|
/// placed. Returns the block record's handle.
|
||||||
|
BlockCreate {
|
||||||
|
name: String,
|
||||||
|
entities: Vec<Handle>,
|
||||||
|
base_point: [f64; 3],
|
||||||
|
erase_originals: bool,
|
||||||
|
description: Option<String>,
|
||||||
|
},
|
||||||
|
/// Change a block's description, explodable or uniform-scale settings.
|
||||||
|
BlockModify {
|
||||||
|
name: String,
|
||||||
|
description: Option<String>,
|
||||||
|
explodable: Option<bool>,
|
||||||
|
scale_uniformly: Option<bool>,
|
||||||
|
},
|
||||||
|
/// Rename a block; every insert of it follows.
|
||||||
|
BlockRename { from: String, to: String },
|
||||||
|
/// Delete an unreferenced block definition and its contents.
|
||||||
|
BlockDelete { name: String },
|
||||||
|
/// Add a new entity to a block definition, validated exactly as a new
|
||||||
|
/// model-space entity is. The entity's owner is set by the host. Returns the
|
||||||
|
/// new entity's handle. Edit and delete members with the ordinary entity
|
||||||
|
/// operations.
|
||||||
|
BlockEntityAdd { block: String, entity: EntityType },
|
||||||
|
/// Create a simple linetype. `pattern` is signed lengths in drawing units:
|
||||||
|
/// positive is a dash, negative a gap, zero a dot (2-12 elements with at
|
||||||
|
/// least one dash or dot and one gap). Returns the linetype's handle.
|
||||||
|
LinetypeCreate { name: String, description: String, pattern: Vec<f64> },
|
||||||
|
/// Change a simple linetype's description or pattern in place.
|
||||||
|
LinetypeModify { name: String, description: Option<String>, pattern: Option<Vec<f64>> },
|
||||||
|
/// Rename a linetype; layers and entities that use it follow.
|
||||||
|
LinetypeRename { from: String, to: String },
|
||||||
|
/// Delete a linetype that no layer, entity, dimension style or the current
|
||||||
|
/// setting uses. `Continuous`, `ByLayer` and `ByBlock` are never deleted.
|
||||||
|
LinetypeDelete { name: String },
|
||||||
|
/// Create a paper-space layout with the default page setup and sheet viewport.
|
||||||
|
LayoutCreate { name: String },
|
||||||
|
/// Rename a paper-space layout (never `Model`).
|
||||||
|
LayoutRename { from: String, to: String },
|
||||||
|
/// Delete a paper-space layout and everything on it (never `Model`).
|
||||||
|
LayoutDelete { name: String },
|
||||||
|
/// Switch the active layout (`Model` or a paper-space layout).
|
||||||
|
LayoutSetCurrent { name: String },
|
||||||
|
/// Change a paper-space layout's sheet: size in millimetres, rotation in
|
||||||
|
/// degrees (0, 90, 180 or 270) and a custom plot scale (numerator,
|
||||||
|
/// denominator).
|
||||||
|
LayoutSetPage {
|
||||||
|
name: String,
|
||||||
|
paper_size: Option<[f64; 2]>,
|
||||||
|
rotation: Option<u16>,
|
||||||
|
scale: Option<[f64; 2]>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The style tables `TableOperation` can rename, delete or make current.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub enum TableStyleKind {
|
||||||
|
Text,
|
||||||
|
Dim,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Properties for creating or changing a text style; `None` leaves a property
|
||||||
|
/// as it was (or the default for a new style). Angles are in radians.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
|
||||||
|
pub struct TextStyleConfig {
|
||||||
|
pub name: String,
|
||||||
|
/// Fixed height; `0` lets each text choose its own.
|
||||||
|
pub height: Option<f64>,
|
||||||
|
pub width_factor: Option<f64>,
|
||||||
|
pub oblique_angle: Option<f64>,
|
||||||
|
pub font_file: Option<String>,
|
||||||
|
pub big_font_file: Option<String>,
|
||||||
|
pub true_type_font: Option<String>,
|
||||||
|
pub backward: Option<bool>,
|
||||||
|
pub upside_down: Option<bool>,
|
||||||
|
pub vertical: Option<bool>,
|
||||||
|
pub annotative: Option<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A kernel operation on ACIS-backed solids (API v7, additive). The host owns
|
||||||
|
/// the geometry: a script never sees or rewrites the payload.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub enum SolidOperation {
|
||||||
|
/// Build a new solid on `layer` (layer `0` when `None`).
|
||||||
|
Create { primitive: SolidPrimitive, layer: Option<String> },
|
||||||
|
/// Apply a rigid transform, given as a column-major 4x4 matrix, to an
|
||||||
|
/// existing solid. Scaling and shear are refused.
|
||||||
|
Transform { handle: Handle, matrix: [f64; 16] },
|
||||||
|
/// Build a planar region from one closed planar profile entity (a circle,
|
||||||
|
/// ellipse, closed polyline or spline, ...). The new region goes on
|
||||||
|
/// `layer`, or on the source's layer when `None`; `delete_source` erases
|
||||||
|
/// the profile afterwards, as the REGION command does.
|
||||||
|
RegionFromProfile { source: Handle, layer: Option<String>, delete_source: bool },
|
||||||
|
/// Build a plane surface from one closed planar profile entity.
|
||||||
|
SurfaceFromProfile { source: Handle, layer: Option<String>, delete_source: bool },
|
||||||
|
/// Extrude a planar profile along `direction`: a solid when the profile is
|
||||||
|
/// closed, a surface when it is open.
|
||||||
|
Extrude { source: Handle, direction: [f64; 3], layer: Option<String>, delete_source: bool },
|
||||||
|
/// Combine two solids into a new one. Both operands are consumed unless
|
||||||
|
/// `keep_operands`; the result goes on `layer` or the first operand's
|
||||||
|
/// layer. The kernel refuses some cases (coincident faces, cuts it has no
|
||||||
|
/// closed form for); a refusal changes nothing. Curved operands can take a
|
||||||
|
/// second or two, and the host thread is busy meanwhile.
|
||||||
|
/// Embed a picture file as an OLE frame whose bottom-left corner is at
|
||||||
|
/// `origin`, `width` drawing units wide, keeping the picture's aspect.
|
||||||
|
/// PNG, JPEG and BMP are stored as read; other formats are re-encoded as
|
||||||
|
/// PNG. The frame goes on `layer` (layer `0` when `None`).
|
||||||
|
EmbedPicture { path: String, origin: [f64; 3], width: f64, layer: Option<String> },
|
||||||
|
Boolean {
|
||||||
|
first: Handle,
|
||||||
|
second: Handle,
|
||||||
|
operation: SolidBoolean,
|
||||||
|
layer: Option<String>,
|
||||||
|
keep_operands: bool,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Value of a host-managed drafting or document setting exposed to plugins.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub enum HostSettingValue {
|
||||||
|
Text(String),
|
||||||
|
Number(f64),
|
||||||
|
}
|
||||||
|
|
||||||
/// A notification the host sends to a plugin. These are best-effort,
|
/// A notification the host sends to a plugin. These are best-effort,
|
||||||
/// full-duplex messages correlated with an optional `command_id`.
|
/// full-duplex messages correlated with an optional `command_id`.
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
@@ -76,6 +313,10 @@ pub enum HostNotification {
|
|||||||
DocumentTabClosed { tab_id: u64 },
|
DocumentTabClosed { tab_id: u64 },
|
||||||
/// V4 selection changed for a specific tab. Discriminant 7.
|
/// V4 selection changed for a specific tab. Discriminant 7.
|
||||||
SelectionChangedV4 { tab_id: u64, handles: Vec<Handle> },
|
SelectionChangedV4 { tab_id: u64, handles: Vec<Handle> },
|
||||||
|
/// V7 active interactive-command state for a tab. Discriminant 8.
|
||||||
|
CommandStateChanged { tab_id: u64, command: Option<String> },
|
||||||
|
/// V7 drawing epoch, broadcast even without an open shared view. Discriminant 9.
|
||||||
|
DrawingChanged { tab_id: u64, epoch: u64 },
|
||||||
/// Fallback for notification variants added in future minor revisions.
|
/// Fallback for notification variants added in future minor revisions.
|
||||||
/// Carries the raw bincode payload so an older peer can ignore it without
|
/// Carries the raw bincode payload so an older peer can ignore it without
|
||||||
/// failing deserialization.
|
/// failing deserialization.
|
||||||
@@ -126,6 +367,20 @@ impl Serialize for HostNotification {
|
|||||||
bincode::serialize_into(&mut bytes, handles)
|
bincode::serialize_into(&mut bytes, handles)
|
||||||
.map_err(serde::ser::Error::custom)?;
|
.map_err(serde::ser::Error::custom)?;
|
||||||
}
|
}
|
||||||
|
HostNotification::CommandStateChanged { tab_id, command } => {
|
||||||
|
bytes.push(8);
|
||||||
|
bincode::serialize_into(&mut bytes, tab_id)
|
||||||
|
.map_err(serde::ser::Error::custom)?;
|
||||||
|
bincode::serialize_into(&mut bytes, command)
|
||||||
|
.map_err(serde::ser::Error::custom)?;
|
||||||
|
}
|
||||||
|
HostNotification::DrawingChanged { tab_id, epoch } => {
|
||||||
|
bytes.push(9);
|
||||||
|
bincode::serialize_into(&mut bytes, tab_id)
|
||||||
|
.map_err(serde::ser::Error::custom)?;
|
||||||
|
bincode::serialize_into(&mut bytes, epoch)
|
||||||
|
.map_err(serde::ser::Error::custom)?;
|
||||||
|
}
|
||||||
HostNotification::Unknown(raw) => bytes.extend_from_slice(raw),
|
HostNotification::Unknown(raw) => bytes.extend_from_slice(raw),
|
||||||
}
|
}
|
||||||
bytes.serialize(serializer)
|
bytes.serialize(serializer)
|
||||||
@@ -163,6 +418,12 @@ impl<'de> Deserialize<'de> for HostNotification {
|
|||||||
7 => bincode::deserialize(rest)
|
7 => bincode::deserialize(rest)
|
||||||
.map(|(tab_id, handles)| HostNotification::SelectionChangedV4 { tab_id, handles })
|
.map(|(tab_id, handles)| HostNotification::SelectionChangedV4 { tab_id, handles })
|
||||||
.map_err(serde::de::Error::custom),
|
.map_err(serde::de::Error::custom),
|
||||||
|
8 => bincode::deserialize(rest)
|
||||||
|
.map(|(tab_id, command)| HostNotification::CommandStateChanged { tab_id, command })
|
||||||
|
.map_err(serde::de::Error::custom),
|
||||||
|
9 => bincode::deserialize(rest)
|
||||||
|
.map(|(tab_id, epoch)| HostNotification::DrawingChanged { tab_id, epoch })
|
||||||
|
.map_err(serde::de::Error::custom),
|
||||||
_ => Ok(HostNotification::Unknown(bytes)),
|
_ => Ok(HostNotification::Unknown(bytes)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -553,6 +814,62 @@ pub trait HostApi {
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Read a named host setting without invoking the command dispatcher.
|
||||||
|
/// Names are case-insensitive. Hosts may support only a subset.
|
||||||
|
fn system_variable(&self, _name: &str) -> Option<HostSettingValue> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set a named host setting without re-entering command dispatch.
|
||||||
|
/// Returns the effective value after validation and normalization.
|
||||||
|
fn set_system_variable(
|
||||||
|
&mut self,
|
||||||
|
_name: &str,
|
||||||
|
_value: HostSettingValue,
|
||||||
|
) -> Result<HostSettingValue, String> {
|
||||||
|
Err("system variable is not supported by this host".to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Validate and replace existing entities as one undo step (API v7).
|
||||||
|
/// Callers clone entities from `document()`, change only supported fields,
|
||||||
|
/// and submit all replacements together. Identity and kind must be kept.
|
||||||
|
/// An error leaves the drawing and undo history unchanged.
|
||||||
|
fn update_entities_transaction(
|
||||||
|
&mut self,
|
||||||
|
_label: &str,
|
||||||
|
_entities: Vec<EntityType>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
Err("entity transactions are not supported by this host".to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Current ordered selection in this session's tab (API v7).
|
||||||
|
fn selection(&self) -> Vec<Handle> { Vec::new() }
|
||||||
|
|
||||||
|
/// Replace this tab's selection with exactly these handles, in order.
|
||||||
|
/// Missing or duplicate handles reject the request (API v7).
|
||||||
|
fn set_selection(&mut self, _handles: &[Handle]) -> Result<(), String> {
|
||||||
|
Err("selection writes are not supported by this host".to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run a kernel-backed solid operation and return the created or updated
|
||||||
|
/// entity's handle. Refused, without any change, when the kernel cannot
|
||||||
|
/// perform it losslessly (API v7, additive).
|
||||||
|
fn solid_operation(&mut self, _operation: SolidOperation) -> Result<Handle, String> {
|
||||||
|
Err("solid operations are not supported by this host".to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drive an OCS command from a script (API v7, additive). Refused, with
|
||||||
|
/// nothing run, when another command is already active or the request names
|
||||||
|
/// a command that could end the session or re-enter the plugin.
|
||||||
|
fn run_command(&mut self, _request: CommandRequest) -> Result<CommandOutcome, String> {
|
||||||
|
Err("running commands is not supported by this host".to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create, change, rename, delete or select a drawing table record (API v7,
|
||||||
|
/// additive). Returns the record's handle; a refusal changes nothing.
|
||||||
|
fn table_operation(&mut self, _operation: TableOperation) -> Result<Handle, String> {
|
||||||
|
Err("table operations are not supported by this host".to_owned())
|
||||||
|
}
|
||||||
/// Add a layer to the active document with full initial properties.
|
/// Add a layer to the active document with full initial properties.
|
||||||
/// If an optional property in `config` is `None`, standard CAD defaults are applied.
|
/// If an optional property in `config` is `None`, standard CAD defaults are applied.
|
||||||
/// Returns `None` if the layer already exists or `config.name` is invalid.
|
/// Returns `None` if the layer already exists or `config.name` is invalid.
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ use acadrust::{CadDocument, EntityType, Handle};
|
|||||||
use interprocess::local_socket::traits::Stream as StreamTrait;
|
use interprocess::local_socket::traits::Stream as StreamTrait;
|
||||||
use interprocess::local_socket::{GenericNamespaced, Stream, ToNsName};
|
use interprocess::local_socket::{GenericNamespaced, Stream, ToNsName};
|
||||||
|
|
||||||
use crate::host::{DocumentReader, HostApi, InteractiveCommand, ReaderEntity};
|
use crate::host::{DocumentReader, HostApi, HostSettingValue, InteractiveCommand, ReaderEntity};
|
||||||
use crate::ipc::protocol::{
|
use crate::ipc::protocol::{
|
||||||
HostResponse, HostToPlugin, PluginRequest, PluginResponse, PluginToHost, RunnerHandshake,
|
HostResponse, HostToPlugin, PluginRequest, PluginResponse, PluginToHost, RunnerHandshake,
|
||||||
};
|
};
|
||||||
@@ -417,6 +417,104 @@ impl HostApi for PluginHostApi {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn system_variable(&self, name: &str) -> Option<HostSettingValue> {
|
||||||
|
match self.client.request(PluginRequest::GetSystemVariable { name: name.to_owned() }) {
|
||||||
|
Ok(PluginResponse::SystemVariable(value)) => value,
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_system_variable(
|
||||||
|
&mut self,
|
||||||
|
name: &str,
|
||||||
|
value: HostSettingValue,
|
||||||
|
) -> Result<HostSettingValue, String> {
|
||||||
|
match self.client.request(PluginRequest::SetSystemVariable {
|
||||||
|
name: name.to_owned(),
|
||||||
|
value,
|
||||||
|
}) {
|
||||||
|
Ok(PluginResponse::SystemVariableResult(result)) => {
|
||||||
|
if result.is_ok() {
|
||||||
|
self.document_cache = OnceCell::new();
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
Ok(PluginResponse::Error(error)) => Err(error),
|
||||||
|
Ok(other) => Err(format!("unexpected system variable response: {other:?}")),
|
||||||
|
Err(error) => Err(error.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update_entities_transaction(
|
||||||
|
&mut self,
|
||||||
|
label: &str,
|
||||||
|
entities: Vec<EntityType>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
match self.client.request(PluginRequest::UpdateEntitiesTransaction {
|
||||||
|
label: label.to_owned(), entities,
|
||||||
|
}) {
|
||||||
|
Ok(PluginResponse::EntityTransactionResult(result)) => {
|
||||||
|
if result.is_ok() { self.document_cache = OnceCell::new(); }
|
||||||
|
result
|
||||||
|
}
|
||||||
|
Ok(PluginResponse::Error(error)) => Err(error),
|
||||||
|
Ok(other) => Err(format!("unexpected entity transaction response: {other:?}")),
|
||||||
|
Err(error) => Err(error.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn selection(&self) -> Vec<Handle> {
|
||||||
|
match self.client.request(PluginRequest::GetSelection) {
|
||||||
|
Ok(PluginResponse::Selection(handles)) => handles,
|
||||||
|
_ => Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn solid_operation(&mut self, operation: crate::host::SolidOperation) -> Result<Handle, String> {
|
||||||
|
match self.client.request(PluginRequest::SolidOperation { operation }) {
|
||||||
|
Ok(PluginResponse::SolidResult(result)) => {
|
||||||
|
if result.is_ok() { self.document_cache = OnceCell::new(); }
|
||||||
|
result
|
||||||
|
}
|
||||||
|
Ok(PluginResponse::Error(error)) => Err(error),
|
||||||
|
Ok(other) => Err(format!("unexpected solid operation response: {other:?}")),
|
||||||
|
Err(error) => Err(error.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run_command(&mut self, request: crate::host::CommandRequest) -> Result<crate::host::CommandOutcome, String> {
|
||||||
|
match self.client.request(PluginRequest::RunCommand { request }) {
|
||||||
|
Ok(PluginResponse::CommandResult(result)) => {
|
||||||
|
self.document_cache = OnceCell::new();
|
||||||
|
result
|
||||||
|
}
|
||||||
|
Ok(PluginResponse::Error(error)) => Err(error),
|
||||||
|
Ok(other) => Err(format!("unexpected command response: {other:?}")),
|
||||||
|
Err(error) => Err(error.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn table_operation(&mut self, operation: crate::host::TableOperation) -> Result<Handle, String> {
|
||||||
|
match self.client.request(PluginRequest::TableOperation { operation }) {
|
||||||
|
Ok(PluginResponse::TableResult(result)) => {
|
||||||
|
if result.is_ok() { self.document_cache = OnceCell::new(); }
|
||||||
|
result
|
||||||
|
}
|
||||||
|
Ok(PluginResponse::Error(error)) => Err(error),
|
||||||
|
Ok(other) => Err(format!("unexpected table operation response: {other:?}")),
|
||||||
|
Err(error) => Err(error.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_selection(&mut self, handles: &[Handle]) -> Result<(), String> {
|
||||||
|
match self.client.request(PluginRequest::SetSelection { handles: handles.to_vec() }) {
|
||||||
|
Ok(PluginResponse::SelectionResult(result)) => result,
|
||||||
|
Ok(PluginResponse::Error(error)) => Err(error),
|
||||||
|
Ok(other) => Err(format!("unexpected selection response: {other:?}")),
|
||||||
|
Err(error) => Err(error.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn add_layer(&mut self, config: crate::host::LayerConfig) -> Option<Handle> {
|
fn add_layer(&mut self, config: crate::host::LayerConfig) -> Option<Handle> {
|
||||||
match self.client.request(PluginRequest::AddLayer(config)) {
|
match self.client.request(PluginRequest::AddLayer(config)) {
|
||||||
Ok(PluginResponse::OptHandle(h)) => {
|
Ok(PluginResponse::OptHandle(h)) => {
|
||||||
|
|||||||
@@ -17,7 +17,7 @@
|
|||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::host::{CommandSource, CommandStep};
|
use crate::host::{CommandSource, CommandStep, HostSettingValue};
|
||||||
use crate::manifest::ApiVersion;
|
use crate::manifest::ApiVersion;
|
||||||
use crate::ribbon::owned::{OwnedPluginManifest, OwnedRibbonGroup};
|
use crate::ribbon::owned::{OwnedPluginManifest, OwnedRibbonGroup};
|
||||||
|
|
||||||
@@ -81,6 +81,8 @@ pub enum HostRequest {
|
|||||||
code: String,
|
code: String,
|
||||||
tab_index: usize,
|
tab_index: usize,
|
||||||
},
|
},
|
||||||
|
/// V7: release an interactive command after completion or cancellation.
|
||||||
|
DropInteractive { command_id: u64 },
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Responses the plugin runner sends back for `HostRequest`.
|
/// Responses the plugin runner sends back for `HostRequest`.
|
||||||
@@ -149,6 +151,21 @@ pub enum PluginRequest {
|
|||||||
ModifyLayer(crate::host::LayerConfig),
|
ModifyLayer(crate::host::LayerConfig),
|
||||||
/// Run a command on the active document tab's command line (AutoLISP style).
|
/// Run a command on the active document tab's command line (AutoLISP style).
|
||||||
ExecuteCommand(String),
|
ExecuteCommand(String),
|
||||||
|
/// Read a host-managed setting without nested command dispatch.
|
||||||
|
GetSystemVariable { name: String },
|
||||||
|
/// Change a host-managed setting without nested command dispatch.
|
||||||
|
SetSystemVariable { name: String, value: HostSettingValue },
|
||||||
|
/// V7: validate and replace existing entities in a single undo step.
|
||||||
|
UpdateEntitiesTransaction { label: String, entities: Vec<EntityType> },
|
||||||
|
/// V7: synchronous selection read/write for the dispatch tab.
|
||||||
|
GetSelection,
|
||||||
|
SetSelection { handles: Vec<Handle> },
|
||||||
|
/// V7 (additive): kernel-backed solid create or transform.
|
||||||
|
SolidOperation { operation: crate::host::SolidOperation },
|
||||||
|
/// V7 (additive): drawing table record create/modify/rename/delete.
|
||||||
|
TableOperation { operation: crate::host::TableOperation },
|
||||||
|
/// V7 (additive): drive an OCS command.
|
||||||
|
RunCommand { request: crate::host::CommandRequest },
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Responses the host sends back for `PluginRequest`.
|
/// Responses the host sends back for `PluginRequest`.
|
||||||
@@ -177,6 +194,14 @@ pub enum PluginResponse {
|
|||||||
DocumentPath(Option<std::ffi::OsString>),
|
DocumentPath(Option<std::ffi::OsString>),
|
||||||
/// Optional entity handle (e.g. from AddLayer).
|
/// Optional entity handle (e.g. from AddLayer).
|
||||||
OptHandle(Option<Handle>),
|
OptHandle(Option<Handle>),
|
||||||
|
SystemVariable(Option<HostSettingValue>),
|
||||||
|
SystemVariableResult(Result<HostSettingValue, String>),
|
||||||
|
EntityTransactionResult(Result<(), String>),
|
||||||
|
Selection(Vec<Handle>),
|
||||||
|
SelectionResult(Result<(), String>),
|
||||||
|
SolidResult(Result<Handle, String>),
|
||||||
|
TableResult(Result<Handle, String>),
|
||||||
|
CommandResult(Result<crate::host::CommandOutcome, String>),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Messages sent from the host to the plugin runner.
|
/// Messages sent from the host to the plugin runner.
|
||||||
|
|||||||
@@ -3,6 +3,27 @@
|
|||||||
use crate::host::HostApi;
|
use crate::host::HostApi;
|
||||||
use crate::ipc::protocol::{PluginRequest, PluginResponse};
|
use crate::ipc::protocol::{PluginRequest, PluginResponse};
|
||||||
|
|
||||||
|
fn addressable_document_snapshot(host: &dyn HostApi) -> acadrust::CadDocument {
|
||||||
|
let mut snapshot = host.document().clone();
|
||||||
|
let attributes = host
|
||||||
|
.document()
|
||||||
|
.entities()
|
||||||
|
.filter_map(|entity| match entity {
|
||||||
|
acadrust::EntityType::Insert(insert) => Some(insert.attributes.clone()),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.flatten()
|
||||||
|
.map(acadrust::EntityType::AttributeEntity)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
for attribute in attributes {
|
||||||
|
// Attribute entities remain canonical children of INSERT in the host
|
||||||
|
// document. The IPC snapshot also indexes them by handle so plugin
|
||||||
|
// document models can address a child exactly like any other entity.
|
||||||
|
let _ = snapshot.add_entity(attribute);
|
||||||
|
}
|
||||||
|
snapshot
|
||||||
|
}
|
||||||
|
|
||||||
/// Apply one plugin request to the host's `HostApi` implementation.
|
/// Apply one plugin request to the host's `HostApi` implementation.
|
||||||
///
|
///
|
||||||
/// `on_start_interactive` is called when the plugin starts an interactive
|
/// `on_start_interactive` is called when the plugin starts an interactive
|
||||||
@@ -54,7 +75,7 @@ pub fn handle_plugin_request(
|
|||||||
on_start_interactive(command_id);
|
on_start_interactive(command_id);
|
||||||
PluginResponse::Ok
|
PluginResponse::Ok
|
||||||
}
|
}
|
||||||
DocumentSnapshot => PluginResponse::Document(Box::new(host.document().clone())),
|
DocumentSnapshot => PluginResponse::Document(Box::new(addressable_document_snapshot(host))),
|
||||||
OpenDocumentView => match host.document_view() {
|
OpenDocumentView => match host.document_view() {
|
||||||
Some(info) => PluginResponse::DocumentView {
|
Some(info) => PluginResponse::DocumentView {
|
||||||
path: info.path,
|
path: info.path,
|
||||||
@@ -80,5 +101,17 @@ pub fn handle_plugin_request(
|
|||||||
AddLayer(config) => PluginResponse::OptHandle(host.add_layer(config)),
|
AddLayer(config) => PluginResponse::OptHandle(host.add_layer(config)),
|
||||||
ModifyLayer(config) => PluginResponse::Bool(host.modify_layer(config)),
|
ModifyLayer(config) => PluginResponse::Bool(host.modify_layer(config)),
|
||||||
ExecuteCommand(cmd) => PluginResponse::Bool(host.execute_command(&cmd)),
|
ExecuteCommand(cmd) => PluginResponse::Bool(host.execute_command(&cmd)),
|
||||||
|
GetSystemVariable { name } => PluginResponse::SystemVariable(host.system_variable(&name)),
|
||||||
|
SetSystemVariable { name, value } => {
|
||||||
|
PluginResponse::SystemVariableResult(host.set_system_variable(&name, value))
|
||||||
|
}
|
||||||
|
UpdateEntitiesTransaction { label, entities } => PluginResponse::EntityTransactionResult(
|
||||||
|
host.update_entities_transaction(&label, entities),
|
||||||
|
),
|
||||||
|
GetSelection => PluginResponse::Selection(host.selection()),
|
||||||
|
SetSelection { handles } => PluginResponse::SelectionResult(host.set_selection(&handles)),
|
||||||
|
SolidOperation { operation } => PluginResponse::SolidResult(host.solid_operation(operation)),
|
||||||
|
TableOperation { operation } => PluginResponse::TableResult(host.table_operation(operation)),
|
||||||
|
RunCommand { request } => PluginResponse::CommandResult(host.run_command(request)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -17,7 +17,7 @@ use interprocess::TryClone;
|
|||||||
|
|
||||||
use crate::host::{
|
use crate::host::{
|
||||||
DocumentReader, ExecutionResult, HostApi, HostNotification, InteractiveCommand,
|
DocumentReader, ExecutionResult, HostApi, HostNotification, InteractiveCommand,
|
||||||
PluginNotification, PluginRequestSender, PluginRequestError, ReaderEntity,
|
PluginNotification, PluginRequestSender, PluginRequestError, ReaderEntity, HostSettingValue,
|
||||||
};
|
};
|
||||||
use crate::ipc::protocol::{
|
use crate::ipc::protocol::{
|
||||||
HostRequest, HostResponse, PluginRequest, PluginResponse, RunnerHandshake,
|
HostRequest, HostResponse, PluginRequest, PluginResponse, RunnerHandshake,
|
||||||
@@ -731,6 +731,104 @@ impl HostApi for V4PluginHostApi {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn system_variable(&self, name: &str) -> Option<HostSettingValue> {
|
||||||
|
match self.request(PluginRequest::GetSystemVariable { name: name.to_owned() }) {
|
||||||
|
Ok(PluginResponse::SystemVariable(value)) => value,
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_system_variable(
|
||||||
|
&mut self,
|
||||||
|
name: &str,
|
||||||
|
value: HostSettingValue,
|
||||||
|
) -> Result<HostSettingValue, String> {
|
||||||
|
match self.request(PluginRequest::SetSystemVariable {
|
||||||
|
name: name.to_owned(),
|
||||||
|
value,
|
||||||
|
}) {
|
||||||
|
Ok(PluginResponse::SystemVariableResult(result)) => {
|
||||||
|
if result.is_ok() {
|
||||||
|
self.document_cache = OnceCell::new();
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
Ok(PluginResponse::Error(error)) => Err(error),
|
||||||
|
Ok(other) => Err(format!("unexpected system variable response: {other:?}")),
|
||||||
|
Err(error) => Err(error.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update_entities_transaction(
|
||||||
|
&mut self,
|
||||||
|
label: &str,
|
||||||
|
entities: Vec<EntityType>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
match self.request(PluginRequest::UpdateEntitiesTransaction {
|
||||||
|
label: label.to_owned(), entities,
|
||||||
|
}) {
|
||||||
|
Ok(PluginResponse::EntityTransactionResult(result)) => {
|
||||||
|
if result.is_ok() { self.document_cache = OnceCell::new(); }
|
||||||
|
result
|
||||||
|
}
|
||||||
|
Ok(PluginResponse::Error(error)) => Err(error),
|
||||||
|
Ok(other) => Err(format!("unexpected entity transaction response: {other:?}")),
|
||||||
|
Err(error) => Err(error.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn selection(&self) -> Vec<Handle> {
|
||||||
|
match self.request(PluginRequest::GetSelection) {
|
||||||
|
Ok(PluginResponse::Selection(handles)) => handles,
|
||||||
|
_ => Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn solid_operation(&mut self, operation: crate::host::SolidOperation) -> Result<Handle, String> {
|
||||||
|
match self.request(PluginRequest::SolidOperation { operation }) {
|
||||||
|
Ok(PluginResponse::SolidResult(result)) => {
|
||||||
|
if result.is_ok() { self.document_cache = OnceCell::new(); }
|
||||||
|
result
|
||||||
|
}
|
||||||
|
Ok(PluginResponse::Error(error)) => Err(error),
|
||||||
|
Ok(other) => Err(format!("unexpected solid operation response: {other:?}")),
|
||||||
|
Err(error) => Err(error.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run_command(&mut self, request: crate::host::CommandRequest) -> Result<crate::host::CommandOutcome, String> {
|
||||||
|
match self.request(PluginRequest::RunCommand { request }) {
|
||||||
|
Ok(PluginResponse::CommandResult(result)) => {
|
||||||
|
self.document_cache = OnceCell::new();
|
||||||
|
result
|
||||||
|
}
|
||||||
|
Ok(PluginResponse::Error(error)) => Err(error),
|
||||||
|
Ok(other) => Err(format!("unexpected command response: {other:?}")),
|
||||||
|
Err(error) => Err(error.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn table_operation(&mut self, operation: crate::host::TableOperation) -> Result<Handle, String> {
|
||||||
|
match self.request(PluginRequest::TableOperation { operation }) {
|
||||||
|
Ok(PluginResponse::TableResult(result)) => {
|
||||||
|
if result.is_ok() { self.document_cache = OnceCell::new(); }
|
||||||
|
result
|
||||||
|
}
|
||||||
|
Ok(PluginResponse::Error(error)) => Err(error),
|
||||||
|
Ok(other) => Err(format!("unexpected table operation response: {other:?}")),
|
||||||
|
Err(error) => Err(error.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_selection(&mut self, handles: &[Handle]) -> Result<(), String> {
|
||||||
|
match self.request(PluginRequest::SetSelection { handles: handles.to_vec() }) {
|
||||||
|
Ok(PluginResponse::SelectionResult(result)) => result,
|
||||||
|
Ok(PluginResponse::Error(error)) => Err(error),
|
||||||
|
Ok(other) => Err(format!("unexpected selection response: {other:?}")),
|
||||||
|
Err(error) => Err(error.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn add_layer(&mut self, config: crate::host::LayerConfig) -> Option<Handle> {
|
fn add_layer(&mut self, config: crate::host::LayerConfig) -> Option<Handle> {
|
||||||
match self.request(PluginRequest::AddLayer(config)) {
|
match self.request(PluginRequest::AddLayer(config)) {
|
||||||
Ok(PluginResponse::OptHandle(h)) => {
|
Ok(PluginResponse::OptHandle(h)) => {
|
||||||
|
|||||||
@@ -86,6 +86,167 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn command_state_notification_roundtrips() {
|
||||||
|
let notification = HostNotification::CommandStateChanged {
|
||||||
|
tab_id: 42,
|
||||||
|
command: Some("LINE".to_owned()),
|
||||||
|
};
|
||||||
|
let bytes = bincode::serialize(¬ification).unwrap();
|
||||||
|
let decoded: HostNotification = bincode::deserialize(&bytes).unwrap();
|
||||||
|
assert_eq!(decoded, notification);
|
||||||
|
let stopped = HostNotification::CommandStateChanged { tab_id: 42, command: None };
|
||||||
|
let bytes = bincode::serialize(&stopped).unwrap();
|
||||||
|
let decoded: HostNotification = bincode::deserialize(&bytes).unwrap();
|
||||||
|
assert_eq!(decoded, stopped);
|
||||||
|
let changed = HostNotification::DrawingChanged { tab_id: 42, epoch: 7 };
|
||||||
|
let bytes = bincode::serialize(&changed).unwrap();
|
||||||
|
let decoded: HostNotification = bincode::deserialize(&bytes).unwrap();
|
||||||
|
assert_eq!(decoded, changed);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn command_request_and_outcome_roundtrip() {
|
||||||
|
use crate::host::{CommandOutcome, CommandRequest};
|
||||||
|
for request in [
|
||||||
|
CommandRequest::Run { line: "LINE 0,0 1,1".into() },
|
||||||
|
CommandRequest::Start { name: "OFFSET".into() },
|
||||||
|
CommandRequest::Point { point: [1.0, 2.0, 3.0] },
|
||||||
|
CommandRequest::Text { text: "2".into() },
|
||||||
|
CommandRequest::Token { text: "R".into() },
|
||||||
|
CommandRequest::Entity { handle: acadrust::Handle::new(9), point: [0.0; 3] },
|
||||||
|
CommandRequest::Selection,
|
||||||
|
CommandRequest::Enter,
|
||||||
|
CommandRequest::Cancel,
|
||||||
|
] {
|
||||||
|
let bytes = bincode::serialize(&PluginRequest::RunCommand { request: request.clone() }).unwrap();
|
||||||
|
assert!(matches!(bincode::deserialize::<PluginRequest>(&bytes).unwrap(),
|
||||||
|
PluginRequest::RunCommand { request: decoded } if decoded == request));
|
||||||
|
}
|
||||||
|
let outcome = CommandOutcome {
|
||||||
|
status: "waiting_input".into(),
|
||||||
|
blocked_by: Some("command".into()),
|
||||||
|
command: "OFFSET".into(),
|
||||||
|
prompt: "Select object".into(),
|
||||||
|
accepts: vec!["entity".into()],
|
||||||
|
options: vec!["M".into()],
|
||||||
|
entities: 4,
|
||||||
|
added: -1,
|
||||||
|
unconsumed: vec!["x".into()],
|
||||||
|
error: Some("e".into()),
|
||||||
|
};
|
||||||
|
for result in [Ok(outcome), Err("refused".to_owned())] {
|
||||||
|
let bytes = bincode::serialize(&PluginResponse::CommandResult(result.clone())).unwrap();
|
||||||
|
assert!(matches!(bincode::deserialize::<PluginResponse>(&bytes).unwrap(),
|
||||||
|
PluginResponse::CommandResult(decoded) if decoded == result));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn table_operation_request_and_response_roundtrip() {
|
||||||
|
use crate::host::{LayerConfig, TableOperation};
|
||||||
|
for operation in [
|
||||||
|
TableOperation::LayerCreate {
|
||||||
|
config: LayerConfig {
|
||||||
|
name: "Walls".into(),
|
||||||
|
color: Some(acadrust::types::Color::Index(5)),
|
||||||
|
frozen: Some(true),
|
||||||
|
description: Some("d".into()),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
},
|
||||||
|
TableOperation::LayerModify { config: LayerConfig { name: "Walls".into(), off: Some(true), ..Default::default() } },
|
||||||
|
TableOperation::LayerRename { from: "A".into(), to: "B".into() },
|
||||||
|
TableOperation::LayerDelete { name: "A".into(), erase_objects: true },
|
||||||
|
TableOperation::LayerSetCurrent { name: "A".into() },
|
||||||
|
TableOperation::TextStyleCreate {
|
||||||
|
config: crate::host::TextStyleConfig { name: "T".into(), height: Some(2.5), oblique_angle: Some(0.2), backward: Some(true), ..Default::default() },
|
||||||
|
},
|
||||||
|
TableOperation::TextStyleModify { config: crate::host::TextStyleConfig { name: "T".into(), font_file: Some("romans".into()), ..Default::default() } },
|
||||||
|
TableOperation::DimStyleCreate { name: "D".into(), copy_from: Some("Standard".into()), properties: "{\"dimscale\":2}".into() },
|
||||||
|
TableOperation::DimStyleModify { name: "D".into(), properties: "{}".into() },
|
||||||
|
TableOperation::StyleRename { kind: crate::host::TableStyleKind::Text, from: "A".into(), to: "B".into() },
|
||||||
|
TableOperation::StyleDelete { kind: crate::host::TableStyleKind::Dim, name: "A".into() },
|
||||||
|
TableOperation::StyleSetCurrent { kind: crate::host::TableStyleKind::Dim, name: "A".into() },
|
||||||
|
TableOperation::BlockCreate {
|
||||||
|
name: "B".into(),
|
||||||
|
entities: vec![acadrust::Handle::new(4), acadrust::Handle::new(5)],
|
||||||
|
base_point: [1.0, 2.0, 3.0],
|
||||||
|
erase_originals: true,
|
||||||
|
description: Some("d".into()),
|
||||||
|
},
|
||||||
|
TableOperation::BlockModify { name: "B".into(), description: None, explodable: Some(false), scale_uniformly: Some(true) },
|
||||||
|
TableOperation::BlockRename { from: "B".into(), to: "C".into() },
|
||||||
|
TableOperation::BlockDelete { name: "C".into() },
|
||||||
|
TableOperation::BlockEntityAdd {
|
||||||
|
block: "C".into(),
|
||||||
|
entity: acadrust::EntityType::Line(acadrust::entities::Line::new()),
|
||||||
|
},
|
||||||
|
TableOperation::LinetypeCreate { name: "L".into(), description: "d".into(), pattern: vec![1.0, -1.0] },
|
||||||
|
TableOperation::LinetypeModify { name: "L".into(), description: None, pattern: Some(vec![2.0, -2.0]) },
|
||||||
|
TableOperation::LinetypeRename { from: "L".into(), to: "M".into() },
|
||||||
|
TableOperation::LinetypeDelete { name: "M".into() },
|
||||||
|
TableOperation::LayoutCreate { name: "S".into() },
|
||||||
|
TableOperation::LayoutRename { from: "S".into(), to: "T".into() },
|
||||||
|
TableOperation::LayoutDelete { name: "T".into() },
|
||||||
|
TableOperation::LayoutSetCurrent { name: "Model".into() },
|
||||||
|
TableOperation::LayoutSetPage { name: "S".into(), paper_size: Some([420.0, 297.0]), rotation: Some(90), scale: Some([1.0, 50.0]) },
|
||||||
|
] {
|
||||||
|
let bytes = bincode::serialize(&PluginRequest::TableOperation { operation: operation.clone() }).unwrap();
|
||||||
|
assert!(matches!(bincode::deserialize::<PluginRequest>(&bytes).unwrap(),
|
||||||
|
PluginRequest::TableOperation { operation: decoded } if decoded == operation));
|
||||||
|
}
|
||||||
|
for result in [Ok(acadrust::Handle::new(9)), Err("refused".to_owned())] {
|
||||||
|
let bytes = bincode::serialize(&PluginResponse::TableResult(result.clone())).unwrap();
|
||||||
|
assert!(matches!(bincode::deserialize::<PluginResponse>(&bytes).unwrap(),
|
||||||
|
PluginResponse::TableResult(decoded) if decoded == result));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn solid_operation_request_and_response_roundtrip() {
|
||||||
|
use crate::host::{SolidOperation, SolidPrimitive};
|
||||||
|
for operation in [
|
||||||
|
SolidOperation::Create {
|
||||||
|
primitive: SolidPrimitive::Pyramid { center: [1.0, 2.0, 3.0], radius: 4.0, height: 5.0, sides: 6 },
|
||||||
|
layer: Some("SOLIDS".into()),
|
||||||
|
},
|
||||||
|
SolidOperation::Transform { handle: acadrust::Handle::new(7), matrix: [1.0; 16] },
|
||||||
|
SolidOperation::RegionFromProfile { source: acadrust::Handle::new(3), layer: None, delete_source: true },
|
||||||
|
SolidOperation::EmbedPicture { path: "p.png".into(), origin: [0.0; 3], width: 5.0, layer: None },
|
||||||
|
SolidOperation::Boolean {
|
||||||
|
first: acadrust::Handle::new(1),
|
||||||
|
second: acadrust::Handle::new(2),
|
||||||
|
operation: crate::host::SolidBoolean::Subtract,
|
||||||
|
layer: None,
|
||||||
|
keep_operands: false,
|
||||||
|
},
|
||||||
|
SolidOperation::SurfaceFromProfile { source: acadrust::Handle::new(4), layer: Some("S".into()), delete_source: false },
|
||||||
|
SolidOperation::Extrude { source: acadrust::Handle::new(5), direction: [0.0, 0.0, 2.0], layer: None, delete_source: true },
|
||||||
|
] {
|
||||||
|
let bytes = bincode::serialize(&PluginRequest::SolidOperation { operation: operation.clone() }).unwrap();
|
||||||
|
assert!(matches!(bincode::deserialize::<PluginRequest>(&bytes).unwrap(),
|
||||||
|
PluginRequest::SolidOperation { operation: decoded } if decoded == operation));
|
||||||
|
}
|
||||||
|
for result in [Ok(acadrust::Handle::new(9)), Err("refused".to_owned())] {
|
||||||
|
let bytes = bincode::serialize(&PluginResponse::SolidResult(result.clone())).unwrap();
|
||||||
|
assert!(matches!(bincode::deserialize::<PluginResponse>(&bytes).unwrap(),
|
||||||
|
PluginResponse::SolidResult(decoded) if decoded == result));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn selection_request_and_response_roundtrip() {
|
||||||
|
let request = PluginRequest::SetSelection { handles: vec![acadrust::Handle::new(9)] };
|
||||||
|
let bytes = bincode::serialize(&request).unwrap();
|
||||||
|
assert!(matches!(bincode::deserialize::<PluginRequest>(&bytes).unwrap(),
|
||||||
|
PluginRequest::SetSelection { handles } if handles == vec![acadrust::Handle::new(9)]));
|
||||||
|
let response = PluginResponse::Selection(vec![acadrust::Handle::new(9)]);
|
||||||
|
let bytes = bincode::serialize(&response).unwrap();
|
||||||
|
assert!(matches!(bincode::deserialize::<PluginResponse>(&bytes).unwrap(),
|
||||||
|
PluginResponse::Selection(handles) if handles == vec![acadrust::Handle::new(9)]));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn plugin_notification_roundtrip() {
|
fn plugin_notification_roundtrip() {
|
||||||
let frame = PluginToHostV4::Notification(NotificationEnvelope {
|
let frame = PluginToHostV4::Notification(NotificationEnvelope {
|
||||||
|
|||||||
@@ -36,6 +36,8 @@ pub mod manifest;
|
|||||||
pub mod ribbon;
|
pub mod ribbon;
|
||||||
pub mod type_registry;
|
pub mod type_registry;
|
||||||
pub mod type_registry_types;
|
pub mod type_registry_types;
|
||||||
|
pub mod entity_coverage;
|
||||||
|
pub mod entity_coverage_types;
|
||||||
pub mod version_info;
|
pub mod version_info;
|
||||||
|
|
||||||
/// Runtime host surface — only built with the `host` feature (pulls `acadrust`).
|
/// Runtime host surface — only built with the `host` feature (pulls `acadrust`).
|
||||||
@@ -73,6 +75,8 @@ pub use type_registry::{
|
|||||||
get_embedded_type_registry_json, EnumVariantInfo, FieldInfo, MethodInfo, ParameterInfo,
|
get_embedded_type_registry_json, EnumVariantInfo, FieldInfo, MethodInfo, ParameterInfo,
|
||||||
TypeId, TypeInfo, TypeKind, TypeRegistry,
|
TypeId, TypeInfo, TypeKind, TypeRegistry,
|
||||||
};
|
};
|
||||||
|
pub use entity_coverage::{get_embedded_entity_coverage_json, EntityCoverageCatalog,
|
||||||
|
EntityKindCoverage, EntityScope, ModelAccess, PropertyCoverage};
|
||||||
pub use version_info::get_embedded_version_info_json;
|
pub use version_info::get_embedded_version_info_json;
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@@ -19,8 +19,10 @@
|
|||||||
/// vtable so API v2 plugins keep working. v4 adds full-duplex notifications on
|
/// vtable so API v2 plugins keep working. v4 adds full-duplex notifications on
|
||||||
/// a multiplexed socket while leaving the V2/V3 ABI and protocol untouched. v5
|
/// a multiplexed socket while leaving the V2/V3 ABI and protocol untouched. v5
|
||||||
/// adds the `BuiltinPlugin::on_load` lifecycle callback and
|
/// adds the `BuiltinPlugin::on_load` lifecycle callback and
|
||||||
/// `HostApi::document_path`.
|
/// `HostApi::document_path`. v6 appends generic host system-variable access
|
||||||
pub const API_VERSION: u32 = 5;
|
/// (`HostApi::system_variable` / `set_system_variable`). v7 appends atomic,
|
||||||
|
/// undoable replacement of a set of existing entities.
|
||||||
|
pub const API_VERSION: u32 = 7;
|
||||||
|
|
||||||
/// Oldest plugin API major the current host still loads. This keeps previously
|
/// Oldest plugin API major the current host still loads. This keeps previously
|
||||||
/// compiled cdylibs usable as long as their vtable layout is a prefix of the
|
/// compiled cdylibs usable as long as their vtable layout is a prefix of the
|
||||||
@@ -28,7 +30,7 @@ pub const API_VERSION: u32 = 5;
|
|||||||
pub const API_VERSION_MIN_SUPPORTED: u32 = 2;
|
pub const API_VERSION_MIN_SUPPORTED: u32 = 2;
|
||||||
|
|
||||||
/// Environment variable that caps the API major accepted by the host at
|
/// Environment variable that caps the API major accepted by the host at
|
||||||
/// runtime. Set to `4` to disable V5 plugins, `3` to disable V4, or `2` for
|
/// runtime. Set to `5` to disable V6 plugins, `4` to disable V5, or `2` for
|
||||||
/// V2-only mode.
|
/// V2-only mode.
|
||||||
pub const MAX_API_VERSION_ENV: &str = "OCS_PLUGIN_MAX_API_VERSION";
|
pub const MAX_API_VERSION_ENV: &str = "OCS_PLUGIN_MAX_API_VERSION";
|
||||||
|
|
||||||
|
|||||||
@@ -237,6 +237,7 @@ pub(crate) fn request_kind(req: &HostRequest) -> &'static str {
|
|||||||
HostRequest::GetPrompt { .. } => "GetPrompt",
|
HostRequest::GetPrompt { .. } => "GetPrompt",
|
||||||
HostRequest::NeedsEntityPick { .. } => "NeedsEntityPick",
|
HostRequest::NeedsEntityPick { .. } => "NeedsEntityPick",
|
||||||
HostRequest::ExecuteCode { .. } => "ExecuteCode",
|
HostRequest::ExecuteCode { .. } => "ExecuteCode",
|
||||||
|
HostRequest::DropInteractive { .. } => "DropInteractive",
|
||||||
HostRequest::Shutdown => "Shutdown",
|
HostRequest::Shutdown => "Shutdown",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -621,6 +622,15 @@ impl PluginProcess {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Release a completed or abandoned V4 interactive command in the runner.
|
||||||
|
pub fn drop_interactive(&self, command_id: u64) -> Result<(), PluginError> {
|
||||||
|
let Some(v4) = &self.v4 else { return Ok(()); };
|
||||||
|
match v4.call(&mut NullHost, HostRequest::DropInteractive { command_id }, &mut |_| {})? {
|
||||||
|
HostResponse::Bool(true) => Ok(()),
|
||||||
|
other => Err(PluginError::UnexpectedResponse(Box::new(other))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Ask the plugin process for the current prompt of an interactive command.
|
/// Ask the plugin process for the current prompt of an interactive command.
|
||||||
pub fn get_prompt(&self, command_id: u64) -> Result<String, PluginError> {
|
pub fn get_prompt(&self, command_id: u64) -> Result<String, PluginError> {
|
||||||
if let Some(v4) = &self.v4 {
|
if let Some(v4) = &self.v4 {
|
||||||
|
|||||||
@@ -16,8 +16,7 @@ use crate::ipc::v4::protocol::{HostToPluginV4, NotificationEnvelope};
|
|||||||
use crate::ipc::v4::server::{
|
use crate::ipc::v4::server::{
|
||||||
default_notify_rate_limit, run_host_reader_thread, HostIncoming, RateLimiter, V4HostShared,
|
default_notify_rate_limit, run_host_reader_thread, HostIncoming, RateLimiter, V4HostShared,
|
||||||
};
|
};
|
||||||
use crate::process::PluginError;
|
use crate::process::{request_kind, request_timeout, PluginError};
|
||||||
use crate::process::{request_kind, request_timeout};
|
|
||||||
|
|
||||||
type DeferredRequest = (u64, Option<u64>, Box<PluginRequest>);
|
type DeferredRequest = (u64, Option<u64>, Box<PluginRequest>);
|
||||||
|
|
||||||
@@ -387,16 +386,21 @@ mod tests {
|
|||||||
|
|
||||||
struct DummyHost {
|
struct DummyHost {
|
||||||
push_info_messages: StdMutex<Vec<String>>,
|
push_info_messages: StdMutex<Vec<String>>,
|
||||||
|
transactions: StdMutex<Vec<(String, Vec<acadrust::EntityType>)>>,
|
||||||
}
|
}
|
||||||
impl DummyHost {
|
impl DummyHost {
|
||||||
fn new() -> Self {
|
fn new() -> Self {
|
||||||
Self {
|
Self {
|
||||||
push_info_messages: StdMutex::new(Vec::new()),
|
push_info_messages: StdMutex::new(Vec::new()),
|
||||||
|
transactions: StdMutex::new(Vec::new()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn take_push_info(&self) -> Vec<String> {
|
fn take_push_info(&self) -> Vec<String> {
|
||||||
std::mem::take(&mut *self.push_info_messages.lock().unwrap())
|
std::mem::take(&mut *self.push_info_messages.lock().unwrap())
|
||||||
}
|
}
|
||||||
|
fn take_transactions(&self) -> Vec<(String, Vec<acadrust::EntityType>)> {
|
||||||
|
std::mem::take(&mut *self.transactions.lock().unwrap())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
impl HostApi for DummyHost {
|
impl HostApi for DummyHost {
|
||||||
fn tab_index(&self) -> usize {
|
fn tab_index(&self) -> usize {
|
||||||
@@ -433,6 +437,14 @@ mod tests {
|
|||||||
false
|
false
|
||||||
}
|
}
|
||||||
fn push_undo(&mut self, _label: &str) {}
|
fn push_undo(&mut self, _label: &str) {}
|
||||||
|
fn update_entities_transaction(
|
||||||
|
&mut self,
|
||||||
|
label: &str,
|
||||||
|
entities: Vec<acadrust::EntityType>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
self.transactions.lock().unwrap().push((label.to_owned(), entities));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
fn set_dirty(&mut self) {}
|
fn set_dirty(&mut self) {}
|
||||||
fn push_info(&mut self, msg: &str) {
|
fn push_info(&mut self, msg: &str) {
|
||||||
self.push_info_messages.lock().unwrap().push(msg.to_string());
|
self.push_info_messages.lock().unwrap().push(msg.to_string());
|
||||||
@@ -604,6 +616,49 @@ mod tests {
|
|||||||
restore_test_env();
|
restore_test_env();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn v4_connection_routes_entity_transaction_over_nested_ipc() {
|
||||||
|
let _guard = ENV_LOCK.lock().unwrap();
|
||||||
|
set_test_env();
|
||||||
|
let (host_stream, mut runner_stream) = connect_pair();
|
||||||
|
let handler: Arc<dyn Fn(Option<u64>, PluginNotification) + Send + Sync> =
|
||||||
|
Arc::new(|_, _| {});
|
||||||
|
let conn = V4Connection::new(host_stream, handler).unwrap();
|
||||||
|
let mut point = acadrust::entities::Point::new();
|
||||||
|
point.common.handle = Handle::new(42);
|
||||||
|
point.location.x = 7.0;
|
||||||
|
let expected = acadrust::EntityType::Point(point);
|
||||||
|
let sent = expected.clone();
|
||||||
|
|
||||||
|
let runner = thread::spawn(move || {
|
||||||
|
let req = recv::<HostToPluginV4>(&mut runner_stream).unwrap();
|
||||||
|
let HostToPluginV4::Request { id, payload: HostRequest::Dispatch { .. } } = req else {
|
||||||
|
panic!("unexpected host request: {req:?}");
|
||||||
|
};
|
||||||
|
send(&mut runner_stream, &PluginToHostV4::Request {
|
||||||
|
id: 99,
|
||||||
|
tab_id: Some(0),
|
||||||
|
payload: PluginRequest::UpdateEntitiesTransaction {
|
||||||
|
label: "Move point".into(),
|
||||||
|
entities: vec![sent],
|
||||||
|
},
|
||||||
|
}).unwrap();
|
||||||
|
assert!(matches!(recv::<HostToPluginV4>(&mut runner_stream).unwrap(),
|
||||||
|
HostToPluginV4::Response { id: 99, payload: PluginResponse::EntityTransactionResult(Ok(())) }));
|
||||||
|
send(&mut runner_stream, &PluginToHostV4::Response {
|
||||||
|
id,
|
||||||
|
payload: HostResponse::Bool(true),
|
||||||
|
}).unwrap();
|
||||||
|
});
|
||||||
|
|
||||||
|
let mut host = DummyHost::new();
|
||||||
|
assert!(matches!(conn.call(&mut host, HostRequest::Dispatch { cmd: "MOVE".into() }, &mut |_| {}).unwrap(),
|
||||||
|
HostResponse::Bool(true)));
|
||||||
|
assert_eq!(host.take_transactions(), vec![("Move point".into(), vec![expected])]);
|
||||||
|
runner.join().unwrap();
|
||||||
|
restore_test_env();
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn v4_connection_notification_invokes_handler() {
|
fn v4_connection_notification_invokes_handler() {
|
||||||
let _guard = ENV_LOCK.lock().unwrap();
|
let _guard = ENV_LOCK.lock().unwrap();
|
||||||
|
|||||||
@@ -211,6 +211,10 @@ fn handle_host_request(
|
|||||||
Err(_) => HostResponse::Error("interactive command panicked".to_string()),
|
Err(_) => HostResponse::Error("interactive command panicked".to_string()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
HostRequest::DropInteractive { command_id } => {
|
||||||
|
interactive.borrow_mut().remove(&command_id);
|
||||||
|
HostResponse::Bool(true)
|
||||||
|
}
|
||||||
HostRequest::GetPrompt { command_id } => {
|
HostRequest::GetPrompt { command_id } => {
|
||||||
let result = {
|
let result = {
|
||||||
let registry = interactive.borrow();
|
let registry = interactive.borrow();
|
||||||
@@ -330,6 +334,10 @@ fn handle_host_request_v4(
|
|||||||
Err(_) => Some(HostResponse::Error("interactive command panicked".to_string())),
|
Err(_) => Some(HostResponse::Error("interactive command panicked".to_string())),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
HostRequest::DropInteractive { command_id } => {
|
||||||
|
interactive.borrow_mut().remove(&command_id);
|
||||||
|
Some(HostResponse::Bool(true))
|
||||||
|
}
|
||||||
HostRequest::GetPrompt { command_id } => {
|
HostRequest::GetPrompt { command_id } => {
|
||||||
let result = {
|
let result = {
|
||||||
let registry = interactive.borrow();
|
let registry = interactive.borrow();
|
||||||
|
|||||||
@@ -83,13 +83,19 @@ impl<T: SnapshotData> DocumentSnapshotStore<T> {
|
|||||||
/// page.
|
/// page.
|
||||||
pub fn new(tab_id: u64, segment_size: usize) -> io::Result<Self> {
|
pub fn new(tab_id: u64, segment_size: usize) -> io::Result<Self> {
|
||||||
let segment_size = segment_size.checked_next_multiple_of(4096).ok_or_else(|| {
|
let segment_size = segment_size.checked_next_multiple_of(4096).ok_or_else(|| {
|
||||||
io::Error::new(io::ErrorKind::InvalidInput, "snapshot segment size overflow")
|
io::Error::new(
|
||||||
|
io::ErrorKind::InvalidInput,
|
||||||
|
"snapshot segment size overflow",
|
||||||
|
)
|
||||||
})?;
|
})?;
|
||||||
let total = segment_size
|
let total = segment_size
|
||||||
.checked_mul(2)
|
.checked_mul(2)
|
||||||
.and_then(|segments| CONTROL_SIZE.checked_add(segments))
|
.and_then(|segments| CONTROL_SIZE.checked_add(segments))
|
||||||
.ok_or_else(|| {
|
.ok_or_else(|| {
|
||||||
io::Error::new(io::ErrorKind::InvalidInput, "snapshot mapping size overflow")
|
io::Error::new(
|
||||||
|
io::ErrorKind::InvalidInput,
|
||||||
|
"snapshot mapping size overflow",
|
||||||
|
)
|
||||||
})?;
|
})?;
|
||||||
if total > MAX_SNAPSHOT_SIZE {
|
if total > MAX_SNAPSHOT_SIZE {
|
||||||
return Err(io::Error::new(
|
return Err(io::Error::new(
|
||||||
@@ -245,7 +251,10 @@ impl<T: SnapshotData> SharedDocumentReader<T> {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
let file_len = usize::try_from(file_len).map_err(|_| {
|
let file_len = usize::try_from(file_len).map_err(|_| {
|
||||||
io::Error::new(io::ErrorKind::InvalidData, "snapshot file size is unsupported")
|
io::Error::new(
|
||||||
|
io::ErrorKind::InvalidData,
|
||||||
|
"snapshot file size is unsupported",
|
||||||
|
)
|
||||||
})?;
|
})?;
|
||||||
let mmap = unsafe { MmapOptions::new().len(file_len).map(&file)? };
|
let mmap = unsafe { MmapOptions::new().len(file_len).map(&file)? };
|
||||||
let segment_size = (file_len - CONTROL_SIZE) / 2;
|
let segment_size = (file_len - CONTROL_SIZE) / 2;
|
||||||
@@ -543,10 +552,22 @@ pub struct DocumentViewDataV4 {
|
|||||||
|
|
||||||
impl From<&CadDocument> for DocumentViewDataV4 {
|
impl From<&CadDocument> for DocumentViewDataV4 {
|
||||||
fn from(doc: &CadDocument) -> Self {
|
fn from(doc: &CadDocument) -> Self {
|
||||||
|
let mut entities: Vec<_> = doc.entities().map(EntityViewV4::from).collect();
|
||||||
|
// ATTRIB records live inside their owning INSERT in CadDocument rather
|
||||||
|
// than in the flat entity index. Flatten them into the plugin snapshot
|
||||||
|
// as addressable entities while keeping the INSERT's canonical nested
|
||||||
|
// copy intact for rendering and file serialization.
|
||||||
|
for entity in doc.entities() {
|
||||||
|
if let EntityType::Insert(insert) = entity {
|
||||||
|
entities.extend(insert.attributes.iter().map(|attribute| {
|
||||||
|
EntityViewV4::from(&EntityType::AttributeEntity(attribute.clone()))
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
Self {
|
Self {
|
||||||
layers: doc.layers.iter().map(LayerView::from).collect(),
|
layers: doc.layers.iter().map(LayerView::from).collect(),
|
||||||
app_ids: doc.app_ids.iter().map(AppIdView::from).collect(),
|
app_ids: doc.app_ids.iter().map(AppIdView::from).collect(),
|
||||||
entities: doc.entities().map(EntityViewV4::from).collect(),
|
entities,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -721,7 +742,10 @@ mod tests {
|
|||||||
|
|
||||||
let archived = reader.archived().unwrap();
|
let archived = reader.archived().unwrap();
|
||||||
let entity = &archived.entities[0];
|
let entity = &archived.entities[0];
|
||||||
assert_eq!(entity.handle, doc.entities().next().unwrap().common().handle.value());
|
assert_eq!(
|
||||||
|
entity.handle,
|
||||||
|
doc.entities().next().unwrap().common().handle.value()
|
||||||
|
);
|
||||||
let decoded: EntityType = bincode::deserialize(&entity.data).expect("bincode decode");
|
let decoded: EntityType = bincode::deserialize(&entity.data).expect("bincode decode");
|
||||||
assert!(matches!(decoded, EntityType::Point(_)));
|
assert!(matches!(decoded, EntityType::Point(_)));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,220 @@
|
|||||||
|
# cadcodec DXF reader/writer gaps found by the OCS Python host audit
|
||||||
|
|
||||||
|
Reports on `HakanSeven12/cadcodec` (the `acadrust` crate). **Status (21 September
|
||||||
|
2026):** fixes for issues 1-6 below, with regression tests, are submitted as
|
||||||
|
[HakanSeven12/cadcodec#48](https://github.com/HakanSeven12/cadcodec/pull/48) (branch
|
||||||
|
`fix/dxf-reader-writer-roundtrip` on `felixriestra/cadcodec`); the five findings under
|
||||||
|
"Observed but not filed" and the style and block ones added later are not filed. Every finding was made against **cadcodec revision
|
||||||
|
`5b682ed`** (OCS pins `acadrust` to it) by saving a document with
|
||||||
|
`DxfWriter` or `DwgWriter`, reloading it, and comparing entity fields.
|
||||||
|
|
||||||
|
Each report names an executable canary in OCS (`src/app/plugin_host.rs`). The
|
||||||
|
canaries assert today's wrong result, so they fail loudly once cadcodec is
|
||||||
|
fixed; flip the marked expectation when that happens. To reproduce, from the
|
||||||
|
OCS repository:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
STAGE="$PWD/work/bundled-plugins/opencad.python"
|
||||||
|
bash plugins/opencad-python/tools/stage-bundled.sh "$STAGE" --debug
|
||||||
|
cargo build --bin OpenCADStudio
|
||||||
|
OCS_TEST_PYTHON_PLUGIN="$STAGE/libopencad_python.dylib" \
|
||||||
|
OCS_PLUGIN_RUNNER_EXE="$PWD/target/debug/OpenCADStudio" \
|
||||||
|
cargo test --lib app::plugin_host::tests::<test name> -- --test-threads=1
|
||||||
|
```
|
||||||
|
|
||||||
|
| # | Area | Severity | Effect |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 1 | `ATTDEF` reader | high | Most attribute-definition properties silently reset to defaults |
|
||||||
|
| 2 | Boolean group codes (290-299) | high | Booleans read through `as_i16()` are never applied |
|
||||||
|
| 3 | `UNDERLAY` rotation | high | Rotation is not converted back to radians; repeated saves compound it |
|
||||||
|
| 4 | `LEADER` | medium | Annotation link and three vectors are lost |
|
||||||
|
| 5 | `DRAWINGVIEW` / `SECTIONLINE` | medium | Typed entity not restored from the ENTITIES section |
|
||||||
|
| 6 | `TABLE` merged ranges | low | `merged_ranges` is empty after DXF reopen |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. ATTDEF reader handles eight group codes; the writer emits all of them
|
||||||
|
|
||||||
|
**Where:** `src/io/dxf/reader/section_reader.rs`, `read_attdef` (around line
|
||||||
|
15647). The writer, `write_attdef` in `writer/section_writer.rs` (around line
|
||||||
|
4837), emits `7, 11, 41, 51, 70, 71, 72, 73, 74, 210` and `280` in addition to
|
||||||
|
the groups the reader consumes.
|
||||||
|
|
||||||
|
**What happens:** the reader has arms for groups `1, 2, 3, 10/20/30, 40, 50,
|
||||||
|
280` and `101` only; everything else falls through to `_ =>`. After a DXF round
|
||||||
|
trip these fields reset to defaults:
|
||||||
|
|
||||||
|
- text style name (7)
|
||||||
|
- alignment point (11/21/31) and both alignments (72, 74)
|
||||||
|
- width factor (41) and oblique angle (51)
|
||||||
|
- attribute flags (70): invisible, constant, verify, preset
|
||||||
|
- text generation flags (71) and field length (73)
|
||||||
|
- normal (210/220/230) and the position-lock state
|
||||||
|
|
||||||
|
Tag, prompt, default value, insertion point, height and rotation survive.
|
||||||
|
Losing the attribute flags is the worst part: an invisible or constant
|
||||||
|
attribute becomes visible and editable after a DXF save.
|
||||||
|
|
||||||
|
**Evidence:** `audit_python_attribute_definition_lifecycle_over_real_ipc`
|
||||||
|
compares every writable field through both formats. DWG round-trips the full
|
||||||
|
state; the DXF digest is pinned to the defaults (see the `BLOCKER` comment on
|
||||||
|
`expect_edited_dxf`).
|
||||||
|
|
||||||
|
**Suggested fix:** add reader arms for the missing groups, using the same
|
||||||
|
conversions the writer applies (rotation and oblique angle are written in
|
||||||
|
degrees). `TEXT` and `ATTRIB` already read most of these groups and can share
|
||||||
|
the implementation.
|
||||||
|
|
||||||
|
## 2. Boolean group codes are read with `as_i16()` and never applied
|
||||||
|
|
||||||
|
**Where:** `src/io/dxf/reader/stream_reader.rs` defines
|
||||||
|
`DxfCodePair::as_i16()` as `Some` only for `CodePairValue::Int`. Groups 290-299
|
||||||
|
are typed `Bool`, so `as_i16()` returns `None` for them and
|
||||||
|
`unwrap_or(0) != 0` yields `false`. The pattern appears in many arms of
|
||||||
|
`section_reader.rs`.
|
||||||
|
|
||||||
|
**Confirmed impact (round-trip tested):**
|
||||||
|
|
||||||
|
- `HELIX` group 290 (`handedness`): a clockwise helix reopens counter-clockwise.
|
||||||
|
The reader arm is `290 => { if let Some(v) = pair.as_i16() { ... } }`
|
||||||
|
(around line 12796).
|
||||||
|
- `LIGHT` groups 291, 292, 293 (`plot_glyph`, `use_attenuation_limits`,
|
||||||
|
`cast_shadows`; around lines 18154-18182), and 290 for the photometric web
|
||||||
|
file flag: `cast_shadows` reopens `false`.
|
||||||
|
|
||||||
|
**Same pattern, not individually tested** (line numbers in `section_reader.rs`):
|
||||||
|
13833, 13955-13969 (point-cloud style flags); 18194 (`has_web_file`);
|
||||||
|
18431-18438 and 18493-18494 (sweep, loft and revolve option flags); and several
|
||||||
|
`if let Some(v) = pair.as_i16()` arms on 290/292 near lines 9815, 10096, 10478
|
||||||
|
and 12861. Some other arms already use `as_bool()` correctly (for example lines
|
||||||
|
18376 and 18550), so the fix is mechanical.
|
||||||
|
|
||||||
|
**Evidence:** `audit_python_helix_lifecycle_over_real_ipc` (canary
|
||||||
|
`expect_edited_dxf`) and `audit_python_light_lifecycle_over_real_ipc`.
|
||||||
|
|
||||||
|
**Suggested fix:** read these groups with a helper that accepts either
|
||||||
|
representation, for example
|
||||||
|
`pair.as_bool().or_else(|| pair.as_i16().map(|v| v != 0))`, and audit every arm
|
||||||
|
whose code is in 290-299. Alternatively make `as_i16()` accept `Bool` values.
|
||||||
|
|
||||||
|
## 3. `UNDERLAY` rotation is written in degrees and read back unconverted
|
||||||
|
|
||||||
|
**Where:** `write_underlay` writes group 50 with `underlay.rotation.to_degrees()`
|
||||||
|
(around line 11038 of `writer/section_writer.rs`). `read_underlay` stores the
|
||||||
|
raw value: `50 => { if let Some(v) = pair.as_double() { underlay.rotation = v; } }`
|
||||||
|
(`reader/section_reader.rs`, around line 19470), with no `to_radians()`.
|
||||||
|
|
||||||
|
**What happens:** a rotation of `0.5` rad is written as 28.6479 degrees and
|
||||||
|
read back as 28.6479 rad. Because the writer converts again on every save, the
|
||||||
|
error compounds: a second save-and-reopen yields 1641.4. This silently corrupts
|
||||||
|
existing drawings each time they pass through cadcodec.
|
||||||
|
|
||||||
|
**Evidence:** `audit_python_underlay_lifecycle_over_real_ipc`; the canary
|
||||||
|
`expect_edited_dxf` / `expect_reedited_dxf` records 28.6 then 1641.4.
|
||||||
|
|
||||||
|
**Suggested fix:** `underlay.rotation = v.to_radians()` in the reader. Check
|
||||||
|
that `DGN`/`DWF`/`PDF` underlays share the code path.
|
||||||
|
|
||||||
|
## 4. `LEADER`: annotation link and vectors are lost in DXF
|
||||||
|
|
||||||
|
**a. The writer never emits group 340.** `write_leader` writes 3, 71-76, 10, 210,
|
||||||
|
211, 212 and 213 but no associated-annotation handle, while the reader has a
|
||||||
|
`340 =>` arm that fills `annotation_handle` (around line 16619). A DXF save
|
||||||
|
therefore unlinks every leader from its text, tolerance or block annotation.
|
||||||
|
|
||||||
|
**b. The coordinate mapping does not reassemble 211, 212 and 213.**
|
||||||
|
`GroupCodeValueType::coordinate_axis` in `src/io/dxf/group_code_value.rs` maps
|
||||||
|
X to `10..=18 | 110..=112 | 210 | 1010..=1013` (and the Y/Z equivalents), so
|
||||||
|
`add_coordinate` ignores the 211/221/231, 212/222/232 and 213/223/233 series.
|
||||||
|
`read_leader` uses a `PointReader` for `horizontal_direction`, `block_offset`
|
||||||
|
and `annotation_offset`, so all three reopen as their defaults even though the
|
||||||
|
writer emits them. (`normal`, group 210, works.)
|
||||||
|
|
||||||
|
**c. `override_color` is not persisted** in DXF or DWG: a leader coloured by
|
||||||
|
`override_color` reopens `ByLayer`. Observed, cause not traced.
|
||||||
|
|
||||||
|
**Evidence:** the canaries in `staged_python_leader_lifecycle_over_real_ipc`
|
||||||
|
(search for `BLOCKER`). DWG keeps the annotation link, offset and arrow flag.
|
||||||
|
|
||||||
|
**Suggested fix:** write group 340 for a non-null `annotation_handle`; extend
|
||||||
|
`coordinate_axis`/`coordinate_group` to cover the 211-213 series (or read those
|
||||||
|
groups explicitly); decide where the override colour belongs (group 62/420 on
|
||||||
|
the leader).
|
||||||
|
|
||||||
|
## 5. `DRAWINGVIEW` and `SECTIONLINE` are dispatched only inside blocks
|
||||||
|
|
||||||
|
**Where:** `section_reader.rs` has two entity dispatch tables: one for block
|
||||||
|
contents (around lines 3241-3390) and one for the ENTITIES section
|
||||||
|
(`read_entities`, from line 3482). `"DRAWINGVIEW"` (line 3386) and
|
||||||
|
`"SECTIONLINE"` (line 3382) appear only in the first; the ENTITIES table has no
|
||||||
|
arm for them. `write_view_border_dxf` writes `DRAWINGVIEW` correctly.
|
||||||
|
|
||||||
|
**What happens:** a `ViewBorder` saved to DXF in the drawing's entity list
|
||||||
|
reopens as a different, opaque entity kind instead of `ViewBorder`. DWG restores
|
||||||
|
the typed record. The same applies to `SectionSymbol`.
|
||||||
|
|
||||||
|
**Evidence:** `audit_python_view_border_lifecycle_over_real_ipc` (canary
|
||||||
|
`expect_edited_dxf: "wrong kind"`) and `audit_python_section_symbol_lifecycle_over_real_ipc`
|
||||||
|
(canary `wrong kind Unknown`).
|
||||||
|
|
||||||
|
**Suggested fix:** add the two arms to the ENTITIES dispatch, calling
|
||||||
|
`read_view_border_dxf` and `read_section_symbol_dxf`.
|
||||||
|
|
||||||
|
## 6. `TABLE` `merged_ranges` is empty after a DXF reopen
|
||||||
|
|
||||||
|
**What happens:** the writer emits the merged-range list (`AcDbFormattedTableData`,
|
||||||
|
group 90 then 91-94 per range; near line 10216 of `writer/section_writer.rs`),
|
||||||
|
and `reader/section_reader/table_content.rs` (around lines 627-690) appears to
|
||||||
|
parse it, yet `Table::merged_ranges` is empty after a DXF reopen. The merge
|
||||||
|
itself survives through the origin cell's `merge_width` and `merge_height`
|
||||||
|
(groups 175 and 176), and DWG restores `merged_ranges` but not the per-cell
|
||||||
|
dimensions.
|
||||||
|
|
||||||
|
**Impact:** low, because the merge is preserved in the cell fields; consumers
|
||||||
|
that read `merged_ranges` directly see nothing. Cause not traced; it may be that
|
||||||
|
the entity path does not call the table-content parser.
|
||||||
|
|
||||||
|
**Evidence:** `staged_python_table_lifecycle_over_real_ipc` (the DXF branch
|
||||||
|
asserts an empty `merged_ranges` and marks it as a blocker).
|
||||||
|
|
||||||
|
**Suggested fix:** rebuild `merged_ranges` from the cell merge dimensions after
|
||||||
|
reading, or make sure the `AcDbFormattedTableData` block is parsed for entities.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Observed but not filed
|
||||||
|
|
||||||
|
These are format constraints or OCS-side issues, not reader bugs:
|
||||||
|
|
||||||
|
- **DWG R2010+ does not store** a leader's `text_height`, `text_width` or
|
||||||
|
`hookline_enabled`, or a 3-D polyline's `elevation`; the writer stores them
|
||||||
|
only for the older versions that define them.
|
||||||
|
- **Entity-level `MultiLeader.text_height`** is not stored by either writer
|
||||||
|
(`context.text_height` is), so OCS exposes it read-only.
|
||||||
|
- **Legacy `Polyline` reopens as `Polyline3D`** from both formats and a 2-D
|
||||||
|
polyline reopens as `LwPolyline` from DXF. These look like deliberate
|
||||||
|
normalization; OCS made the legacy kind update-only and records the DXF
|
||||||
|
conversion.
|
||||||
|
- **Spline weights in DXF** were briefly suspected but are correct: the writer
|
||||||
|
emits group 41 only when `flags.rational` is set, so the host must set that
|
||||||
|
flag when weights are present (fixed in OCS).
|
||||||
|
|
||||||
|
### Text and dimension style findings (2026-09-21)
|
||||||
|
|
||||||
|
Found by `audit_python_text_and_dim_styles_over_real_ipc`; each is pinned by a canary. The first
|
||||||
|
three are fixed in [HakanSeven12/cadcodec#51](https://github.com/HakanSeven12/cadcodec/pull/51)
|
||||||
|
(independent of #48); the last two are not filed, because fixing them needs the XDATA layout
|
||||||
|
AutoCAD expects and that cannot be checked here.
|
||||||
|
|
||||||
|
- **`STYLE` generation flags:** the DXF writer hard-codes group 71 to 0, so a text
|
||||||
|
style's `flags.backward` and `flags.upside_down` are lost on every DXF save (DWG keeps them).
|
||||||
|
- **`STYLE` oblique angle units:** group 50 is written and read as the raw radian value, while DXF
|
||||||
|
defines it in degrees; it round-trips inside cadcodec but AutoCAD would read 15 degrees as 0.26.
|
||||||
|
DWG stores radians correctly.
|
||||||
|
- **`DIMSTYLE` text style name:** the DXF reader keeps only the text-style handle (group 340) and never
|
||||||
|
resolves `dimtxsty` from it, so the name reopens as `Standard` (the handle is right; DWG resolves both).
|
||||||
|
- **`TextStyle::true_type_font`** is never written or read by either codec, so it lives only in memory.
|
||||||
|
- **`BLOCK_RECORD` description:** the DXF codec does not carry `BlockRecord::description`
|
||||||
|
(found by `audit_python_blocks_over_real_ipc`, pinned by a canary); DWG keeps it. Not filed, for
|
||||||
|
the same reason as `true_type_font`.
|
||||||
|
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
# Scripting ACIS bodies through cadkernel: findings and plan
|
||||||
|
|
||||||
|
Investigation of the blocker on **Solid3D, Body, Region and Surface**
|
||||||
|
(`docs/plugin-host-model-coverage-ledger.md`). The blocker said a script can
|
||||||
|
neither produce a valid ACIS payload nor edit one, and that the handover
|
||||||
|
forbids rewriting an opaque payload without a proven lossless path. This note
|
||||||
|
records what OCS's own kernel path can already do, measured with two spike tests
|
||||||
|
(`spike_kernel_body_round_trip`, `spike_kernel_timings` in
|
||||||
|
`src/app/plugin_host.rs`, both `#[ignore]` because they are slow in a debug
|
||||||
|
build). Measured on cadcodec `5b682ed` / cadkernel `6f046af`, debug build.
|
||||||
|
|
||||||
|
**Conclusion:** the blocker was overstated. OCS already owns a kernel-backed
|
||||||
|
create/transform/boolean pipeline whose output is verified lossless before it is
|
||||||
|
accepted. The missing piece is not geometry but an *operation channel* from a
|
||||||
|
script to that pipeline. Solid3D and Body are then straightforward; Region and
|
||||||
|
Surface need a little more; the one real cost is boolean speed.
|
||||||
|
|
||||||
|
## What exists
|
||||||
|
|
||||||
|
| Capability | Where | Notes |
|
||||||
|
|---|---|---|
|
||||||
|
| Primitives: box, wedge, cylinder, cone/frustum, elliptical cylinder, sphere, torus, pyramid, pyramid frustum | `scene/model/solid_model.rs` (`box_solid`, ...) | return a kernel `Body` |
|
||||||
|
| Transforms: place, turn about an axis, mirror, column-major 4x4 | `placed`, `turned`, `mirrored`, `by_matrix` | analytic surfaces move with their frames, no point rewriting |
|
||||||
|
| Booleans: union, subtract, intersect | `boolean_result` | refuses with a reason instead of returning a broken solid |
|
||||||
|
| Body to entity payload | `acis_export::solid_to_sat` | **self-verifying**: it lifts its own SAT text and SAB binary back and returns `None` unless both are lossless (`loss.is_empty()`) and validate |
|
||||||
|
| Entity payload to body | `solid3d_tess::kernel_body` / `kernel_region_body` / `kernel_surface_body` / `kernel_acis_body` | returns `None` when the lift is lossy or has more than one body |
|
||||||
|
| Regenerating derived data | `app/model_ops.rs::entity_with_boolean_body` | rewrites `acis_data`, `wires`, clears `silhouettes` and `history_handle` for Solid3D, Region and Surface |
|
||||||
|
| Volume, extent, edge wires | `volume`, `extent`, `edge_wires` | used as oracles below |
|
||||||
|
|
||||||
|
`kernel_acis_body` is exactly the "proven lossless path" the handover asked for:
|
||||||
|
a payload is edited only if it lifts with no loss, otherwise it is left alone.
|
||||||
|
|
||||||
|
## Spike results
|
||||||
|
|
||||||
|
Everything below passed, with the kernel's own volume as the oracle.
|
||||||
|
|
||||||
|
| Test | Result |
|
||||||
|
|---|---|
|
||||||
|
| Box 10x6x4 to Solid3D | volume 240, 12 edge wires, lifts back |
|
||||||
|
| DWG save/reopen | lifts back, volume 240, 12 wires kept. `acis_data` changes from SAT text to **SAB binary** (same solid, different bytes) |
|
||||||
|
| DXF save/reopen | lifts back, volume 240. Cached `wires` are dropped (0) and are regenerated on demand; silhouettes were already empty |
|
||||||
|
| Translate by (5,5,5) | volume 240, extent shifted exactly, lifts back |
|
||||||
|
| Rotate 45 degrees about Z | volume 240, extent -5.657..5.657, lifts back |
|
||||||
|
| Mirror in X | volume 240, lifts back |
|
||||||
|
| Box union cylinder | volume 315.277, 16 wires, lifts back |
|
||||||
|
| Box subtract cylinder | volume 189.815, 14 wires, lifts back |
|
||||||
|
| Box intersect cylinder | volume 50.185, 2 wires, lifts back |
|
||||||
|
| Sphere, torus, wedge, pyramid | volumes 112.696, 98.415, 12.000, 28.532; all lift back |
|
||||||
|
| Same payload in a `Body` entity | lifts back; still lifts back after DWG and after DXF |
|
||||||
|
|
||||||
|
Timings (debug build): primitive, transform, `solid_to_sat` and `edge_wires` are
|
||||||
|
effectively instant (under 0.05 s). **Each boolean took about 23 s**, most likely
|
||||||
|
a debug-build artifact for a kernel doing heavy numeric work, but it has not been
|
||||||
|
measured in release and must be before booleans are exposed.
|
||||||
|
|
||||||
|
Two things to understand about "lossless":
|
||||||
|
|
||||||
|
- DWG rewrites SAT text as SAB binary. The solid is identical (same volume,
|
||||||
|
topology, faces) but the bytes are not, so the honest oracle is "lifts back with
|
||||||
|
no loss and the same volume", not byte equality. An untouched body that a
|
||||||
|
script never edits is written exactly as OCS writes any other body.
|
||||||
|
- DXF does not carry the cached wires; they are derived data.
|
||||||
|
|
||||||
|
## Design
|
||||||
|
|
||||||
|
The obstacle is the channel. The generic entity path moves an acadrust
|
||||||
|
`EntityType` from the plugin to the host; the plugin has no kernel and must never
|
||||||
|
see or rewrite ACIS bytes. Three ways to give a script the operations:
|
||||||
|
|
||||||
|
**A. Host-side normalization with a request carrier (no ABI change).** A
|
||||||
|
hand-written converter (as for Dimension) turns `create_entity('Solid3D',
|
||||||
|
primitive='box', ...)` into a Solid3D that carries the request in an otherwise
|
||||||
|
unused field, and the host's `normalize_scripted_entity` replaces it with the real
|
||||||
|
payload, exactly as it already does for MLine geometry, Helix splines and image
|
||||||
|
definitions. It works inside today's v7 protocol, but the carrier field is a hack.
|
||||||
|
|
||||||
|
**B. New host operation (recommended).** Add one additive operation to `HostApi`
|
||||||
|
and the v4 IPC protocol, for example `solid_operation(op) -> Result<Handle, String>`,
|
||||||
|
with `op` one of: create primitive, transform, boolean, and (later) region from
|
||||||
|
curves. The host runs it through the pipeline above inside an undo step and
|
||||||
|
returns the new or updated handle. Because it is a new method with a default
|
||||||
|
"unsupported" implementation it is backward compatible; bump the minor/negotiate
|
||||||
|
by capability rather than the major version. Python side:
|
||||||
|
|
||||||
|
```python
|
||||||
|
box = doc.solids.box(center=(0, 0, 0), size=(10, 6, 4))
|
||||||
|
cyl = doc.solids.cylinder(base=(0, 0, -3), radius=2, height=10)
|
||||||
|
hole = box.subtract(cyl) # new Solid3D; operands untouched
|
||||||
|
box.transform(translate=(5, 5, 5)) # in-place, transactional, undoable
|
||||||
|
```
|
||||||
|
|
||||||
|
**C. Do nothing but layer edits** (the current state).
|
||||||
|
|
||||||
|
Recommended: **B**, with `solid_operation` covering create, transform and boolean.
|
||||||
|
Every operation goes through `solid_to_sat` (self-verifying) and the kernel's own
|
||||||
|
refusal path, so a failure is an error before any mutation, and an untouched
|
||||||
|
payload is never rewritten. In-place edits of an existing entity are gated by
|
||||||
|
`kernel_acis_body` returning `Some`: a payload the kernel cannot lift losslessly
|
||||||
|
is refused with a clear message instead of being rewritten.
|
||||||
|
|
||||||
|
## Per-kind feasibility
|
||||||
|
|
||||||
|
| Kind | Create | Edit | Notes |
|
||||||
|
|---|---|---|---|
|
||||||
|
| **Solid3D** | 9 primitives, boolean of two solids | transform, boolean | Straightforward. Regenerate `wires`; clear `silhouettes`; `history_handle` is cleared by `entity_with_boolean_body`, so a history-carrying solid needs a decision (refuse, or accept losing parametric history). |
|
||||||
|
| **Body** | same payload container | transform | Same pipeline, `kernel_acis_body` works on a `Body` payload (spike). A true non-solid (sheet or wire) body may not lift; those stay layer-only. |
|
||||||
|
| **Region** | from closed curve entities (the REGION command's `add_region_model`) | transform | Needs a "region from these curve handles" operation and planar-face construction. |
|
||||||
|
| **Surface** | plane, extruded, revolved from a profile | transform | The most involved: surface kinds carry `surface_data` besides `acis_data`, and only `Plane` keeps its kind on regeneration (`SurfaceKind::Generic` otherwise). |
|
||||||
|
|
||||||
|
## Risks and open questions
|
||||||
|
|
||||||
|
1. **Boolean speed.** Measured in release, see "Boolean timings" below: about
|
||||||
|
1 to 2.2 s for a box and a cylinder, 0.2 s for two spheres and 1 to 2 ms for
|
||||||
|
planar-only operands, against 23 s in a debug build. The kernel also refuses
|
||||||
|
many curved cases, which matters more than speed.
|
||||||
|
2. **Interoperability cannot be verified here.** `solid_to_sat` is verified by
|
||||||
|
OCS's own lifter. Whether AutoCAD accepts the SAT/SAB that OCS writes is not
|
||||||
|
testable without AutoCAD, so completion should be scoped as "OCS round trip",
|
||||||
|
as for RasterImage.
|
||||||
|
3. **Parametric history.** Regenerating a payload clears `history_handle`.
|
||||||
|
4. **Frames.** Some solids carry a body-to-world transform in the SAT
|
||||||
|
(`body_transform` in `kernel_acis_body`); the lift already applies it, and the
|
||||||
|
spike's translated/rotated bodies confirm it, but a foreign DWG with a
|
||||||
|
scaled or sheared body transform should be added as a fixture.
|
||||||
|
5. **API surface.** `solid_operation` is a protocol addition; decide whether it is
|
||||||
|
one generic operation enum or separate methods before starting.
|
||||||
|
|
||||||
|
## Suggested phases
|
||||||
|
|
||||||
|
1. `solid_operation` protocol and host executor for **create primitive** and
|
||||||
|
**transform** on Solid3D, with the full lifecycle test through the real runner
|
||||||
|
(volume oracle, DWG and DXF reopen, undo, refusal of a lossy payload).
|
||||||
|
2. **Booleans** (after release-build timing) and the **Body** container.
|
||||||
|
3. **Region** from curve handles.
|
||||||
|
4. **Surface** (plane first).
|
||||||
|
|
||||||
|
Phase 1 alone would move Solid3D from blocked to complete-in-OCS.
|
||||||
|
|
||||||
|
**Status (2026-09-20): phase 1 is done.** `HostApi::solid_operation` (create primitive and rigid transform), the `doc.solids` Python API and `audit_python_solid3d_lifecycle_over_real_ipc` are in; Solid3D is complete, Body moves through the same channel. Design B was implemented as recommended. Region creation from a closed profile followed (`RegionFromProfile`). Plane surfaces and extrusions (`SurfaceFromProfile`, `Extrude`) followed. Only booleans remain, plus lofted, revolved, swept and NURBS surfaces.
|
||||||
|
|
||||||
|
## Boolean timings (release build)
|
||||||
|
|
||||||
|
Measured 2026-09-20 in a scratch crate built with `--release` (opt-level 3)
|
||||||
|
against the same cadkernel revision OCS pins (`6f046af`, features `acis` and
|
||||||
|
`offset`), calling exactly what OCS's `solid_model::boolean_result` calls:
|
||||||
|
`brep::operation_tolerance` then `brep::combine`. A debug build of OCS is about
|
||||||
|
22 times slower, so booleans must never be exercised in a debug test run. The
|
||||||
|
scratch program is not in the repository; to repeat it, depend on cadkernel at
|
||||||
|
that revision and time `brep::combine` on `brep::make::{cuboid, cylinder,
|
||||||
|
sphere, torus}` operands.
|
||||||
|
|
||||||
|
| Operation | Time | Result |
|
||||||
|
|---|---|---|
|
||||||
|
| box union / subtract / intersect cylinder (10x6x4 box, r=2 cylinder) | 1.05 to 1.08 s each, identical on repeat runs | ok |
|
||||||
|
| same, operands scaled 10x and 100x | 2.21 s and 2.21 s | ok |
|
||||||
|
| box union / subtract box (planar only) | 0.001 to 0.002 s | ok |
|
||||||
|
| sphere union sphere (overlapping) | 0.22 s | ok |
|
||||||
|
| sphere subtract sphere (overlapping) | 0.23 s | refused `CutRefused` |
|
||||||
|
| box subtract sphere (sphere cutting the box faces) | 1.28 s | refused `Coincident` |
|
||||||
|
| sphere union torus (disjoint) | under 1 ms | refused `NoClosedForm` |
|
||||||
|
| torus subtract cylinder through the ring | under 1 ms | refused `NoClosedForm` |
|
||||||
|
| drill a first cylinder hole in a box | 0.03 s | ok |
|
||||||
|
| drill a second hole in the drilled box | under 1 ms | refused `CutRefused` |
|
||||||
|
|
||||||
|
What this means:
|
||||||
|
|
||||||
|
- **Speed is acceptable.** A curved boolean costs 0.2 to 2.2 s, the same cost as
|
||||||
|
the GUI BOOLEAN command, and planar work is instant. The 23 s seen earlier was
|
||||||
|
a debug-build artifact.
|
||||||
|
- **It blocks the host thread.** The plugin's `PY_RUN` is a synchronous dispatch
|
||||||
|
and nested host requests run inline, so a script freezes the UI while a
|
||||||
|
boolean runs. One to two seconds per operation is tolerable; a script with
|
||||||
|
dozens is not.
|
||||||
|
- **The whole script has a budget.** A `Dispatch` call uses the 30 s default
|
||||||
|
timeout (`OCS_PLUGIN_CALL_TIMEOUT_SECS`, with a 10 s floor), and nested host
|
||||||
|
work counts against one deadline. Roughly fifteen curved booleans in a single
|
||||||
|
script would exceed it.
|
||||||
|
- **Refusals are the real limit.** The kernel says no often: coincident faces, a
|
||||||
|
cut it has no closed form for, torus operands, and, surprisingly, a second
|
||||||
|
cut in a body that was already drilled. Refusals are fast and leave the inputs
|
||||||
|
intact, which is the behavior the API already relies on, but it means booleans
|
||||||
|
will be a partial feature that fails with a reason, not a general one.
|
||||||
|
- **Timing is not proportional to size.** Scaling the operands 10x doubled the
|
||||||
|
time, 100x changed nothing more, so the cost is dominated by the surface
|
||||||
|
intersection setup rather than the geometry size.
|
||||||
|
|
||||||
|
### Recommendation
|
||||||
|
|
||||||
|
Add `SolidOperation::Boolean { first, second, operation, layer }` and run it
|
||||||
|
synchronously on the host thread, surfacing the kernel's refusal (`Coincident`,
|
||||||
|
`CutRefused`, `NoClosedForm`, ...) verbatim in the error and leaving both
|
||||||
|
operands untouched on failure. Build the result with the existing
|
||||||
|
`entity_with_boolean_body` path so it inherits the lossless verification.
|
||||||
|
Test it with **planar** operands (millisecond cost, safe in debug) plus one
|
||||||
|
`#[ignore]` curved case that documents the release-only runtime. Document the
|
||||||
|
30 s script budget and that chained cuts on a drilled body are often refused.
|
||||||
|
Do not move booleans to a background thread yet: it would need cancellation and
|
||||||
|
undo coordination for a cost that is one to two seconds.
|
||||||
|
|
||||||
|
**Status (2026-09-20): implemented.** `SolidOperation::Boolean` and `doc.solids.union`, `subtract` and `intersect` follow the recommendation above, with planar-operand lifecycle testing and an ignored curved refusal test. Every operation this note proposed is now built.
|
||||||
@@ -9,12 +9,12 @@ with Open CAD Studio. The model follows [QGIS](https://plugins.qgis.org/)-style
|
|||||||
extensibility: a small metadata file, a single entry point, an optional separate
|
extensibility: a small metadata file, a single entry point, an optional separate
|
||||||
engine crate, and user-installable packages from a curated index.
|
engine crate, and user-installable packages from a curated index.
|
||||||
|
|
||||||
> **Open CAD Studio ships no built-in plugins.** Every add-on is an **external
|
> Plugins are **out-of-process dynamic libraries** (`cdylib`). The host loads
|
||||||
> dynamic library** (`cdylib`) the host loads at runtime from the user plugins
|
> first-party packages from its application resources and third-party packages
|
||||||
> folder. The host source only contains the generic plugin *runtime*
|
> from the user plugins folder. Both use the generic runtime
|
||||||
> (`src/plugin/`, `src/app/plugin_host.rs`) and the stable contract crate
|
> (`src/plugin/`, `src/app/plugin_host.rs`) and the stable contract crate
|
||||||
> (`crates/ocs_plugin_api`). Add-ons live in their own repositories and
|
> (`crates/ocs_plugin_api`). A user package with the same id explicitly
|
||||||
> **consume** that contract.
|
> overrides a bundled package.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -24,7 +24,7 @@ engine crate, and user-installable packages from a curated index.
|
|||||||
|------|-----------|
|
|------|-----------|
|
||||||
| **One package, one entry point** | Manifest, ribbon tab and commands ship together in the plugin crate; no edits to the host. |
|
| **One package, one entry point** | Manifest, ribbon tab and commands ship together in the plugin crate; no edits to the host. |
|
||||||
| **Stable contract** | Authors target the semver-versioned `ocs_plugin_api` crate, not `OpenCADStudio` internals. |
|
| **Stable contract** | Authors target the semver-versioned `ocs_plugin_api` crate, not `OpenCADStudio` internals. |
|
||||||
| **Out-of-tree by default** | A plugin is its own repo + crate; the host never recompiles to gain one. |
|
| **Out-of-tree by default** | Third-party plugins remain independent; selected first-party plugins may build and ship with OCS. |
|
||||||
| **DWG round-trip** | Domain data lives on entities as XDATA, not in an opaque side database. |
|
| **DWG round-trip** | Domain data lives on entities as XDATA, not in an opaque side database. |
|
||||||
| **Engine reuse** | A headless `std`-only engine crate can run in WASM/CLI without the CAD host. |
|
| **Engine reuse** | A headless `std`-only engine crate can run in WASM/CLI without the CAD host. |
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,341 @@
|
|||||||
|
# OCS canvas entity completion plan
|
||||||
|
|
||||||
|
## Goal and current state
|
||||||
|
|
||||||
|
Build a general Python document model over the OCS host API so a script can control OCS: read and change every canvas entity, manage the drawing's tables, and run OCS's own commands. Keep a property-level record of read/write, read-only, snapshot-only, and unsupported fields in the [43-kind coverage ledger](plugin-host-model-coverage-ledger.md). The architecture and guarantees are in [plugin-host-model.md](plugin-host-model.md); the progress log at the end of this file records each increment with its evidence. Do not resume the separate Lisp-to-Python conversion work.
|
||||||
|
|
||||||
|
**State as of 21 September 2026.** The feature is host API v7. An earlier draft pull request, [#1391](https://github.com/HakanSeven12/OpenCADStudio/pull/1391), covered the first slice of it and was closed in favour of this more complete change.
|
||||||
|
|
||||||
|
- **Entities:** explicit writes for all 43 canvas kinds (41 creatable; the legacy `Polyline` and `Body` are update-only). **31 kinds are `Complete`** (every C/R/E/D/U/I/W/V/P gate passes). The remaining kinds are integration-tested and held short of `Complete` by a named blocker in the ledger: seven by cadcodec DXF bugs (fixes submitted as [cadcodec#48](https://github.com/HakanSeven12/cadcodec/pull/48), not yet merged, so OCS still pins the unfixed revision), Polyline3D by the DWG format, Polyline2D by a kind change on DXF save, RasterImage by an image-reactor structure that cannot be verified, and Body by having no creation path.
|
||||||
|
- **Drawing tables:** layers, text and dimension styles, blocks and their contents, linetypes and layouts, through the additive `TableOperation` request (see the log entries dated 2026-09-21).
|
||||||
|
- **Commands:** `HostApi::run_command` drives the real OCS commands step by step; `doc.command`, `doc.start_command` and `doc.modify` build on it.
|
||||||
|
- **Known open items:** the unfiled cadcodec findings (`cadcodec-reader-gaps.md`), complex (text and shape) linetypes, plot devices and named page setups, and PEDIT's remaining options.
|
||||||
|
|
||||||
|
Repositories:
|
||||||
|
|
||||||
|
- Bundled Python adapter: `plugins/opencad-python`
|
||||||
|
- Host coverage policy: `crates/ocs_plugin_api/entity_coverage_policy.json`
|
||||||
|
- Host coverage/validation: `crates/ocs_plugin_api/src/entity_coverage.rs` and `build.rs`
|
||||||
|
- Adapter mapping: `plugins/opencad-python/entity_manifest.json`,
|
||||||
|
`plugins/opencad-python/build/generate.rs`,
|
||||||
|
`plugins/opencad-python/src/ocs_module.rs`, and
|
||||||
|
`plugins/opencad-python/src/document_model.py`
|
||||||
|
- Host design notes: `docs/plugin-host-model.md`
|
||||||
|
|
||||||
|
Host and adapter changes live in the same repository and are committed together.
|
||||||
|
|
||||||
|
## First: complete the originally agreed Phase 8
|
||||||
|
|
||||||
|
The earlier Phase 8 was **integration and compatibility**, not a new entity kind. `Insert` was added afterward as a separate coverage increment. Before marking any kind complete, establish an executable integration harness that exercises the actual plugin runner and IPC, not only direct Rust conversion helpers:
|
||||||
|
|
||||||
|
1. Stage the in-tree v7 plugin with `bash plugins/opencad-python/tools/stage-bundled.sh <stage directory> [--debug]`. Verify the staged `plugin.toml` says API v7 and its acadrust source and Rust compiler match OCS. Keep the repository-relative `ocs_plugin_api` path; never check in a machine-local path.
|
||||||
|
2. Through real IPC, create, inspect, edit, and delete a representative entity. Verify an invalid multi-entity transaction changes nothing, a valid transaction produces one undo entry, and undo **and redo** restore the expected geometry and references.
|
||||||
|
3. In the running GUI, exercise a real point pick, entity pick, cancellation/Escape, and plugin command cancellation. Verify drawing/selection/command notifications, including overflow recovery.
|
||||||
|
4. Repeat an input request and event poll across two tabs; verify token and notification isolation and cleanup when a tab closes.
|
||||||
|
5. Save and reopen representative edits as **DWG and DXF**, verifying the actual geometry and preserved unmapped fields. Use a real viewport/canvas check where the entity has visible geometry; a converter round trip alone does not satisfy this.
|
||||||
|
6. Record platform, OCS/acadrust revisions, fixture files, commands, results, and any engine limitation. Keep repeatable tests in the relevant repositories.
|
||||||
|
|
||||||
|
Phase 8 is complete only when these checks pass through the bundled plugin and
|
||||||
|
real runner boundary. If a test is blocked by OCS or acadrust behavior, record
|
||||||
|
the specific failure and leave Phase 8 open.
|
||||||
|
|
||||||
|
## Per-kind completion gate
|
||||||
|
|
||||||
|
Use one checklist row per kind in a coverage ledger. Status values: `unstarted`, `mapped`, `integration-tested`, `complete`, or `blocked`; record the blocking dependency. **Do not use “complete” for read-only, update-only, or layer-only support.** For every kind:
|
||||||
|
|
||||||
|
1. **Declare coverage:** Every traced field has an accurate catalog status and validation rule. Distinguish ordinary properties from handles, owners, linked records, external assets, and opaque payloads. Snapshot-only fields remain explicitly unmapped. Assert adapter keys match the host catalog.
|
||||||
|
2. **Create:** A Python script creates a valid entity through the document model in a real document with required tables, styles, definitions, files, and references. Missing or invalid required inputs fail before mutation. Add document-model creation/deletion methods if needed; current `doc.entities` only indexes and iterates, while low-level `ocs.add`/remove APIs exist.
|
||||||
|
3. **Read and edit:** After creation, read the entity by handle through `doc.entities`; edit at least one defining geometry or placement field and one other meaningful writable field inside `doc.transaction`. Verify that all unmentioned fields, handles, ownership, attached records, and XDATA remain unchanged. Check invalid values and forbidden reference edits fail atomically.
|
||||||
|
4. **Delete and history:** Delete the created entity through the Python interface. Prove create, edit, and delete have defined undo/redo behavior in the host, including grouped writes and failure rollback. Record any transaction API extension and bump the host API version if its ABI changes; keep older plugin compatibility.
|
||||||
|
5. **Real IPC and canvas:** Run the above through the staged plugin and actual OCS IPC. Verify visibility/geometry in the canvas and selection or picking in the GUI. For nonvisual entities, verify their observable document or layout behavior and explain the oracle.
|
||||||
|
6. **Persistence:** Save/reopen DWG **and** DXF fixtures. Compare kind, geometry, important metadata, handles/references, and preserved fields after reopen; edit again after reopen. Test at least one valid edge case for that kind. Do not count a JSON or in-memory round trip as file persistence.
|
||||||
|
7. **Packaged build:** Run the in-tree adapter tests with `--locked`, stage the
|
||||||
|
plugin with `stage-bundled.sh`, and load it from the macOS application
|
||||||
|
resources through the separate runner process. The staged manifest must
|
||||||
|
match the host's Rust compiler and acadrust source.
|
||||||
|
|
||||||
|
If OCS/acadrust cannot create or serialize a kind reliably, mark it **blocked**, add a regression test or fixture demonstrating the failure, and move to the next independent kind. An explicit unsupported status is honest progress, not completion.
|
||||||
|
|
||||||
|
## Existing mapped kinds: audit before claiming completion
|
||||||
|
|
||||||
|
Audit these against the same gate: `Point`, `Line`, `Circle`, `Arc`, `Ellipse`, `Polyline`, `Polyline2D`, `Polyline3D`, `LwPolyline`, `Spline`, `Text`, `MText`, `Ray`, `XLine`, `Solid`, `Face3D`, `Insert`. `Insert` currently has transform edits but **no Python creation**; its block name is read-only and attached attributes are snapshot-only. Earlier tests include some direct DWG round trips, but there is no evidence that every mapped kind passes real IPC, GUI, deletion, undo/redo, and both file formats. Mark each independently after testing.
|
||||||
|
|
||||||
|
## Ordered 26-kind expansion queue
|
||||||
|
|
||||||
|
The order below groups shared implementation work. Complete a kind only through the gate above. Within a group, move past a blocked kind after recording the exact dependency. “Minimum exercise” identifies a real entity-specific create/edit/delete case; it does not make other fields automatically writable.
|
||||||
|
|
||||||
|
| # | Kind | Minimum entity-specific exercise and dependency |
|
||||||
|
|---:|---|---|
|
||||||
|
| 1 | Tolerance | Create a feature-control frame with text/style; move and edit its text/direction; check style reference and display. |
|
||||||
|
| 2 | Shape | Create with an installed SHX shape/style; change insertion, size, rotation; verify the named glyph and style survive reopen. |
|
||||||
|
| 3 | AttributeDefinition | Create in a block definition; edit tag, default text, and placement; verify the block’s definition and linked inserts. |
|
||||||
|
| 4 | AttributeEntity | Create as a block reference attribute; edit value and placement; verify parent `Insert`, handles, and sequence linkage. |
|
||||||
|
| 5 | Hatch | Create a closed-boundary solid hatch and a patterned hatch; edit boundary/pattern; verify fill and boundary validity. |
|
||||||
|
| 6 | Leader | Create with vertices and an annotation; edit path and annotation placement; preserve annotation handle. |
|
||||||
|
| 7 | MLine | Create against a valid MLine style; edit vertices and scale; verify style element offsets and joins. |
|
||||||
|
| 8 | Dimension | Create at least one supported dimension subtype with style and reference points; edit defining geometry and displayed measurement. Track subtype coverage separately. |
|
||||||
|
| 9 | MultiLeader | Create text and leader paths using a valid style; edit landing/vertices and text; preserve nested context and annotation links. |
|
||||||
|
| 10 | Table | Create rows, columns, style, and cells; edit size and one cell value; preserve merged ranges and block/style links. |
|
||||||
|
| 11 | PolygonMesh | Create a grid with defined M/N counts and vertices; edit a vertex and density; reject inconsistent counts. |
|
||||||
|
| 12 | PolyfaceMesh | Create vertices/faces; edit a vertex and face indices; reject invalid indices and preserve sequence records. |
|
||||||
|
| 13 | Mesh | Create vertices/faces/edges; edit one vertex and topology; reject out-of-range indices and verify rendered faces. |
|
||||||
|
| 14 | Helix | Create with axis, radius, turns, and height; edit a defining parameter and verify the derived curve plus embedded spline data. |
|
||||||
|
| 15 | RasterImage | Create with a resolvable image definition/file; edit placement, vectors, and clipping; verify display and definition handles. |
|
||||||
|
| 16 | Wipeout | Create with a valid clip polygon; edit boundary and placement; verify masking, clip mode, and image-definition links. |
|
||||||
|
| 17 | Underlay | Create with a valid PDF/DWF/DGN definition; edit transform and clipping; verify external resource and definition handle. |
|
||||||
|
| 18 | Viewport | Create in the appropriate layout; edit center/size/view target; verify visible viewport and frozen-layer/clip references. |
|
||||||
|
| 19 | ViewBorder | Create with its required view/scale references; edit border geometry; verify linked viewport/view records. |
|
||||||
|
| 20 | SectionSymbol | Create with view style and point records; edit endpoints/label; preserve view-representation links. |
|
||||||
|
| 21 | Light | Create a light with position/target; edit intensity and direction; verify color/photometric state and visible glyph. |
|
||||||
|
| 22 | Region | Create/import a valid region payload; transform/edit supported geometry, then verify ACIS payload after both file formats. |
|
||||||
|
| 23 | Body | Create/import a valid body payload; apply a supported transform/edit; verify ACIS and history/reference preservation. |
|
||||||
|
| 24 | Solid3D | Create/import a valid solid; edit a supported geometric operation; verify ACIS, topology, and history after reopen. |
|
||||||
|
| 25 | Surface | Create/import a valid surface; edit a supported parameter/transform; verify surface payload, isolines, and history. |
|
||||||
|
| 26 | Ole2Frame | Create with a valid embedded object payload; edit frame geometry; verify storage, aspect behavior, and persistence. |
|
||||||
|
|
||||||
|
The last five may require new engine capabilities rather than only Python converters. Do not deserialize and rewrite their opaque payloads unless lossless behavior is proven. If a listed kind has no meaningful safe Python creation/edit path, keep it marked blocked or partial and report why; do not relabel it complete to reach 43/43.
|
||||||
|
|
||||||
|
## Work pattern for each coding increment
|
||||||
|
|
||||||
|
1. Inspect the acadrust entity struct, constructors, private fields, serializer, drawing path, and linked tables/objects. Record the intended editable/read-only/unmapped properties first.
|
||||||
|
2. Put generic validation and transaction behavior in the host. Keep the Python adapter thin; add a manifest override only when the generator cannot safely express a field.
|
||||||
|
3. Add focused host validation, adapter conversion, document-model, real transaction/undo/redo, IPC, GUI, and DWG/DXF fixture checks. Record test evidence in the ledger, including which checks were manual.
|
||||||
|
4. Run `cargo test -p ocs_plugin_api --features host --lib` and the relevant
|
||||||
|
app host tests. Run
|
||||||
|
`cargo test --locked --features experimental-host-model --manifest-path plugins/opencad-python/Cargo.toml`
|
||||||
|
plus
|
||||||
|
`python3 -m unittest discover -s plugins/opencad-python/tests -v`.
|
||||||
|
5. Check `git diff --check` and repository status, commit host and adapter changes
|
||||||
|
together, and record the resulting commit and the next unfinished gate in the ledger.
|
||||||
|
|
||||||
|
## Phase 8 progress log
|
||||||
|
|
||||||
|
- Added a V4 local-socket nested-request test for `UpdateEntitiesTransaction` using a simulated runner peer and a recording host. This proves the request and response cross the V4 IPC framing and reach `HostApi`; it does **not** prove the actual Python plugin runs through IPC.
|
||||||
|
- Extended the OCS app-host Point batch test to assert redo after undo. This proves the real app history path for those edits; creation/deletion history remains untested by this case.
|
||||||
|
- Staged the actual debug Python cdylib with `stage-bundled.sh`. Its generated
|
||||||
|
manifest declares API v7 and the exact OCS acadrust and Rust compiler
|
||||||
|
fingerprints. The plugin now builds from `plugins/opencad-python` in this
|
||||||
|
repository and ships from the macOS application resources.
|
||||||
|
- The opt-in `staged_python_plugin_line_lifecycle_over_real_ipc` app test passed with the staged v7 Python plugin and built OCS executable. It creates, edits, and deletes a Line through Python over the actual runner IPC; confirms three undo entries and undo/redo; and writes/reopens the edited Line as DWG and DXF. It does not exercise GUI picking, multiple tabs, or cancellation. Re-run with `OCS_TEST_PYTHON_PLUGIN=<staged dylib> OCS_PLUGIN_RUNNER_EXE=<built OpenCADStudio executable> cargo test app::plugin_host::tests::staged_python_plugin_line_lifecycle_over_real_ipc --lib -- --test-threads=1 --nocapture` from the OCS checkout.
|
||||||
|
- The same Line test now also sends a duplicate-handle batch through Python and confirms the host rejects it without changing geometry or creating an undo entry.
|
||||||
|
- The opt-in `staged_python_point_pick_and_cancel_over_real_ipc` test passes with the same runner. It requests point and entity picks through Python, drives the app's active-command point/object-pick callbacks, polls the returned tokens through a later Python run, and verifies Enter cancellation. The callbacks are invoked by the test harness, not by a physical GUI pointer event; live GUI verification remains open.
|
||||||
|
- The opt-in `staged_python_tabs_isolate_tokens_and_notifications` test passes with two real OCS document tabs and the staged runner. A token created in tab 0 cannot be observed or consumed in tab 1 before or after completion. Host-to-plugin DrawingChanged notifications for both tab ids are delivered over IPC and drained only by their owning tab. A 257-event burst reports overflow, and `DocumentTabClosed` discards queued events for that tab.
|
||||||
|
- Added `doc.create_entity(kind, **properties)` and `doc.delete_entity(entity_or_handle)` to the high-level Python document model. Unit tests cover forwarding and managed identity fields. The real staged-plugin Line lifecycle now uses these methods rather than low-level `ocs.add`/`remove_entity`.
|
||||||
|
- Closed the first new-kind increment for `Tolerance`. The host coverage catalog now maps insertion point, direction, normal, text, dimension style name, text height, and gap; validates geometry and document style references; keeps the style handle read-only; and leaves the undocumented DWG short unmapped. The thin adapter adds generated conversion plus stale style-handle clearing when the style name changes.
|
||||||
|
- `staged_python_tolerance_lifecycle_over_real_ipc` passes the full C/R/E/D/U/I/W/V/P gate with the actual runner: high-level create/read/transaction edit/delete, live canvas selection, undo/redo, invalid direction and missing style rollback, untouched-field preservation, and DWG/DXF reopen. Tolerance is recorded as **Complete** in the ledger. The queue now continues with `Shape`.
|
||||||
|
- Closed `Shape` with a generated SHX fixture and a real shape-file `TextStyle`. Host-owned binding resolves the Python style name to the stable table handle required by DWG; validation rejects missing/non-shape styles and invalid geometry. The adapter maps all stable shape fields and keeps the bound style handle read-only.
|
||||||
|
- `staged_python_shape_lifecycle_over_real_ipc` passes C/R/E/D/U/I/W/V/P through the actual runner, checks the real SHX linework before and after DWG/DXF reopen, and proves that invalid size/style edits remain atomic. The DXF renderer fallback now searches named `is_shape_file` styles as well as legacy unnamed styles. Shape is **Complete**; the queue now continues with `AttributeDefinition`.
|
||||||
|
- Added creation-time `owner_handle` to the generated document-model adapter. It is present in snapshots and accepted by `doc.create_entity`, but rejected after creation; host transactions independently reject owner changes. Generic host validation now requires a non-null canvas owner to resolve to a block record, except `AttributeEntity`, whose owner may be an `Insert`.
|
||||||
|
- Mapped stable AttributeDefinition fields and validated tag, placement, normal, height, width, angles, text style, line count and block ownership. `embedded_mtext` stays snapshot-readable but unmapped so partial Python edits preserve its linked R2018+ layout payload.
|
||||||
|
- `staged_python_attribute_definition_lifecycle_over_real_ipc` passes the real create/read/edit/delete/undo/selection/render/validation/packaged-build path using a structurally valid block and linked Insert. Full DWG state and core DXF geometry survive reopen; deletion stays absent after both formats. OCS also stopped double-converting ATTDEF/ATTRIB DXF rotation already converted by acadrust.
|
||||||
|
- AttributeDefinition remains **Integration-tested / DXF blocked**, not Complete: acadrust `568a12c`'s ATTDEF DXF reader did not restore optional AcDbText fields including width factor. Revalidate this recorded failure against the currently merged `7ea4247` revision before keeping or clearing the W-gate blocker.
|
||||||
|
- Closed `AttributeEntity` without flattening canonical drawing storage. V4 views and IPC snapshots expose each nested child by handle, while host create/update/delete and transactions rewrite the owning Insert so rendering, serialization and undo remain consistent.
|
||||||
|
- `staged_python_attribute_entity_lifecycle_over_real_ipc` passes C/R/E/D/U/I/W/V/P with the actual v7 adapter. It creates a linked attribute from its block's ATTDEF, reads and edits value/placement/rotation, selects the parent Insert, renders text, rejects invalid tag/height/owner edits atomically, reopens edited and deleted state in DWG and DXF, and proves three-step undo/redo. AttributeEntity is **Complete**; the queue now continues with `Hatch`.
|
||||||
|
- Completed `Hatch` with full solid/pattern definitions and typed nested boundary paths. The adapter generator now handles single-payload tagged enums as `{kind, value}` dictionaries, which covers every Hatch edge variant and is reusable by later nested entity models. Unknown adapter properties are rejected instead of being silently ignored.
|
||||||
|
- `staged_python_hatch_lifecycle_over_real_ipc` passes C/R/E/D/U/I/W/V/P with closed line-loop fixtures: solid creation, conversion to a stored-line pattern, boundary replacement, selection and live render-cache checks, atomic invalid scale/association/open-loop/unmapped-payload rejection, edited/deleted DWG and DXF reopen, post-reopen edits, and three-step undo/redo. Hatch is **Complete**; the queue now continues with `Leader`.
|
||||||
|
- Mapped `Leader` (host validation and reference binding in `entity_coverage.rs`, policy/build.rs/manifest entries, adapter count 23). `staged_python_leader_lifecycle_over_real_ipc` passes C/R/E/D/U/I/V/P through the real runner. W is blocked by acadrust: the DXF writer omits the annotation handle (340), DXF reads lose `annotation_offset` (213), and DWG R2010+ does not store text size or hookline flag. Each gap is pinned by a canary assertion so it fails loudly once fixed. The queue now continues with `MLine`.
|
||||||
|
- Completed `MLine`. Host validation and style binding live in `ocs_plugin_api`; derived vertex geometry and element parameters are recomputed by the host (`normalize_scripted_mline`) on scripted create/edit, so scripts supply positions only. The adapter maps `flags` as an integer through a manifest override because the generator cannot classify acadrust's serde-newtype `MLineFlags`. `staged_python_mline_lifecycle_over_real_ipc` passes C/R/E/D/U/I/W/V/P with DWG and DXF reopen. The queue now continues with `Dimension`.
|
||||||
|
- Completed `Dimension` for all nine subtypes. Because the payload is an enum, the adapter generator gained a `manual_kinds` hook (hand-written `<kind>_to_dict/_from_dict/_apply`) and the host catalog a `synthetic` policy section. The host derives `actual_measurement` and the base definition point on every scripted create/edit. Python ints are now accepted wherever a coordinate or angle is expected. `staged_python_dimension_lifecycle_over_real_ipc` records each subtype separately and all nine pass C/R/E/D/U/I/W/V/P. The queue now continues with `MultiLeader`.
|
||||||
|
- Completed `MultiLeader`. The adapter generator now converts `Color`, `LineWeight`, mixed unit/payload enums, fixed float arrays and bitflags-2 newtypes, and a `keep_types` override lets a hand-written setter reuse generated converters (used for the merge-style `context` patch). `Leader.override_color` became writable through the same `Color` form; neither file format stores it. `staged_python_multileader_lifecycle_over_real_ipc` passes the full gate with DWG and DXF reopen. The queue now continues with `Table`.
|
||||||
|
- Completed `Table`. The generator now handles tuples and `usize`; the host keeps DXF cell merge dimensions in step with `merged_ranges`. `staged_python_table_lifecycle_over_real_ipc` passes the full gate with DWG and DXF reopen. The queue now continues with `PolygonMesh`.
|
||||||
|
- Completed `PolygonMesh`, `PolyfaceMesh` and `Mesh` (queue items 6-8) with one shared `run_mesh_lifecycle` test driver and per-kind host validation. The generator now omits a sub-record's own `EntityCommon` from the scripted form. All three pass the full gate including DWG and DXF reopen with re-edit. The queue now continues with `Helix`.
|
||||||
|
- Mapped `Helix` with a host-rebuilt spline. `run_mesh_lifecycle` gained per-format DXF expectations so an engine gap is pinned by a canary instead of hidden. All gates pass except W for `handedness` in DXF (reader ignores boolean group 290). The queue now continues with `RasterImage`.
|
||||||
|
- Mapped `RasterImage`. The host reads the image file, creates and links the `ImageDefinition`, and derives `size` and the default clip boundary. The shared lifecycle driver passes every gate in OCS with a real PNG; `ACAD_IMAGE_DICT`/reactor creation is not implemented, so the kind stays integration-tested. The queue now continues with `Wipeout`.
|
||||||
|
- Completed `Wipeout` (queue item 11) with rectangular and polygonal clip masks through the shared lifecycle driver; scripted creation matches OCS's native command. The queue now continues with `Underlay`.
|
||||||
|
- Mapped `Underlay` against a fixture PDF `UnderlayDefinition`. All gates pass except DXF W: the reader does not convert the degree-valued rotation back to radians, and repeated DXF round trips compound the error (pinned by a canary). The queue now continues with `Viewport`.
|
||||||
|
- Mapped `Viewport` with a paper-space owner rule and frozen-layer reference validation. Every gate except a paper-space canvas oracle passes through the shared driver; the kind stays integration-tested. The queue now continues with `ViewBorder`.
|
||||||
|
- Mapped `ViewBorder` with viewport and scale reference rules. All gates pass in DWG; DXF loading does not restore the typed entity (pinned by a canary). The queue now continues with `SectionSymbol`.
|
||||||
|
- Recorded `SectionSymbol` (queue item 15) as **blocked**: it needs a section view style and view representation the host cannot create, and its raw point-count fields have no documented derivation. Mapped `Light` (item 16); every gate passes except DXF `cast_shadows`, which the reader drops (pinned by a canary). The queue now continues with `Region`.
|
||||||
|
- Recorded `Region`, `Body`, `Solid3D`, `Surface` (queue items 17-20) and `Ole2Frame` (item 21) as **blocked**. The ACIS kinds need a host-side kernel-backed create/transform API that regenerates the payload, wires and silhouettes; the OLE frame needs a valid embedded-storage fixture. No opaque payload is rewritten. With this the ordered queue is complete: 12 kinds are fully complete, Leader, Helix, Underlay, ViewBorder and Light are mapped but blocked at DWG/DXF persistence by acadrust gaps, RasterImage and Viewport lack an oracle or linkage, and six kinds are blocked. Next work is the engine fixes behind the canary assertions, the mapped-kind audit of the 17 pre-existing kinds, and merging `origin/main`.
|
||||||
|
- Audited the 17 pre-existing mapped kinds through the shared real-runner driver (`audit_python_*`). The audit found and fixed genuine validation gaps: Ellipse had none, Text and MText accepted a zero height, Arc accepted non-finite angles, Point and Line accepted infinite thickness, and most basic kinds had no creation-time validation. A shared `validate_basic_entity` now covers Point, Line, Circle, Arc, Ellipse, Text, MText, LwPolyline, Polyline, Polyline2D, Polyline3D and Spline, refusing only problems an edit introduces so already-invalid legacy values stay editable. Twelve of the 17 kinds now pass every gate (Point, Line, Circle, Arc, Ellipse, LwPolyline, Text, MText, Ray, XLine, Solid, Face3D). Four expose persistence findings pinned by canaries (Polyline reopens as Polyline3D; Polyline2D reopens as LwPolyline in DXF; Polyline3D loses elevation in DWG; Spline loses weights in DXF), and Insert is update-only with all applicable gates passing. The driver gained per-format DWG expectations and a host-made block fixture for Insert.
|
||||||
|
- Audited `AttributeDefinition` against acadrust `5b682ed` with a full-field comparison through both formats. Everything passes in DWG. DXF keeps only tag, prompt, value, insertion point, height and rotation because the reader handles eight group codes; alignment, width factor, oblique angle, attribute flags, field length, generation flags, lock and text style reopen as defaults. The kind stays integration-tested and the gap is pinned by canary expectations; the fix belongs in cadcodec's `read_attdef`. The shared driver's block fixture now also serves `MAKEBLOCK` scripts.
|
||||||
|
- Decided the two open audit questions. **Insert is creatable** by naming an existing block (existence, ordinary-block and no-cycle checks; attribute records stay with the AttributeEntity flow), which completes the kind. **Legacy Polyline is update-only** with a hint pointing scripts at Polyline2D and Polyline3D, because both formats convert it on save. The generator gained an `update_only_message` for such kinds, integer coordinates are accepted in Insert scales, and the driver gained `MAKEPOLYLINE` and `MAKEBLOCK` fixtures.
|
||||||
|
- Wrote up the cadcodec DXF reader gaps as draft issues in [cadcodec-reader-gaps.md](cadcodec-reader-gaps.md) (nothing filed): ATTDEF, boolean groups read through `as_i16()`, UNDERLAY rotation units, LEADER, DRAWINGVIEW/SECTIONLINE dispatch and TABLE merged ranges. Verifying them corrected an earlier attribution: the Spline "DXF drops weights" finding was an OCS bug (the writer emits weights only for a rational spline), now fixed by setting `flags.rational` from the weights, so Spline is complete.
|
||||||
|
- Mapped `Ole2Frame` as update-only (queue item 21, previously blocked). OCS already builds real embedded frames (`build_embedded_ole`), which supplied the fixture the blocker was waiting for. Frame corners and the aspect lock are scriptable; the opaque storage and envelope are excluded and refused on edit. The audit proves the embedded picture survives DWG and DXF unchanged. Creation from Python remains a follow-up. The remaining blocked kinds are SectionSymbol, Region, Body, Solid3D and Surface.
|
||||||
|
- Investigated the cadkernel path for the ACIS kinds ([cadkernel-body-path.md](cadkernel-body-path.md)). The earlier "blocked" reasoning was overstated: OCS already builds primitives, transforms bodies and runs booleans through cadkernel, and `solid_to_sat` plus `kernel_acis_body` verify each result lifts back with no loss. Two `#[ignore]` spike tests measured exact volumes and DWG and DXF round trips for a box, moved, rotated and mirrored copies, three booleans, four other primitives and a `Body` entity. The real gap is an operation channel from a script to that pipeline; the note recommends an additive `solid_operation` host method and a phased plan (Solid3D create and transform, then booleans and Body, then Region, then Surface). Booleans took about 23 s each in a debug build and need release timing first. Region, Body, Solid3D and Surface move from blocked to unblocked-by-design; SectionSymbol stays blocked.
|
||||||
|
- Built the cadkernel operation channel and completed `Solid3D` (create and rigid move). `HostApi::solid_operation` is additive (default "unsupported"), so older hosts and plugins are unaffected; it travels as `PluginRequest::SolidOperation` and `PluginResponse::SolidResult`, and the host records its own undo step only after validation so a refused operation leaves nothing behind. The Python surface is `doc.solids.*`. Every result is verified lossless by the kernel path before it is accepted and a payload that will not lift is refused untouched. `Body` moves through the same channel and `Region` is accepted but untested. Booleans, Region creation from curves and Surface remain, in that order; booleans wait on release-build timing. Solid3D, Body and Region are now mapped read-only with the opaque payload excluded and preserved.
|
||||||
|
- Completed `Region`. `SolidOperation::RegionFromProfile` reuses the REGION command's kernel calls and `doc.solids.region` exposes it; the lifecycle test creates regions from real circle and polyline entities and covers deletion of the source, refusals, a move, both formats and undo. Along the way `create_entity` now accepts `(x, y, z)` tuples for point properties (decided from the schema's property types) and every generated float setter accepts Python ints, so `create_entity('Circle', center=(0, 0, 0), radius=5)` works. Left: booleans (release timing first), holes and open-curve merging for regions, and `Surface`.
|
||||||
|
- Completed `Surface` for planes, extruded open profiles, isolines and rigid moves. `SurfaceFromProfile` and `Extrude` join the kernel operations (`doc.solids.surface` and `doc.solids.extrude`); `Extrude` also gives Solid3D extrusions from closed profiles, checked against analytic volumes. The test found and fixed a real bug: Surface's `kind` field silently overwrote the entity-type `kind` key in Python dicts, so it is exposed as `surface_kind`, and a new uniqueness test guards the whole catalog. Transform now accepts surfaces (a plane stays a plane; other kinds turn generic). Left: booleans (release timing first), regions with holes, and lofted, revolved, swept and NURBS surfaces. SectionSymbol is the only unmapped kind.
|
||||||
|
- Timed booleans in a release build (details in [cadkernel-body-path.md](cadkernel-body-path.md)). A curved box-and-cylinder boolean takes about 1 to 2.2 s, overlapping spheres 0.2 s and planar operands 1 to 2 ms, against 23 s in a debug build. The kernel refuses many curved cases quickly with a reason (`Coincident`, `CutRefused`, `NoClosedForm`), including a second cut in an already drilled box. Recommendation: add a synchronous `SolidOperation::Boolean` that surfaces the refusal and leaves the operands untouched, test it with planar operands plus one ignored curved case, and note the 30 s per-script budget. No code changed in this step.
|
||||||
|
- Implemented `SolidOperation::Boolean` and `doc.solids.union`, `subtract` and `intersect`, as recommended by the timing study. It runs synchronously, surfaces the kernel's refusal (`Coincident`, `CutRefused`, `NoClosedForm`) with a plain-language reason and the words "nothing was changed", consumes the operands unless `keep_operands`, and records one undo step. The lifecycle test uses planar boxes (millisecond cost, exact volumes, debug-safe) and an `#[ignore]` test documents a curved refusal. With this the kernel operations in the cadkernel note are all built. SectionSymbol is the only unmapped kind.
|
||||||
|
- Mapped `SectionSymbol`, the last unmapped kind, so all 43 canvas kinds now have explicit writes. The blocker recorded earlier was overstated: cadcodec documents `points` as canonical, says the counts equal the point count in every verified export, and provides `sync_display_fields()`, which OCS's own edits already call; OCS also renders a symbol with no style or view link. The host derives the counts and projections when `points` changes and validates that references are existing `SectionViewStyle` and `ViewRep` class objects. Every gate passes except DXF, where cadcodec reopens a top-level `SECTIONLINE` as an unknown entity (issue 5 in the cadcodec write-up, pinned by a canary). Still unverifiable here: the meaning of `raw_flags_90` and AutoCAD's acceptance of a symbol with no parent view.
|
||||||
|
- Completed `Ole2Frame` by adding creation. `SolidOperation::EmbedPicture` and `doc.embed_picture` build the frame from a picture file with OCS's own embedding code, so a script never touches the opaque storage; PNG, JPEG and BMP are stored byte-for-byte and other formats are re-encoded as PNG. The lifecycle test now creates through Python and the new creation-rules test covers formats, aspect, origin, layer and seven refusals. 30 kinds are complete.
|
||||||
|
- Completed `Viewport` by closing its missing canvas oracle and its derived state. The shared driver now switches the scene to the layout that owns a viewport and requires a drawn frame. The host assigns a unique id (at least 2) and derives `custom_scale = height / view_height` on every scripted create or edit, as MVIEW does, so `custom_scale` became read-only. A control showed my earlier suspicion was wrong: the default id 0 still draws a frame in a layout with no sheet viewport, so the id matters for uniqueness, not visibility. 31 kinds are complete.
|
||||||
|
- Improved `RasterImage` linkage. A scripted image now reuses one definition per file and registers it in `ACAD_IMAGE_DICT`, which owns it; this persists through DWG and DXF. The `IMAGEDEF_REACTOR` is deliberately not written: its owner convention is ambiguous between cadcodec's struct docs and its DXF writer and cannot be checked against AutoCAD here, so the kind stays integration-tested. An exploratory spike also showed that OCS's own IMAGE command creates bare images that lose their file path on save, an OCS bug outside this plugin work that is flagged separately.
|
||||||
|
|
||||||
|
### 2026-09-21: beyond entities, the layer table (`doc.layers`)
|
||||||
|
|
||||||
|
Entity CRUD is at its ceiling without the cadcodec fixes (PR HakanSeven12/cadcodec#48), so work moved to
|
||||||
|
drawing objects a script needs. New additive v7 request `TableOperation` (`LayerCreate`, `LayerModify`,
|
||||||
|
`LayerRename`, `LayerDelete { erase_objects }`, `LayerSetCurrent`) with `HostApi::table_operation`,
|
||||||
|
executed by `HostSession::table_operation`. Every refusal (invalid or duplicate name, bad color,
|
||||||
|
unknown linetype, out-of-range lineweight or transparency, protected layer `0`/`Defpoints`, current
|
||||||
|
layer, layer holding objects without `erase_objects`) is decided before the undo step is recorded, so
|
||||||
|
nothing changes. Python: `ocs.active_document.layers` (`create`, `modify`, `rename`, `delete`,
|
||||||
|
`set_current`, `current`, lookup and iteration). Evidence: `audit_python_layer_table_over_real_ipc`
|
||||||
|
(19 refusals, live/DWG/DXF persistence of colour, lineweight, transparency, flags, linetype,
|
||||||
|
description, rename following entities, `erase_objects` and one-step undo), an IPC round-trip test and a
|
||||||
|
Python unit test. Next: text and dimension styles, linetypes, blocks, layouts; then headless commands.
|
||||||
|
|
||||||
|
### 2026-09-21: text and dimension styles (`doc.text_styles`, `doc.dim_styles`)
|
||||||
|
|
||||||
|
`TableOperation` grew `TextStyleCreate/Modify`, `DimStyleCreate/Modify` (DimStyle fields travel as a JSON
|
||||||
|
object, so all 88 are settable with host validation; handles, xref fields and the name are refused),
|
||||||
|
`StyleRename`, `StyleDelete`, `StyleSetCurrent`. The host reuses OCS's own style machinery (in-use scan,
|
||||||
|
reference-following rename) by widening four `style_ops` methods to `pub(super)`, and additionally makes a
|
||||||
|
renamed text style's name follow into dimension styles. Style operations require the active tab.
|
||||||
|
Evidence: `audit_python_text_and_dim_styles_over_real_ipc` (26 refusals, live/DWG/DXF persistence, copy
|
||||||
|
semantics, rename following references, current/delete guards, five-step undo), IPC round-trip and Python unit
|
||||||
|
tests. Four cadcodec findings (STYLE flags and oblique units, DIMSTYLE name, `true_type_font`) are pinned by
|
||||||
|
canaries and listed in `cadcodec-reader-gaps.md`. Next: linetypes, blocks, layouts; then headless commands.
|
||||||
|
|
||||||
|
### 2026-09-21: blocks (`doc.blocks`)
|
||||||
|
|
||||||
|
`TableOperation` gained `BlockCreate` (copy existing model/paper entities into a definition shifted by
|
||||||
|
`-base_point`, optionally erasing the originals), `BlockModify` (description, explodable, uniform scale),
|
||||||
|
`BlockRename` (inserts follow, via `Scene::rename_block`) and `BlockDelete` (refused while an insert, a
|
||||||
|
dimension-style arrow or a multileader uses it; removes the members, markers, record and orphaned draw-order
|
||||||
|
tables). Creation reuses `Scene::define_block_from_owned_entities`. Python: `blocks.create/modify/rename/delete`,
|
||||||
|
lookup and iteration, records with member handles and kinds. Evidence: `audit_python_blocks_over_real_ipc`
|
||||||
|
(18 refusals; shifted geometry and base point; inserts following a rename; original kept vs erased;
|
||||||
|
live/DWG/DXF persistence; guarded delete; three-step undo restoring the definitions), IPC round-trip and Python
|
||||||
|
unit tests. One more cadcodec finding (DXF drops the block description) is pinned by a canary. Not covered:
|
||||||
|
editing a definition's contents in place, and attribute definitions inside a scripted block. Next: linetypes and
|
||||||
|
layouts, then headless commands.
|
||||||
|
|
||||||
|
### 2026-09-21: block contents (`create_entity(..., block=)`)
|
||||||
|
|
||||||
|
`TableOperation::BlockEntityAdd` adds a validated entity to a definition: the host sets the owner, runs the same
|
||||||
|
validation and reference binding as a new model-space entity, refuses viewports, raster images, block markers,
|
||||||
|
nested attributes and self-nesting inserts (direct or transitive), then reuses the scene's block-editor routing so
|
||||||
|
the entity gets normal preparation. Editing and deleting members already worked through the entity API; deleting a
|
||||||
|
member now also drops its handle from the block record, because the core document leaves a removed entity
|
||||||
|
listed (`entity_handles`). An entity-delta undo of an add still leaves the handle listed (documented scene behaviour),
|
||||||
|
so consumers must treat `entity_handles` as candidates and confirm with `get_entity`; the Python block records
|
||||||
|
already do. Evidence: `audit_python_block_contents_over_real_ipc` (9 refusals; create, edit, delete in a block;
|
||||||
|
attribute definition inside a block; nested insert; live/DWG/DXF persistence; undo), IPC and Python unit tests.
|
||||||
|
Next: linetypes and layouts, then headless commands.
|
||||||
|
|
||||||
|
### 2026-09-21: linetypes and layouts (`doc.linetypes`, `doc.layouts`)
|
||||||
|
|
||||||
|
`TableOperation` gained `LinetypeCreate/Modify/Rename/Delete` (simple patterns only, standard names taken, rename
|
||||||
|
follows layers and entities, delete refused while a layer, entity, dimension style or the current setting uses it) and
|
||||||
|
`LayoutCreate/Rename/Delete/SetCurrent/SetPage` (reusing `add_layout`, the default page setup, the sheet viewport,
|
||||||
|
`rename_layout` plus the layout dictionary key, `delete_layout`, and the application's own `on_layout_switch`; `Model` is
|
||||||
|
protected; `set_page` sets paper size, rotation and a custom scale and refreshes the limits). The host system variable
|
||||||
|
`CTAB` now reports the current layout. Evidence: `audit_python_linetypes_and_layouts_over_real_ipc` (34 refusals; patterns,
|
||||||
|
modify, rename following layers; page setup; an entity created on a sheet and not in model space; live/DWG/DXF
|
||||||
|
persistence; deleting the current layout; four-step undo restoring the layouts, their entity and the linetype), IPC
|
||||||
|
round-trip and Python unit tests. Not covered: complex (text/shape) linetypes, reordering layouts, plot devices and
|
||||||
|
styles, and page-setup names. Next: headless command execution.
|
||||||
|
|
||||||
|
### 2026-09-21: command runner and modify wrappers (`doc.command`, `doc.start_command`, `doc.modify`)
|
||||||
|
|
||||||
|
`HostApi::run_command(CommandRequest) -> CommandOutcome` (additive v7; `Run`, `Start`, `Point`, `Text`, `Token`, `Entity`,
|
||||||
|
`Selection`, `Enter`, `Cancel`) drives the real command through the same primitives the automation channel uses
|
||||||
|
(`run_command_line`, `dispatch_command`, `feed_command`, `feed_active_cmd`, `CommandEscape`) and finishes each step with
|
||||||
|
`drive_headless_task`, which is synchronous on the host thread. The earlier "nested command replay can hang" concern does not
|
||||||
|
apply to this path: no step waits on anything that must arrive from outside, the exploration harness ran every command
|
||||||
|
tried without a hang, and an editor or dialog a command opens is reported in `blocked_by` and closed by `Cancel`. It refuses
|
||||||
|
while another command is active, on a denylist (`QUIT`, `EXIT`, `CLOSE*`, `NEW`, `QNEW`, `OPEN`, `SAVE*`, `RECOVER`, `SCRIPT`,
|
||||||
|
`RUNSCRIPT`, `PY_*`), and off the active tab. It does not consult the user's automation on/off switch, which governs the
|
||||||
|
external MCP/serve channel; a script is already something the user chose to run. Python: `doc.command`, `doc.start_command`
|
||||||
|
(context manager that cancels a waiting command) and `doc.modify` (offset, trim, extend, fillet, move, copy, rotate, scale,
|
||||||
|
mirror, erase). The prompt sequences were observed with `spike_command_runner_prompts` (ignored harness). Evidence:
|
||||||
|
`audit_python_modify_wrappers_over_real_ipc` checks exact geometry for every wrapper (offset distance and side, trim and
|
||||||
|
extend end points, fillet arc centre and radius, move, copy keeping the original, rotate, scale, mirror keeping the source,
|
||||||
|
erase), `doc.command` and an interactive session, nine refusals (quit, new, `PY_RUN`, unknown, incomplete line, input with no
|
||||||
|
command, second command, run while active), no command left running, and a one-step undo. IPC round-trip and Python unit tests.
|
||||||
|
Not covered: chamfer, arrays, hatch, join, explode, break and the many other commands (reachable through `doc.command` and
|
||||||
|
`start_command`); reading prompts for commands with a text editor; an on/off setting for script-driven commands.
|
||||||
|
|
||||||
|
### 2026-09-21: more modify wrappers
|
||||||
|
|
||||||
|
`doc.modify` gained `chamfer`, `array_rect`, `array_polar`, `explode`, `join`, `break_entity`, `stretch` and `lengthen`, each
|
||||||
|
written against the prompt sequence observed in `spike_command_runner_prompts` (STRETCH needs an Enter after the crossing
|
||||||
|
window, LENGTHEN and STRETCH end on Enter, EXPLODE and JOIN use the pre-selection because a pick at their selection prompt
|
||||||
|
selects nothing). `audit_python_modify_wrappers_over_real_ipc` checks exact geometry for each: the chamfer line, all six
|
||||||
|
rectangular-array members, the four polar-array members (start and half turn), the exploded segments and the removed polyline,
|
||||||
|
the joined line without its parts, the two pieces after a break, the stretched and the lengthened end points. HATCH is left to
|
||||||
|
`create_entity("Hatch")`: its command needs an interactive boundary pick that no scripted step can supply. Not wrapped: PEDIT,
|
||||||
|
path and 3-D arrays, and the remaining commands, which stay reachable through `doc.command` and `start_command`.
|
||||||
|
|
||||||
|
### 2026-09-21: nested input is validated (vertex validation gap)
|
||||||
|
|
||||||
|
Found while writing the `explode` audit: an `LwPolyline` created from vertices that used the wrong key (`{'x': .., 'y': ..}` instead of
|
||||||
|
`{'location': ..}`) was accepted and became zero-coordinate vertices. The generated dict-to-struct conversions for nested records
|
||||||
|
defaulted every absent field and ignored unknown keys, so any typo inside a list of vertices, edges or faces vanished silently.
|
||||||
|
The generator now (1) refuses an unknown key in every nested record, naming the keys it takes, and (2) enforces a manifest list,
|
||||||
|
`required_struct_fields`, of the fields that define a nested record's geometry: `LwVertex.location`, `Vertex2D.location`,
|
||||||
|
`Vertex3D.location`, `Vertex3DPolyline.position`, `PolygonMeshVertex.location`, `PolyfaceVertex.location`, `MLineVertex.position`,
|
||||||
|
`LineEdge.start/end`, `CircularArcEdge.center/radius`, `EllipticArcEdge.center/major_axis_endpoint`, `PolylineEdge.vertices` and
|
||||||
|
`SectionSymbolPoint.point`. A `None` counts as missing. Everything else in a nested record still defaults when absent. Evidence:
|
||||||
|
`audit_python_nested_input_is_validated_over_real_ipc` (eight refusals with the right messages for LwPolyline, Polyline2D and
|
||||||
|
PolygonMesh; nothing invalid reaches the drawing; the valid forms still create), and every existing per-kind lifecycle audit still passes.
|
||||||
|
|
||||||
|
### 2026-09-21: PEDIT and the remaining arrays
|
||||||
|
|
||||||
|
`doc.modify` gained `array_path`, `array_3d`, `polyline_close`, `polyline_open`, `polyline_width`, `polyline_reverse` and `polyline_join`,
|
||||||
|
written against the prompts observed in `spike_command_runner_prompts` (PEDIT offers to turn a line or arc into a polyline and the wrapper
|
||||||
|
accepts; the join option takes a selection, and its Enter completes the whole command). The default pick point for a polyline is its first
|
||||||
|
vertex. `audit_python_modify_wrappers_over_real_ipc` checks: closed and opened flags, the widened polyline, the reversed vertex order, the
|
||||||
|
joined polyline's three vertices with its line consumed, a line turned into a widened polyline (and the line gone), all five path-array
|
||||||
|
positions (2600 to 2650 in 12.5 steps), and all eight members of the 3-D array (x 2700/2720, y 0/10, z 0/30). Finding: PEDIT's line-to-polyline
|
||||||
|
step needs between 2 and 4 MiB of stack in a debug build, more than a test thread's 2 MiB, so that audit runs on a 64 MiB thread; the
|
||||||
|
application's main thread has 8 MiB, and a release build uses far less. Not wrapped: PEDIT fit, spline, decurve, linetype generation and
|
||||||
|
vertex editing.
|
||||||
|
|
||||||
|
### 2026-09-21: guardrails (`SCRIPTCOMMANDS`, stack)
|
||||||
|
|
||||||
|
**On/off setting.** A saved user preference, `UserSettings::script_commands` (on by default, so an existing config keeps
|
||||||
|
scripts allowed), toggled by the `SCRIPTCOMMANDS [0|1]` command, gates `HostApi::run_command`: while it is off every `Run`,
|
||||||
|
`Start` and input request is refused (`Cancel` stays allowed so a waiting command is never stranded) with a message that says how to turn it back on. The runner refuses the command
|
||||||
|
itself (it joins `QUIT`, `NEW`, `PY_*` and the rest on the denylist), so a script cannot switch it. It is a command and a
|
||||||
|
persisted flag only; there is no Options-page control, which would need locale and layout work in files outside this feature.
|
||||||
|
Evidence: `script_commands_setting_gates_the_runner` (default on; a script cannot change it; the user turns it off and nothing
|
||||||
|
runs, `Run` and `Start` both refused, no entity added; back on and it runs) and `script_commands_default_on_and_survive_a_round_trip`.
|
||||||
|
Checked that the test did not write the setting into the real user config.
|
||||||
|
|
||||||
|
**Stack.** The planned large-stack thread for command steps was not built, on the evidence: the native builds already link with
|
||||||
|
at least 8 MiB (`.cargo/config.toml` raises Windows to 16 MiB), the deepest step found (PEDIT converting a line to a polyline)
|
||||||
|
needs 2 to 4 MiB in a debug build, and the nesting depth is fixed because `PY_*` is refused, so it cannot recurse. Moving the step
|
||||||
|
to a helper thread would be unsound here (the editor state is not `Send` and some of it has thread affinity), and the alternative,
|
||||||
|
a stack-growing dependency such as `stacker`, adds a crate to H7's tree to guard a case that cannot occur. The 64 MiB thread in the
|
||||||
|
PEDIT audit stays, because a test thread gets only 2 MiB.
|
||||||
|
|
||||||
|
### 2026-09-21: cadcodec PR #51 (text and dimension style DXF fixes)
|
||||||
|
|
||||||
|
Second small upstream PR, [HakanSeven12/cadcodec#51](https://github.com/HakanSeven12/cadcodec/pull/51): STYLE generation
|
||||||
|
flags (group 71 was hard-coded to 0), the STYLE oblique angle (group 50 is degrees; it was written and read as raw radians)
|
||||||
|
and the DIMSTYLE text-style name (resolved from the group 340 handle). Three commits, three regression tests, independent of
|
||||||
|
#48 (merged locally with it; the combined suite passes). Not included: `true_type_font` and the block description, which need
|
||||||
|
an XDATA layout that cannot be verified here. OCS still pins the unfixed revision, so the canaries in
|
||||||
|
`audit_python_text_and_dim_styles_over_real_ipc` still assert the wrong result until #51 is merged and OCS repins.
|
||||||
|
|
||||||
|
### 2026-09-21: Linux and Windows verification
|
||||||
|
|
||||||
|
The change was built in release on Ubuntu and Windows runners with the Python plugin staged beside the executable
|
||||||
|
(`plugins/opencad.python`, where the host looks for it on both platforms), and the real-IPC plugin tests ran against
|
||||||
|
that build: **60 of 60 on each** (unsigned portable packages, built by a fork-only workflow that is not part of this change).
|
||||||
|
The first Windows run failed two tests because the harness substituted the Windows temp directory (`C:\Users\...`) into a
|
||||||
|
Python string literal, where `\U` is a unicode escape; that was a test-harness path problem, not a product one, and is fixed by
|
||||||
|
handing the scripts a forward-slash path. Not covered: the whole workspace suite on Windows, the macOS-only bundle path, and an
|
||||||
|
installer (AppImage or MSI) that includes the plugin.
|
||||||
|
|
||||||
|
### 2026-09-21: pull-request check (`python-host-check.yml`)
|
||||||
|
|
||||||
|
`.github/workflows/python-host-check.yml` runs on `pull_request` (path-filtered to the plugin API, the plugin, the host's plugin and command
|
||||||
|
files, settings and the lockfile), on a `pr-check-*` tag and by hand, on `ubuntu-22.04` and `windows-latest`. Steps: the plugin API tests
|
||||||
|
(`--features host`), staging the bundled plugin and building the runner, the plugin crate tests, the Python model unit tests, and the host's
|
||||||
|
real-IPC tests. It fails outright if the staged plugin or the runner is missing, because those tests otherwise skip and report success. First run
|
||||||
|
(`pr-check-1`, commit `1f8cbb81`, all green on both platforms): 115 plugin API tests, 20 plugin crate tests, 16 Python model tests and 60 real-IPC
|
||||||
|
host tests on each. Debug build, so a cold run is about 30 minutes and a cached one much less. The whole lib suite is deliberately not run by that workflow, because `main`'s own `Tests` workflow (`cargo test --workspace --locked`, added upstream on 21 September) runs it on every pull request. Against the merged tree that command gives 1,805 passed and 1 failed locally on macOS, `fonts_parse_and_resolve`, which also fails on pristine `main` there.
|
||||||
|
|
||||||
|
### 2026-09-21: merged upstream `main` (25 commits)
|
||||||
|
|
||||||
|
Merged `origin/main` at its head (no conflicts). Upstream added `.github/workflows/ci.yml` (`cargo test --workspace --locked` on Linux for every
|
||||||
|
pull request, `LC_ALL=C`), removed the Nix files, and added parametric-constraint and viewport-plot changes. Re-verified on the merged tree: the
|
||||||
|
plugin gate (60 real-IPC host tests, 115 plugin API, 20 plugin crate, 16 Python model), the wasm check, and the upstream workspace command with
|
||||||
|
`--no-fail-fast` (1,805 passed, 1 failed: `fonts_parse_and_resolve`, which fails on pristine `main` on this Mac too; `arc_grips_drive_center_start_and_end_but_not_midpoint`
|
||||||
|
now passes, fixed upstream). The change is 72 files, +30,705 / -178 against current `main` (fork-only workflow excluded).
|
||||||
|
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
# OCS canvas kind coverage ledger
|
||||||
|
|
||||||
|
Use with [the completion plan](plugin-host-model-completion-plan.md). This ledger is current as of 21 September 2026 (the object tables, block contents and command runner added since are described in [the design note](plugin-host-model.md) and the plan's progress log; they are not entity kinds): **43 of 43 canvas kinds have explicit geometry writes** (41 creatable, plus update-only legacy `Polyline` and `Body`), **31 kinds are complete**, and none remains layer-only. `Mapped` means at least one non-layer field is exposed for Python writes; it does **not** mean the kind passes the completion gate. `Update-only` means Python creation is unavailable. `Layer-only` means raw inspection and canvas layer edits exist, but geometry is not mapped. Record actual evidence or a blocking issue before changing any status to `Complete`.
|
||||||
|
|
||||||
|
**Rows blocked at W by cadcodec.** Fixes for six of the DXF bugs behind them are submitted as [HakanSeven12/cadcodec#48](https://github.com/HakanSeven12/cadcodec/pull/48) (ATTDEF fields, boolean group codes for Helix and Light, UNDERLAY rotation, LEADER link and vectors, DRAWINGVIEW/SECTIONLINE dispatch, TABLE merged ranges). OCS still pins the unfixed revision `5b682ed`, so those rows stay blocked and their canaries still assert the wrong result; the expectation is that they flip and the rows move to `Complete` once #48 is merged and OCS repins. That has been checked in cadcodec's own round-trip tests, not yet in OCS.
|
||||||
|
|
||||||
|
Completion gate codes: **C** = create through Python document model; **R** = read; **E** = edit defining geometry and another property; **D** = delete; **U** = undo/redo and atomic failure; **I** = real IPC plus GUI/canvas pick or observable behavior; **W** = DWG and DXF save/reopen; **V** = invalid-input checks and untouched-field/reference preservation; **P** = build and load the in-tree bundled plugin with a manifest matching the host toolchain and acadrust source. A kind is `Complete` only when **C/R/E/D/U/I/W/V/P** all pass and its property catalog matches implementation. `Blocked` requires a specific dependency or failing fixture.
|
||||||
|
|
||||||
|
| Kind | Baseline | Gate evidence / blocker |
|
||||||
|
|---|---|---|
|
||||||
|
| Point | **Complete** | Exercised: `location`, `thickness`. Rejects non-finite location, thickness and axis angle and a zero normal, which the audit found were previously accepted (thickness and normal) or unchecked at creation. `audit_python_point_lifecycle_over_real_ipc` (shared `run_mesh_lifecycle`, real runner) passes C/R/E/D/U/I/W/V/P: creation, a two-or-more-property transaction edit with the entity's common data, identity and selection preserved, canvas wires, invalid-input rejection with an atomic multi-entity rollback, DWG and DXF reopen with re-edit, and three-step undo/redo. The audit added the shared `validate_basic_entity` (creation must be valid; an edit is refused only for problems it introduces, so already-invalid legacy values stay editable). |
|
||||||
|
| Line | **Complete** | Exercised: `end`, `thickness`. Existing endpoint, undo, selection and pick coverage plus the second-property edit the earlier row asked for. Rejects non-finite endpoints and thickness and a zero normal (thickness was previously accepted). `audit_python_line_lifecycle_over_real_ipc` (shared `run_mesh_lifecycle`, real runner) passes C/R/E/D/U/I/W/V/P: creation, a two-or-more-property transaction edit with the entity's common data, identity and selection preserved, canvas wires, invalid-input rejection with an atomic multi-entity rollback, DWG and DXF reopen with re-edit, and three-step undo/redo. The audit added the shared `validate_basic_entity` (creation must be valid; an edit is refused only for problems it introduces, so already-invalid legacy values stay editable). |
|
||||||
|
| Circle | **Complete** | Exercised: `radius`, `center`. Rejects a non-positive or non-finite radius, non-finite center and thickness, and a zero normal. `audit_python_circle_lifecycle_over_real_ipc` (shared `run_mesh_lifecycle`, real runner) passes C/R/E/D/U/I/W/V/P: creation, a two-or-more-property transaction edit with the entity's common data, identity and selection preserved, canvas wires, invalid-input rejection with an atomic multi-entity rollback, DWG and DXF reopen with re-edit, and three-step undo/redo. The audit added the shared `validate_basic_entity` (creation must be valid; an edit is refused only for problems it introduces, so already-invalid legacy values stay editable). |
|
||||||
|
| Arc | **Complete** | Exercised: `end_angle`, `radius`. Rejects a non-positive radius, non-finite angles (previously accepted), center and thickness, and a zero normal. `audit_python_arc_lifecycle_over_real_ipc` (shared `run_mesh_lifecycle`, real runner) passes C/R/E/D/U/I/W/V/P: creation, a two-or-more-property transaction edit with the entity's common data, identity and selection preserved, canvas wires, invalid-input rejection with an atomic multi-entity rollback, DWG and DXF reopen with re-edit, and three-step undo/redo. The audit added the shared `validate_basic_entity` (creation must be valid; an edit is refused only for problems it introduces, so already-invalid legacy values stay editable). |
|
||||||
|
| Ellipse | **Complete** | Exercised: `minor_axis_ratio`, `end_parameter`. The audit found Ellipse had no validation at all; it now requires a nonzero major axis, a ratio within (0, 1], finite parameters and a nonzero normal. `audit_python_ellipse_lifecycle_over_real_ipc` (shared `run_mesh_lifecycle`, real runner) passes C/R/E/D/U/I/W/V/P: creation, a two-or-more-property transaction edit with the entity's common data, identity and selection preserved, canvas wires, invalid-input rejection with an atomic multi-entity rollback, DWG and DXF reopen with re-edit, and three-step undo/redo. The audit added the shared `validate_basic_entity` (creation must be valid; an edit is refused only for problems it introduces, so already-invalid legacy values stay editable). |
|
||||||
|
| Polyline | **Update-only (decision)** | Decision (2026-09-20): the legacy `Polyline` (3-D vertices) is not creatable from Python, because both file formats save it as `Polyline3D` and it would silently change kind on the first save. Creating one now fails with a message that names `Polyline2D` and `Polyline3D`. Existing `Polyline` entities remain editable: `audit_python_polyline_lifecycle_over_real_ipc` (host-made fixture) passes E/D/U/I/V with vertex and closed edits, canvas wires, rejection of short and non-finite vertex lists, an atomic rollback and three-step undo/redo, and pins the reopen behavior (both DWG and DXF return a `Polyline3D` with the vertices and closure intact). Scripts should create `Polyline2D` or `Polyline3D`. |
|
||||||
|
| Polyline2D | **Integration-tested / kind changes on DXF save** | Exercised: `vertices`, `closed`, `thickness`. Passes every gate in DWG. DXF reopens a 2-D polyline as an `LwPolyline` (vertices, closure and width survive, but the kind changes and `thickness` is not part of that record's digest here); pinned by a canary expectation. `audit_python_polyline2d_lifecycle_over_real_ipc` (shared `run_mesh_lifecycle`, real runner) passes C/R/E/D/U/I/W/V/P: creation, a two-or-more-property transaction edit with the entity's common data, identity and selection preserved, canvas wires, invalid-input rejection with an atomic multi-entity rollback, DWG and DXF reopen with re-edit, and three-step undo/redo. The audit added the shared `validate_basic_entity` (creation must be valid; an edit is refused only for problems it introduces, so already-invalid legacy values stay editable). |
|
||||||
|
| Polyline3D | **Integration-tested / blocked at W by the DWG format (elevation)** | Exercised: `vertices`, `elevation`. Passes every gate in DXF; DWG does not store a 3-D polyline's `elevation`, so it reopens as 0 (pinned by a canary). Vertices persist. `audit_python_polyline3d_lifecycle_over_real_ipc` (shared `run_mesh_lifecycle`, real runner) passes C/R/E/D/U/I/W/V/P: creation, a two-or-more-property transaction edit with the entity's common data, identity and selection preserved, canvas wires, invalid-input rejection with an atomic multi-entity rollback, DWG and DXF reopen with re-edit, and three-step undo/redo. The audit added the shared `validate_basic_entity` (creation must be valid; an edit is refused only for problems it introduces, so already-invalid legacy values stay editable). |
|
||||||
|
| LwPolyline | **Complete** | Exercised: `vertices` (with a bulge), `is_closed`, `constant_width`. Rejects fewer than 2 vertices, non-finite locations, bulges and widths, a negative constant width and a zero normal. `audit_python_lwpolyline_lifecycle_over_real_ipc` (shared `run_mesh_lifecycle`, real runner) passes C/R/E/D/U/I/W/V/P: creation, a two-or-more-property transaction edit with the entity's common data, identity and selection preserved, canvas wires, invalid-input rejection with an atomic multi-entity rollback, DWG and DXF reopen with re-edit, and three-step undo/redo. The audit added the shared `validate_basic_entity` (creation must be valid; an edit is refused only for problems it introduces, so already-invalid legacy values stay editable). |
|
||||||
|
| Spline | **Complete** | Exercised: `control_points`, `weights`. Validation covers degree, control-point count, knot count and order, weights and finite points. The host sets `flags.rational` whenever weights are present, because the DXF writer emits group 41 only for a rational spline; the audit first showed weights vanishing in DXF and traced it to that missing flag (an OCS bug, not a cadcodec one), now fixed. `audit_python_spline_lifecycle_over_real_ipc` (shared `run_mesh_lifecycle`, real runner) passes C/R/E/D/U/I/W/V/P with DWG and DXF reopen, re-edit, atomic rollback and three-step undo/redo. |
|
||||||
|
| Text | **Complete** | Exercised: `text`, `rotation`, `height`. Rejects a non-positive height (previously accepted), a non-positive width factor, non-finite placement and angles, and a zero normal. Style and alignment fields are mapped but not individually exercised. `audit_python_text_lifecycle_over_real_ipc` (shared `run_mesh_lifecycle`, real runner) passes C/R/E/D/U/I/W/V/P: creation, a two-or-more-property transaction edit with the entity's common data, identity and selection preserved, canvas wires, invalid-input rejection with an atomic multi-entity rollback, DWG and DXF reopen with re-edit, and three-step undo/redo. The audit added the shared `validate_basic_entity` (creation must be valid; an edit is refused only for problems it introduces, so already-invalid legacy values stay editable). |
|
||||||
|
| MText | **Complete** | Exercised: `text`, `rectangle_width`, `rotation`. Rejects a non-positive height (previously accepted), a negative width, non-finite placement, a non-positive line-spacing factor and a zero normal. Attachment, columns and background fields are mapped but not individually exercised. `audit_python_mtext_lifecycle_over_real_ipc` (shared `run_mesh_lifecycle`, real runner) passes C/R/E/D/U/I/W/V/P: creation, a two-or-more-property transaction edit with the entity's common data, identity and selection preserved, canvas wires, invalid-input rejection with an atomic multi-entity rollback, DWG and DXF reopen with re-edit, and three-step undo/redo. The audit added the shared `validate_basic_entity` (creation must be valid; an edit is refused only for problems it introduces, so already-invalid legacy values stay editable). |
|
||||||
|
| Ray | **Complete** | Exercised: `base_point`, `direction`. Unit-direction and finite-point validation already existed; the audit added the full DWG and DXF reopen and re-edit gate. `audit_python_ray_lifecycle_over_real_ipc` (shared `run_mesh_lifecycle`, real runner) passes C/R/E/D/U/I/W/V/P: creation, a two-or-more-property transaction edit with the entity's common data, identity and selection preserved, canvas wires, invalid-input rejection with an atomic multi-entity rollback, DWG and DXF reopen with re-edit, and three-step undo/redo. The audit added the shared `validate_basic_entity` (creation must be valid; an edit is refused only for problems it introduces, so already-invalid legacy values stay editable). |
|
||||||
|
| XLine | **Complete** | Exercised: `base_point`, `direction`. Same as Ray. `audit_python_xline_lifecycle_over_real_ipc` (shared `run_mesh_lifecycle`, real runner) passes C/R/E/D/U/I/W/V/P: creation, a two-or-more-property transaction edit with the entity's common data, identity and selection preserved, canvas wires, invalid-input rejection with an atomic multi-entity rollback, DWG and DXF reopen with re-edit, and three-step undo/redo. The audit added the shared `validate_basic_entity` (creation must be valid; an edit is refused only for problems it introduces, so already-invalid legacy values stay editable). |
|
||||||
|
| Solid | **Complete** | Exercised: `fourth_corner`, `thickness`. Finite corners, thickness and normal validation already existed; the audit added the full gate. `audit_python_solid_lifecycle_over_real_ipc` (shared `run_mesh_lifecycle`, real runner) passes C/R/E/D/U/I/W/V/P: creation, a two-or-more-property transaction edit with the entity's common data, identity and selection preserved, canvas wires, invalid-input rejection with an atomic multi-entity rollback, DWG and DXF reopen with re-edit, and three-step undo/redo. The audit added the shared `validate_basic_entity` (creation must be valid; an edit is refused only for problems it introduces, so already-invalid legacy values stay editable). |
|
||||||
|
| Face3D | **Complete** | Exercised: `third_corner`, `invisible_edges`. Finite corners and known edge bits validation already existed; the audit added the full gate. `audit_python_face3d_lifecycle_over_real_ipc` (shared `run_mesh_lifecycle`, real runner) passes C/R/E/D/U/I/W/V/P: creation, a two-or-more-property transaction edit with the entity's common data, identity and selection preserved, canvas wires, invalid-input rejection with an atomic multi-entity rollback, DWG and DXF reopen with re-edit, and three-step undo/redo. The audit added the shared `validate_basic_entity` (creation must be valid; an edit is refused only for problems it introduces, so already-invalid legacy values stay editable). |
|
||||||
|
| Insert | **Complete** | Decision (2026-09-20): Insert is creatable. A script names an existing block with `block_name` and a placement; the host does not generate attribute records, because attributes stay with the `AttributeEntity` flow that already creates them from the block's ATTDEFs. Writable: `block_name` (fixed after creation; the mutation check refuses a different block), `insert_point`, `x_scale`, `y_scale`, `z_scale`, `rotation`, `normal`, `column_count`, `row_count`, `column_spacing`, `row_spacing`. Creation and rename rules: the block must exist, must not be model or paper space, and must not make a block contain itself directly or through nested inserts; scales must be finite and nonzero, array counts positive, and the name non-empty. An edit that keeps the block name is exempt from the block checks so a legacy insert of a missing block stays editable. `audit_python_insert_lifecycle_over_real_ipc` (shared driver, host-made block) passes C/R/E/D/U/I/W/V/P: creation by block name, a six-property transaction edit, canvas wires, rejection of zero scale, non-finite rotation and point, zero array count, zero normal and an unknown block, an atomic rollback, DWG and DXF reopen with re-edit, and three-step undo/redo. `audit_python_insert_creation_rules_over_real_ipc` covers unknown block, model-space block, bad scale, zero count, empty name, direct self-insertion and indirect nesting cycles. Not covered: MINSERT (`dwg_minsert`) and attached-attribute creation, which stay excluded and preserved. |
|
||||||
|
| Tolerance | **Complete** | `staged_python_tolerance_lifecycle_over_real_ipc` passes C/R/E/D/U/I/W/V/P with the staged API v7 plugin: high-level create/read/transaction edit/delete; insertion, direction, and text edits; live canvas selection; grouped undo/redo; invalid direction and missing style atomic rollback; exact untouched common/style/private-field preservation; and edited DWG plus DXF reopen. Host-owned coverage exposes placement, direction, normal, text, style name, height and gap; style handle is read-only and the undocumented DWG short remains unmapped. `tolerance_geometry_and_style_references_are_validated` and the existing Tolerance tessellation tests cover reference and rendered-frame behavior. |
|
||||||
|
| Shape | **Complete** | `staged_python_shape_lifecycle_over_real_ipc` passes C/R/E/D/U/I/W/V/P with a generated parser-valid SHX file and a real shape-file `TextStyle`: high-level create/read/transaction edit/delete; insertion, size, rotation and width-factor edits; live canvas selection; grouped undo/redo; invalid size and missing style rollback; exact identity/style/common-field preservation; and DWG plus DXF reopen. Each live and reopened document renders the three-point SHX glyph rather than the placeholder. Host-owned reference binding writes the stable style handle needed by DWG. The DXF fallback now searches all `is_shape_file` styles, preserving named-style glyph resolution after reopen. |
|
||||||
|
| AttributeDefinition | **Integration-tested / blocked at W by acadrust (DXF ATTDEF reader)** | Host commit `5b854bd1` maps block ownership plus every stable ATTDEF field except the nested `embedded_mtext` payload, which is snapshot-readable and preserved untouched. Two staged tests cover it. `staged_python_attribute_definition_lifecycle_over_real_ipc` passes with a real block record, Block/BlockEnd markers and a linked Insert. The 2026-09-20 audit `audit_python_attribute_definition_lifecycle_over_real_ipc` (shared `run_mesh_lifecycle`, host-made block) compares **every writable field** through both formats: creation with non-default tag, prompt, value, placement, alignment point, height, rotation, width factor, oblique angle, alignments, all attribute flags, field length, generation flags and lock; a nine-property transaction edit; canvas wires; eight rejection cases (whitespace tag, non-positive height and width factor, missing style, owner change, zero normal, non-finite rotation, unknown alignment) plus an atomic rollback; DWG reopen with the **complete** edited state and re-edit; deletion; and three-step undo/redo. **W blocker, revalidated on acadrust `5b682ed`:** the DXF writer emits every ATTDEF group, but the reader handles only groups 1, 2, 3, 10, 40, 50, 280 and 101, so a DXF reopen keeps tag, prompt, value, insertion point, height and rotation and resets the alignment point, both alignments, width factor, oblique angle, all attribute flags (invisible, constant, verify, preset), field length, generation flags, lock and text style to defaults. This is now pinned by canary expectations for both the edit and the re-edit. Not `Complete` until the reader is extended; the fix belongs in cadcodec's `read_attdef`. `embedded_mtext` mutation remains unsupported pending linked-layout validation. |
|
||||||
|
| AttributeEntity | **Complete** | OCS commit `cf2a9235` and adapter commit `9c6b5c3` make nested ATTRIB records addressable by handle while retaining canonical storage in `Insert.attributes`. Host validation binds tag to a definition in the Insert's block, validates placement/text geometry and style references, keeps owner and definition handles read-only, and preserves embedded MTEXT. `staged_python_attribute_entity_lifecycle_over_real_ipc` passes C/R/E/D/U/I/W/V/P with a real block, ATTDEF and Insert: high-level create/read/transaction edit/delete, parent selection, rendered text, atomic invalid tag/height/owner rejection, edited and deleted DWG/DXF reopen, and three-step undo/redo. `nested_insert_attribute_crud_uses_parent_storage_and_undo` additionally proves the child never becomes an orphan flat entity in the host document. |
|
||||||
|
| Hatch | **Complete** | OCS commit `98b56ef6` and adapter commit `a9b5de8` expose solid and patterned Hatches with elevation/normal, complete pattern definitions, pattern controls, style, association state, boundary paths and seed points. Nested tagged boundary edges use the reusable `{kind, value}` adapter form. Host validation requires closed finite loops, validates line/arc/ellipse/polyline/spline payloads and stored pattern lines, resolves associative boundary handles, and preserves gradient and MPOLYGON payloads as explicitly unsupported. `staged_python_hatch_lifecycle_over_real_ipc` passes C/R/E/D/U/I/W/V/P: Python solid creation, patterned boundary edit, live render-model pattern/boundary checks, selection, atomic invalid scale/association/open-loop/unmapped-property rejection, edited and deleted DWG/DXF reopen, post-reopen edits, and three-step undo/redo. |
|
||||||
|
| Leader | **Integration-tested / blocked at W by acadrust** | Fields mapped writable: `vertices` (≥2 finite points, not all coincident), `annotation_handle`, `creation_type`, `path_type`, `dimension_style`, `arrow_enabled`, `hookline_enabled`, `hookline_direction`, `text_height`, `text_width`, `normal`, `horizontal_direction`, `block_offset`, `annotation_offset`. Read-only: `origin`, `dimension_gap`, `arrowhead_type`, `arrow_size`, `byblock_color`. `override_color` is writable through the new generator `Color` form (`{'kind': 'Rgb', 'value': {'r','g','b'}}`, `Index`, `ByLayer`, `ByBlock`, `None`). Unmapped but preserved on edit: the `dwg_unknown_*` fields. Host reference binding validates that `annotation_handle` exists, is not the leader itself, matches `creation_type` (Text/MText, Tolerance, Insert; `NoAnnotation` forbids a handle) and that `dimension_style` exists; nothing is silently defaulted. `staged_python_leader_lifecycle_over_real_ipc` passes C/R/E/D/U/I/V/P against acadrust `7ea4247`: linked Text annotation, path/height/arrow/offset transaction edit with untouched-field preservation, GUI pick grouping (scripted selection stays exact), seven single-edit rejections plus a cross-entity atomic rollback, four-step undo/redo, real render linework, DWG and DXF reopen and re-edit. Erasing a leader also erases its annotation (scene leader grouping); undo restores both. **W blockers (engine, recorded as canary assertions in the test):** (1) the DXF writer never emits group 340, so a DXF save unlinks the annotation; (2) DXF reads drop `annotation_offset` (group 213 is written but not reassembled); (3) DWG R2010+ does not store `text_height`, `text_width` or `hookline_enabled` (acadrust writes them only for R13–R2007 / R13–R14); (4) neither writer stores `override_color`, so it reopens as `ByLayer` in DWG and DXF. Not `Complete` until the engine round-trips (1) and (2); (3) needs a decision to document or make read-only. |
|
||||||
|
| MLine | **Complete** | Writable: `vertices` (raw vertex dicts; a script may pass only `position`), `flags` (integer, unknown bits rejected), `justification`, `normal`, `scale_factor`, `style_name`. Read-only: `start_point`, `style_handle`, `style_element_count`. Host validation requires ≥2 finite non-coincident vertices, ≥3 for a closed multiline, a finite nonzero scale and normal, an existing non-empty `MLineStyle`, and per-vertex segments that are either empty or match the style element count. Vertex `direction`/`miter`, segment layout and per-element miter offsets (justification and scale included) are host-derived by `normalize_scripted_mline` on every scripted create or edit, reusing the drawing command's `rebuild_mline_geometry`/`sync_mline_element_parameters`; dash and fill cuts survive an edit unless a vertex moves. `staged_python_mline_lifecycle_over_real_ipc` passes C/R/E/D/U/I/W/V/P: create against the Standard style, a three-vertex/scale/justification transaction edit with untouched-field preservation, corner miter widening and element offsets checked, real `mline_lines` linework before and after DWG and DXF reopen, nine single-edit rejections plus a cross-entity atomic rollback, re-edit after reopen in both formats, deletion, and three-step undo/redo. Known limit: switching to a style with a different element count is rejected until the script also clears the vertices' `segments`; only the rejection is covered by the integration test. |
|
||||||
|
| Dimension | **Complete** (all 9 subtypes) | `EntityType::Dimension` wraps a nine-variant enum, so the adapter uses a hand-written flat model (`dimension_model.rs.inc`, wired in through the manifest's `manual_kinds`) and the coverage catalog lists its properties through the policy's `synthetic` section. Python sees `subtype` (fixed at creation), the shared base fields (`text`, `style_name`, `normal`, `text_middle_point`, `attachment_point`, `text_rotation`, `horizontal_direction`, `flip_arrow1/2`, `text_user_positioned`) and only the fields of that subtype; a field from another subtype is rejected, not ignored. `actual_measurement` and the base definition point are host-derived (`normalize_scripted_dimension`, the same recompute grip edits use). Unmapped but preserved: `user_text`, `insertion_point`, `block_name`, version and DWG flags, style overrides in XDATA. Per-subtype status, all verified by `staged_python_dimension_lifecycle_over_real_ipc` (C/R/E/D/U/I/W/V/P; measurement and canvas wires checked for each, DWG and DXF reopen recorded per subtype): Linear (10), Aligned (5), Radius (5), Diameter (10), Angular3Pt (90°), Angular2Ln (90°), Ordinate (5), Arc (5·π/2), LargeRadial (6) — every one creates, reads, derives the right measurement, renders wires, and keeps its measurement through DWG and DXF. Edits (Linear second point/text/attachment, Radius definition point) update the measurement, nine rejection cases plus a cross-entity atomic rollback and three create-time rejections leave the document untouched, and post-reopen re-edit passes in both formats. Not covered: text formatting overrides, arrowheads and other DIMSTYLE overrides stored in XDATA, the anonymous `*D` block. The subtype-specific field meanings for the angular subtypes follow the DXF group-code layout rather than the acadrust convenience constructors. |
|
||||||
|
| MultiLeader | **Complete** | Mapped through the generic generator, which gained support for `Color`, `LineWeight`, mixed unit/payload enums, fixed `[f64; N]` arrays, bitflags-2 newtypes and per-type module paths for this kind. Writable: `content_type`, `path_type`, `line_color`, `line_weight`, `enable_landing`, `enable_dogleg`, `dogleg_length`, `arrowhead_size`, `text_color`, `text_frame`, the four text attachments, attachment direction/point, `text_alignment`, `text_angle_type`, `text_direction_negative`, `scale_factor`, `enable_annotation_scale`, `extend_leader_to_text`, block content fields, the reference handles (`style_handle`, `text_style_handle`, `arrowhead_handle`, `line_type_handle`, `block_content_handle`) and `context`, which merges as a patch so a script can change `text_string` without resetting leader roots. Read-only: `dwg_version`, `property_override_flags`, `text_align_in_ipe` and the entity-level `text_height` (neither writer stores it; set `context.text_height`). Excluded but preserved: `arrowhead_overrides`, `block_attributes`. Host validation checks finite/positive scale, height, dogleg and arrow sizes, finite context geometry and transform, non-empty leader lines, content-type/context consistency, and that every referenced handle exists as the right object kind. `staged_python_multileader_lifecycle_over_real_ipc` passes C/R/E/D/U/I/W/V/P: MText creation with a three-point leader root, a partial-context edit that replaces the path (four points), text, text location, dogleg and colour while preserving scale/content/common fields, canvas wires, eleven rejection cases plus a duplicate-handle atomic rollback, DWG and DXF reopen (text, path, dogleg, `context.text_height`, colour) with post-reopen re-edit, and three-step undo/redo. Not covered: block-content MultiLeaders (no block fixture yet), tolerance content, and style-defined defaults. |
|
||||||
|
| Table | **Complete** | Mapped through the generic generator (now also handling tuples and `usize`, with the generic `LegacyBorderOverrides<T>` fields excluded and preserved). Writable: `insertion_point`, `horizontal_direction`, `normal`, `table_style_handle`, `rows`, `columns`, `merged_ranges`, `break_spacing`, `break_flow_direction`, `break_options`. Read-only: `block_name`, `block_record_handle`, `data_version`, `value_flags`, the override flags, `name`, `description`, `field_handles`, `base_style`, `break_data`, `break_ranges`, `legacy_style_override`. Creation yields the engine default 3x3 grid; scripts read `rows`/`columns`, modify or extend them and assign them back (rows and columns replace wholesale, so copy an existing row dict when adding one). Host validation requires a non-empty grid, positive finite row heights and column widths, every row to have exactly one cell per column, finite cell and content geometry, merged ranges inside the grid and non-overlapping, and existing table-style, cell text-style and cell block handles. `normalize_scripted_table` mirrors `merged_ranges` onto the origin cell's `merge_width/height` on every scripted change to the ranges. `staged_python_table_lifecycle_over_real_ipc` passes C/R/E/D/U/I/W/V/P: default-grid creation, a row append, column-width edit, a text cell, a three-column merge and break spacing in one transaction with untouched rows/columns/style/common fields preserved, canvas wires, ten rejection cases plus an atomic rollback, DWG and DXF reopen (row count, width, cell text, insertion) with re-edit, and three-step undo/redo. Format notes: DWG restores `merged_ranges` but not per-cell merge dimensions; DXF restores the cell dimensions but its reader does not rebuild `merged_ranges` (recorded by a canary assertion); both keep the merge. Not covered: the anonymous table block is not regenerated, cell styles and formats beyond text, linked data and field content. |
|
||||||
|
| PolygonMesh | **Complete** | Writable: `flags`, `m_vertex_count`, `n_vertex_count`, `m_smooth_density`, `n_smooth_density`, `smooth_type`, `elevation`, `normal`, `vertices` (each `{location, flags}`; a vertex's own common data is not scripted and defaults). Host validation requires M and N of at least 2, exactly M×N vertices, non-negative densities, finite elevation and locations, and a nonzero normal, so inconsistent counts are refused before any mutation. `staged_python_polygon_mesh_lifecycle_over_real_ipc` (shared `run_mesh_lifecycle`) passes C/R/E/D/U/I/W/V/P: a 3×3 grid, a vertex move plus density and cubic smoothing in one transaction, canvas wires, seven rejection cases plus an atomic rollback, DWG and DXF reopen with re-edit, and three-step undo/redo. |
|
||||||
|
| PolyfaceMesh | **Complete** | Writable: `elevation`, `flags`, `normal`, `start_width`, `end_width`, `smooth_surface`, `thickness`, `vertices` (location, flags, bulge, widths, tangent, id) and `faces` (four indices, flags, optional colour). `seqend_handle` is read-only and preserved. Host validation requires at least 3 finite vertices and 1 face, every face index within the vertex count (a negative index hides that edge, 0 marks an unused corner), at least 3 indices per face, and finite widths, thickness and elevation. `staged_python_polyface_mesh_lifecycle_over_real_ipc` passes the full gate: two triangles, a vertex move plus a new vertex and a hidden-edge face in one transaction, canvas wires, six rejection cases plus an atomic rollback, DWG and DXF reopen with re-edit, and three-step undo/redo. |
|
||||||
|
| Mesh | **Complete** | Writable: `blend_crease`, `subdivision_level`, `vertices`, `faces`, `edges` (start, end, optional crease), `override_option`; `version` is read-only. Host validation requires at least 3 finite vertices, faces of at least 3 in-range indices, edges with distinct in-range endpoints and a finite non-negative crease, and a non-negative subdivision level, so out-of-range topology is rejected before mutation. `staged_python_mesh_lifecycle_over_real_ipc` passes the full gate: a quad with a creased edge, an added vertex and triangle plus subdivision level 1 in one transaction, canvas wires, seven rejection cases plus an atomic rollback, DWG and DXF reopen with re-edit, and three-step undo/redo. |
|
||||||
|
| Helix | **Integration-tested / blocked at W by acadrust (DXF handedness)** | Writable generating parameters: `axis_base_point`, `start_point`, `axis_vector`, `radius` (the top radius; the base radius is the start point's distance from the axis), `turns`, `turn_height`, `handedness`, `constraint`. Read-only: `spline`, `major_version`, `maintenance_version`. The host rebuilds the derived NURBS spline with OCS's own helix builder on every scripted create or parameter edit (`normalize_scripted_helix`), so the spline always matches the parameters. Host validation requires finite positive radius, turns and turn height, a nonzero axis and a start point off the axis. `staged_python_helix_lifecycle_over_real_ipc` (shared `run_mesh_lifecycle`) passes C/R/E/D/U/I/V/P: creation with a derived spline ending at z = turns × turn height, a turns and handedness edit that regenerates it, canvas wires, seven rejection cases plus an atomic rollback, DWG reopen and re-edit, DXF reopen and re-edit, and three-step undo/redo. **W blocker (engine, pinned by a canary assertion):** the DXF reader parses boolean group 290 as an `i16` and never applies it, so a clockwise helix reopens counter-clockwise from DXF while DWG keeps it. Not `Complete` until the reader is fixed. |
|
||||||
|
| RasterImage | **Integration-tested** | Writable: `file_path` (creation only; a later change is rejected because the image definition owns it), `insertion_point`, `u_vector`, `v_vector` (world units per pixel), `flags`, `clipping_enabled`, `brightness`, `contrast`, `fade`, `clip_boundary`. Read-only: `size` (pixel size, taken from the file), `class_version`, `definition_handle`, `definition_reactor_handle`. Creating from a script requires a readable image file: the host reads its pixel size, creates the `ImageDefinition` object, links it, and sets `size` and a whole-image clip boundary from the file. Host validation requires finite, non-parallel `u`/`v` vectors, brightness/contrast/fade within 0..=100, known display flags, finite clip vertices, at least 2 clip vertices when clipping is enabled, and an existing definition. `staged_python_raster_image_lifecycle_over_real_ipc` (shared `run_mesh_lifecycle`, real PNG fixture) passes C/R/E/D/U/I/W/V/P inside OCS: creation with a host-made definition, placement/scale/brightness/contrast/fade and clip edit in one transaction, canvas wires, eight rejection cases plus an atomic rollback, DWG and DXF reopen with the definition link and file path intact, re-edit, and three-step undo/redo. **Linkage (updated 2026-09-20):** a scripted image now reuses one `ImageDefinition` per file and registers each definition in `ACAD_IMAGE_DICT` under the file's name (a `_2`, `_3` suffix keeps keys unique), creating that dictionary under the root when the drawing has none, and the dictionary owns the definition, as for an image AutoCAD attached. `audit_python_raster_image_definition_linkage_over_real_ipc` checks two images of one file sharing a definition, a third file getting its own, the entries resolving with the right owner, and all of it surviving DWG and DXF reopen and an undo without a dangling entry. **Why not `Complete`:** the host still writes no `IMAGEDEF_REACTOR`: cadcodec's struct documents the reactor's owner as the definition while its DXF writer follows a different convention, and AutoCAD's behavior cannot be checked here, so guessing risks a structure AutoCAD repairs or rejects. **Related finding:** OCS's own IMAGE command creates a bare `RasterImage` with no definition, and a save through either writer drops its file path (`spike_raster_image_definition_persistence`), while the definition-linked form keeps it. Editing an existing definition (file path, resolution) is out of scope. |
|
||||||
|
| Wipeout | **Complete** | Writable: `insertion_point`, `u_vector`, `v_vector` (the region's world extent), `size`, `flags`, `clipping_enabled`, `brightness`, `contrast`, `fade`, `clip_mode`, `clip_type` and `clip_boundary_vertices` (normalized image coordinates, -0.5..0.5). Read-only: `class_version`, `definition_handle`, `definition_reactor_handle`. Scripted creation matches OCS's native WIPEOUT command, which also leaves the definition link unset. Host validation requires finite non-parallel `u`/`v` vectors, a positive `size`, brightness/contrast/fade within 0..=100, known flags, finite clip vertices, exactly 2 vertices for a rectangular clip and at least 3 for a polygonal one. `staged_python_wipeout_lifecycle_over_real_ipc` (shared `run_mesh_lifecycle`) passes C/R/E/D/U/I/W/V/P: rectangular creation, a switch to a three-vertex polygonal inside-clip with a move in one transaction, canvas wires, eight rejection cases plus an atomic rollback, DWG and DXF reopen with re-edit, and three-step undo/redo. |
|
||||||
|
| Underlay | **Integration-tested / blocked at W by acadrust (DXF rotation units)** | Writable: `underlay_type` and `definition_handle` (both fixed by the definition: creation names an existing `UnderlayDefinition`, and a mismatched type or missing definition is rejected), `insertion_point`, `x_scale`, `y_scale`, `z_scale`, `rotation`, `normal`, `flags`, `contrast`, `fade`, `clip_boundary_vertices`, `clip_inverted`. The file path and page live on the definition object, which scripts cannot create or list yet; they reference one the drawing already owns. Host validation requires finite nonzero scales, a finite rotation, a nonzero normal, contrast/fade within 0..=100, known flags, finite clip vertices (none, or at least 2) and an existing definition of the same type. `staged_python_underlay_lifecycle_over_real_ipc` (shared `run_mesh_lifecycle` with a fixture PDF definition) passes C/R/E/D/U/I/V/P and DWG W: creation, a placement/scale/rotation/contrast/fade/clip transaction, canvas wires, eight rejection cases plus an atomic rollback, DWG reopen and re-edit, and three-step undo/redo. **W blocker (engine, pinned by canary assertions):** DXF stores the rotation in degrees but the reader returns it unconverted, so 0.5 rad reopens as 28.6 and each further DXF save-reopen compounds it (1641.4 after a second), silently corrupting the rotation. Not `Complete` until the reader converts degrees back to radians. Not covered: creating definitions from a file path, DWF/DGN fixtures. |
|
||||||
|
| Viewport | **Complete (OCS round trip)** | Writable: `center`, `width`, `height`, `status`, `view_center`, `view_direction`, `view_target`, `lens_length`, `front_clip_z`, `back_clip_z`, `view_height`, `twist_angle`, `frozen_layers` (layer handles), `render_mode`, `circle_sides`, `ucs_icon_visible`. Read-only: `id`, `custom_scale`, snap and grid settings, UCS fields, `clip_boundary_handle`, `style_sheet`, shade-plot, background, visual-style and sun handles, lighting, `ambient_color`, `elevation`. Reference rules: the owner must be a paper-space layout block and every frozen-layer handle an existing layer. **Derived by the host (new 2026-09-20), as the MVIEW command does:** a scripted viewport gets an `id` unique in its layout and at least 2 (max existing plus one), and `custom_scale` is `height / view_height`, recomputed whenever either changes, so `custom_scale` is now read-only (setting the scale directly would have let it drift from the geometry). Host validation requires finite centers, positive width, height, view height, lens length and scale, a nonzero view direction, finite clip planes and twist, and at least 3 circle sides. **Canvas oracle (new):** the shared driver now activates the layout that owns the viewport (`Scene::set_current_layout`) and requires the viewport to draw a frame both after creation and after the edit. `staged_python_viewport_lifecycle_over_real_ipc` passes C/R/E/D/U/I/V/W/P: creation in the paper-space block, a move/resize/view-height/twist/frozen-layer transaction, seven rejection cases plus an atomic rollback, DWG and DXF reopen with re-edit, and three-step undo/redo. `audit_python_viewport_ids_and_scale_over_real_ipc` checks unique ids (2, 3, 4), the derived scale on create and after a zoom and a resize, an id kept across edits, a rejected direct `custom_scale` write, and that every viewport draws a frame. A control showed that the engine default id 0 is **not** invisible in a layout with no sheet viewport (it draws a frame), which corrects an earlier suspicion; the derived id matters for uniqueness. Not covered: clip boundary entities (`clip_boundary_handle` is read-only and preserved), non-rectangular viewports, and AutoCAD acceptance of the written viewports, which cannot be tested here. |
|
||||||
|
| ViewBorder | **Integration-tested / blocked at W by acadrust (DXF kind)** | Writable: `min`, `max`, `center` (2-D pairs), `scale`, `rotation_angle`, `active_viewport` and `scale_handle` (both required at creation). `version` is read-only. Reference rules: `active_viewport` must be an existing Viewport entity and `scale_handle` an existing `Scale` object. Host validation requires finite bounds with `min` below `max` on both axes, a positive scale and a finite rotation. `staged_python_view_border_lifecycle_over_real_ipc` (shared `run_mesh_lifecycle`, driver-made viewport and scale fixtures) passes C/R/E/D/U/I/V/P and DWG W: creation, a resize/recenter/scale/rotation transaction, canvas wires, seven rejection cases plus an atomic rollback, DWG reopen and re-edit, and three-step undo/redo. **W blocker (engine, pinned by a canary):** a DXF `DRAWINGVIEW` reopens as a different, opaque entity kind rather than as a ViewBorder, so only DWG restores the typed record. Not `Complete` until DXF loading restores the typed entity. Not covered: the linked view representation and drawing-view definition records. |
|
||||||
|
| SectionSymbol | **Integration-tested / blocked at W by cadcodec (DXF SECTIONLINE)** | The earlier blocker was overstated, and reading cadcodec and OCS showed why. cadcodec documents `points` as the canonical geometry, says the point-count fields equal the point count in every verified ODA export, and ships `sync_display_fields()` to refresh the `end_a`/`end_b`/`tick_a`/`tick_b`/`label` projections; OCS's own grip and transform code already calls it. OCS also renders a symbol with no style and no view link. So the kind is mapped: writable `points` (each `{point, bulge, label, label_offset, raw_flag_280}`), `symbol_scale`, `style_handle` and `view_rep_handle`; read-only `view_symbol_version`, `raw_view_symbol_70`, `version`, `raw_flags_90`, the two derived counts and the five projections. The host sets `raw_point_count_90` and `raw_point_record_count` to the point count and calls `sync_display_fields()` whenever `points` is created or changed, and leaves a symbol whose points did not change exactly as read. Host validation requires at least two finite points with finite bulges and label offsets, a positive scale, and that each non-null reference is an existing `SectionViewStyle` (style) or `ViewRep` (view representation) class object; the wrong object kind is refused. Creating one without references gives a standalone symbol. `audit_python_section_symbol_lifecycle_over_real_ipc` (shared driver) passes C/R/E/D/U/I/V/P and DWG W: a two-point symbol, a three-point edit with a new label, bulge and scale in one transaction (counts and projections follow), canvas wires, seven rejection cases plus an atomic rollback, DWG reopen and re-edit, three-step undo/redo. `audit_python_section_symbol_references_over_real_ipc` covers valid references, a standalone symbol and four wrong-object refusals with host-made class objects. **W blocker (cadcodec, pinned by a canary; issue 5 in [cadcodec-reader-gaps.md](cadcodec-reader-gaps.md)):** the DXF reader dispatches `SECTIONLINE` only inside blocks, so a symbol in the drawing's entity list reopens as an `Unknown` entity. Open items that cannot be checked here: `raw_flags_90` has unknown semantics (0 for a new symbol, preserved on read), and whether AutoCAD accepts a symbol with no parent view. Scripts cannot create the style or view-representation objects. |
|
||||||
|
| Light | **Integration-tested / blocked at W by acadrust (DXF `cast_shadows`)** | Writable: `name`, `light_type` (1 distant, 2 point, 3 spot), `position`, `target`, `status`, `light_color`, `plot_glyph`, `intensity`, the attenuation type and limits, `hotspot_angle`, `falloff_angle`, `cast_shadows`, `shadow_type`, `shadow_map_size`, `shadow_map_softness`, `photometric_mode`, `photometric_data`; `class_version` is read-only. Host validation requires a non-empty name, a known light type, finite placement, a spot or distant target that differs from the position, non-negative intensity, angles and limits, an attenuation start not above its end, a spot hotspot not above its falloff, and a non-negative shadow map size. `staged_python_light_lifecycle_over_real_ipc` (shared `run_mesh_lifecycle`) passes C/R/E/D/U/I/V/P and DWG W: a spot light with an RGB colour, an intensity/target/position/shadow transaction that preserves the colour and untouched fields, the canvas glyph, eight rejection cases plus an atomic rollback, DWG reopen and re-edit, and three-step undo/redo. **W blocker (engine, pinned by a canary):** the DXF reader does not restore `cast_shadows`, which reopens false; colour, placement and intensity persist. Not covered: photometric web data edits and sun/skylight objects. |
|
||||||
|
| Region | **Complete (create from a profile + rigid move)** | New `SolidOperation::RegionFromProfile` and `doc.solids.region(profile, layer=None, delete_source=False)`. The host builds the region exactly as the REGION command does (`presspull_model::profile_geometry` then `cadkernel::brep::planar_region`), verifies it with `solid_to_sat`, puts it on `layer` or on the profile's layer, and erases the profile only when `delete_source` is set. One closed planar profile per call (a circle, ellipse, closed polyline, spline and so on); an open profile, a ray, a region, a missing entity or an empty layer is refused with a message before anything changes. Rigid moves go through the same `doc.solids.transform` channel as Solid3D. `audit_python_region_lifecycle_over_real_ipc` passes C/R/E/D/U/I/W/V/P through the real runner: regions from a circle (source kept), a closed rectangle (source deleted) and a second circle on its own layer with exact extents, canvas geometry, six refusals that change nothing and record no undo step, a move with the exact shifted extent, DWG and DXF reopen with the payload lifting and the same extent, a reopened region moving again, and undo restoring the region exactly. Not covered: regions with holes and merging open curves into a boundary (the REGION command's second path), and AutoCAD acceptance of the payload. |
|
||||||
|
| Body | **Integration-tested (rigid move only)** | Mapped read-only like Solid3D (same payload container). `audit_python_body_transform_over_real_ipc` moves a Body carrying a kernel box through `doc.solids.translate`, checks the exact extent, DWG reopen with a losslessly lifting payload and the exact volume, and the explanatory refusal of `create_entity('Body')`. Scripts cannot create a Body, and a non-solid (sheet or wire) body that does not lift is refused untouched. |
|
||||||
|
| Solid3D | **Complete (create + rigid move)** | New in this session: an additive `HostApi::solid_operation` (`SolidOperation::Create` and `Transform`, plus a `SolidPrimitive` enum) carried by `PluginRequest::SolidOperation` / `PluginResponse::SolidResult` through both IPC clients, the server and `HostSession`, and a Python `doc.solids` API: `box`, `wedge`, `cylinder`, `sphere`, `torus`, `pyramid`, `transform`, `translate`, `rotate`, `mirror`. The host builds bodies with cadkernel, and every result goes through `solid_to_sat`, which lifts its own output back and refuses anything lossy. A transform first lifts the existing payload with `kernel_acis_body` and is refused, leaving the payload untouched, when that is lossy. Only rigid moves and mirrors are accepted (scaling and shear are refused). Regenerated `wires` follow the body, `silhouettes` are cleared and `history_handle` is dropped. Python sees `uid`, `point_of_reference` and `history_handle` read-only; `acis_data`, `wires` and `silhouettes` are excluded and preserved; creation through `create_entity` is refused with a message pointing at `doc.solids`. `audit_python_solid3d_lifecycle_over_real_ipc` passes C/R/E/D/U/I/W/V/P through the real runner with the kernel as oracle: all six primitives match their analytic volumes (box, wedge and cube exactly, curved solids within 2 percent of the tessellated volume), a translate, a rotate and a mirror keep the volume and move the extent exactly and keep 12 edge wires, 13 refusals (zero and non-finite sizes, a torus with minor above major, too few pyramid sides, an empty layer, an unknown primitive, a wrong number count, a scaling matrix, a non-finite offset, a payload the kernel cannot lift, a missing entity) change nothing and leave no undo step, DWG and DXF reopen with the payload lifting losslessly and the same volume and extent, a reopened payload moves again, and undo restores the original solid exactly. Not covered: solids that carry parametric history, and AutoCAD acceptance of the written payload, which cannot be tested here. **Booleans** (`SolidOperation::Boolean`, `doc.solids.union`, `subtract` and `intersect`) are covered by `audit_python_boolean_lifecycle_over_real_ipc`: two overlapping boxes give exact volumes (union 360, subtract and intersect 120) and extents, the operands are consumed unless `keep_operands` (undo restores both exactly), a result takes the first operand's layer or an explicit one, a second planar operation chains on the result (a through-hole gives 104), eight refusals change nothing and record no undo step (same operand twice, a non-solid, a missing entity, an unliftable payload, an empty layer, an unknown operation, a disjoint intersection), and DWG and DXF reopen losslessly with a reopened result moving again. The kernel refuses many curved cases (measured in release: about 1 to 2 s when it succeeds, and `Coincident`, `CutRefused` or `NoClosedForm` when it does not, including a second cut in a drilled box); its reason reaches the script and nothing changes, shown by an `#[ignore]` curved test that takes about 27 s in a debug build. Booleans block the host thread and count against the script's 30 s budget; only Solid3D operands are accepted. |
|
||||||
|
| Surface | **Complete (plane surface, extruded open profile, isolines, rigid move)** | New `SolidOperation::SurfaceFromProfile` and `SolidOperation::Extrude`, exposed as `doc.solids.surface(profile)` and `doc.solids.extrude(profile, direction)`. A closed planar profile becomes a `Plane` surface (built as the region body, so it keeps the plane kind); a profile extruded along a nonzero direction becomes a Solid3D when it is closed and a generic Surface when it is open, using OCS's own `extrusion_body`. Every payload is verified lossless by `solid_to_sat`, and rigid moves (now accepted for surfaces too) keep a plane a plane and turn any other kind generic, as OCS does after an edit. Python sees `surface_kind`, `modeler_format_version`, `point_of_reference` and `history_handle` read-only and `u_isolines` and `v_isolines` writable (0 to 200); the payload, wires, silhouettes and the kind-specific `surface_data` are excluded and preserved. The kind field is exposed as `surface_kind` because a bare `kind` key names the entity type in every Python dict; the new `exposed_property_names_are_unique_per_kind` test guards against that class of collision. `audit_python_surface_lifecycle_over_real_ipc` passes C/R/E/D/U/I/W/V/P through the real runner: two plane surfaces (one on its own layer), a surface from an open polyline extrusion, three extruded solids checked against their analytic volumes (a box exactly, curved ones within 2 percent), `delete_source` erasing only the intended profile, canvas geometry, nine refusals that change nothing and record no undo step, an isoline transaction with four rejections (500, negative, the read-only kind, an excluded key), moves with exact extents, DWG and DXF reopen with lifting payloads, matching extents, kept isolines and the plane kind, a reopened surface moving again, and exact undo. Not covered: lofted, revolved, swept and NURBS surfaces (a script cannot create them; an existing one is preserved and turns generic on a move), parametric history, and AutoCAD acceptance. |
|
||||||
|
| Ole2Frame | **Complete** | Writable: `upper_left_corner`, `lower_right_corner`, `lock_aspect`, `is_paper_space`. Read-only: `version`, `source_application`, `ole_object_type`, `dwg_mode`. The embedded object `storage` and the frame `envelope` are opaque, excluded from the Python form, refused by the mutation check (`Ole2Frame embedded storage cannot change`) and preserved untouched. **Creation (new 2026-09-20):** `SolidOperation::EmbedPicture` and `doc.embed_picture(path, origin=(0, 0, 0), width=1, layer=None)` build a frame from a picture file with OCS's own `EmbeddedImage::from_file` and `build_embedded_ole`: PNG, JPEG and BMP are stored as read, any other format (a TIFF in the test) is re-encoded as PNG, `origin` is the bottom-left corner, `width` the frame width, and the height follows the picture's aspect. The generic `create_entity('Ole2Frame')` is refused with a message pointing at `doc.embed_picture`. Host validation requires finite corners spanning a nonzero size and `lock_aspect` of 0 or 1 for edits, and for creation a readable picture, a finite origin, a positive width and a non-empty layer. `audit_python_ole2frame_lifecycle_over_real_ipc` (shared driver) passes C/R/E/D/U/I/W/V/P through the real runner: creation from a PNG, a corner and aspect-lock transaction, canvas geometry, five rejection cases (including an attempt to write `storage`), an atomic rollback, **DWG and DXF reopen with the 119-byte embedded picture byte-for-byte intact (extracted through `extract_presentation`)**, re-edit, and three-step undo/redo. `audit_python_ole2frame_creation_rules_over_real_ipc` checks that PNG and JPEG are stored byte-for-byte, a TIFF becomes a PNG, the frame keeps the picture's 2:1 aspect with the requested origin and layer, and seven refusals (missing file, a non-image, empty layer, zero width, non-finite origin, a short origin list, and generic creation) change nothing and record no undo step. Not covered: OLE objects that are not pictures, and AutoCAD acceptance of the written frame, which cannot be tested here. |
|
||||||
|
|
||||||
|
After each increment, update the row with test names, fixture paths, exact
|
||||||
|
passing commands, the OCS commit hash, and any manual GUI result. Host and
|
||||||
|
adapter changes now share the same repository commit. If a gate is untested,
|
||||||
|
leave it pending. Do not raise the headline completion count from converter
|
||||||
|
coverage alone.
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
# Scripting host model (API v7)
|
||||||
|
|
||||||
|
This note describes how a script controls OCS and what the host guarantees. The
|
||||||
|
per-kind evidence is in the [coverage ledger](plugin-host-model-coverage-ledger.md),
|
||||||
|
the increment-by-increment record in the [completion plan](plugin-host-model-completion-plan.md),
|
||||||
|
and the script-facing reference in `plugins/opencad-python/PLUGIN.md`. A reviewer new to
|
||||||
|
the change should start with the [review guide](plugin-host-review-guide.md).
|
||||||
|
|
||||||
|
## Shape
|
||||||
|
|
||||||
|
Python runs in RustPython inside a separate plugin process
|
||||||
|
(`plugins/opencad-python`), so a script cannot crash the editor. It talks to the
|
||||||
|
host over the versioned IPC in `crates/ocs_plugin_api`. **The host owns the
|
||||||
|
drawing**: it validates every request, records the undo step, refreshes scene
|
||||||
|
caches and the shared document view, and marks the document dirty. The Python
|
||||||
|
adapter is thin: it turns dictionaries into typed values and back, and holds no
|
||||||
|
CAD rules of its own. Everything below is additive to API v7; a plugin built
|
||||||
|
without it keeps working, and the default `HostApi` methods refuse.
|
||||||
|
|
||||||
|
## What the host offers
|
||||||
|
|
||||||
|
| Area | `HostApi` entry | What it does |
|
||||||
|
|---|---|---|
|
||||||
|
| Read | `document()`, `entity_snapshot` | The full `CadDocument` snapshot; a detached JSON view of any typed entity. |
|
||||||
|
| Entities | `add_entity`, `remove_entity`, `update_entities_transaction` | Create, delete and replace entities. A transaction validates every replacement first and either commits all of them as one undo step or none. |
|
||||||
|
| Selection | `selection`, `set_selection` | Ordered, tab-scoped, exact (missing or duplicate handles reject the request). |
|
||||||
|
| Solids | `solid_operation` | Kernel-backed create, transform, booleans, extrude, region and surface from a profile, picture embedding. Every result is verified to lift back from its ACIS payload without loss; a refusal leaves the operands untouched. |
|
||||||
|
| Tables | `table_operation` | Layers, text and dimension styles, blocks and their contents, linetypes, layouts (see below). |
|
||||||
|
| Commands | `run_command` | Drives the real OCS command one step at a time (see below). |
|
||||||
|
| Settings | `system_variable`, `set_system_variable` | `CLAYER`, `SNAPANG`, and a read-only `CTAB` (the current layout). |
|
||||||
|
|
||||||
|
Entity kinds outside a generated schema still read (handle, kind, layer) and take
|
||||||
|
`layer` changes; nothing is writable that the host has not validated.
|
||||||
|
|
||||||
|
## Entity validation
|
||||||
|
|
||||||
|
The host embeds a coverage catalog generated from its traced `EntityType`
|
||||||
|
registry and `crates/ocs_plugin_api/entity_coverage_policy.json`. It classifies all
|
||||||
|
48 variants: 43 canvas kinds, three internal records (`Block`, `BlockEnd`,
|
||||||
|
`Seqend`) and two opaque fallbacks (`Extended`, `Unknown`), and records for each
|
||||||
|
property its source field, type, shape, snapshot readability, Python access
|
||||||
|
(`read_write`, `read_only`, `unmapped`) and validation status.
|
||||||
|
|
||||||
|
Creation and edits are validated per kind (finite coordinates, positive radii and
|
||||||
|
scales, unit directions, non-parallel vectors, in-range flags, reference targets
|
||||||
|
that exist and have the right kind, and so on). Creation must be valid; an edit
|
||||||
|
is refused only for problems it introduces, so already-invalid legacy values stay
|
||||||
|
editable. Derived state is computed by the host, never trusted from a script (MLine
|
||||||
|
geometry, Dimension measurement, Helix spline, Table merge dimensions, Spline
|
||||||
|
rational flag, SectionSymbol counts, Viewport id and scale).
|
||||||
|
|
||||||
|
Nested records are checked too. A dictionary for a vertex, edge or face may not
|
||||||
|
carry an unknown key, and the fields that define its geometry are required
|
||||||
|
(`entity_manifest.json`, `required_struct_fields`); a typo can no longer turn into
|
||||||
|
a zero coordinate. Everything else in a nested record defaults when absent.
|
||||||
|
|
||||||
|
Every kind is exercised through the real plugin runner by a per-kind audit that
|
||||||
|
checks create, read, edit, delete, undo, invalid input with an atomic rollback,
|
||||||
|
and a DWG and DXF round trip. A kind is `Complete` in the ledger only when all of
|
||||||
|
those pass.
|
||||||
|
|
||||||
|
## Tables
|
||||||
|
|
||||||
|
`TableOperation` is one additive request with typed variants, executed by
|
||||||
|
`HostSession::table_operation`. Every refusal is decided **before** the undo step is
|
||||||
|
recorded, so a failure changes nothing and leaves the history alone.
|
||||||
|
|
||||||
|
- **Layers:** create, modify, rename (entities follow), delete (refused while it
|
||||||
|
holds objects unless erasing them is asked for), set current. Layer `0`,
|
||||||
|
`Defpoints` and the current layer are protected.
|
||||||
|
- **Text and dimension styles:** create, modify, rename, delete, set current. Dimension
|
||||||
|
style fields travel as a validated JSON object; handles, xref fields and the name are
|
||||||
|
host-managed. Renaming a text style updates the dimension styles that name it.
|
||||||
|
`Standard` and any style that is current or in use are protected.
|
||||||
|
- **Blocks:** create from entities (copied in shifted by the base point, optionally
|
||||||
|
erasing the originals), modify, rename (inserts follow), delete (refused while
|
||||||
|
referenced), and add an entity to a definition through the normal validation path.
|
||||||
|
A block may not nest itself, directly or through other blocks.
|
||||||
|
- **Linetypes:** simple dash, gap and dot patterns; rename follows layers and
|
||||||
|
entities; delete is refused while anything uses it.
|
||||||
|
- **Layouts:** create with the default page setup and sheet viewport, rename, delete,
|
||||||
|
switch (through OCS's own layout switch), and page setup (paper size, rotation,
|
||||||
|
custom scale). `Model` is protected.
|
||||||
|
|
||||||
|
Style and layout operations act on the active document, because they use the
|
||||||
|
application's shared style and view machinery.
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
`run_command` takes a `CommandRequest` (`Run`, `Start`, `Point`, `Text`, `Token`,
|
||||||
|
`Entity`, `Selection`, `Enter`, `Cancel`) and answers with a `CommandOutcome`:
|
||||||
|
whether the command is done or waiting, its prompt, what input it accepts, its
|
||||||
|
keyword options, how many entities it added, tokens nobody asked for, and any
|
||||||
|
error. It uses the same primitives as the automation channel and finishes each
|
||||||
|
step synchronously on the host thread, so a step never waits for anything that has
|
||||||
|
to arrive from outside; an earlier fire-and-forget replay could hang, this does not.
|
||||||
|
|
||||||
|
Guards: refused while another command is active or off the active tab; refused for
|
||||||
|
commands that could end the session or re-enter Python (`QUIT`, `EXIT`, `CLOSE*`,
|
||||||
|
`NEW`, `QNEW`, `OPEN`, `SAVE*`, `RECOVER`, `SCRIPT`, `RUNSCRIPT`, `SCRIPTCOMMANDS`, `PY_*`); an editor or
|
||||||
|
dialog a command opens is reported and closed by `Cancel`. The user can turn the whole
|
||||||
|
facility off with the saved `SCRIPTCOMMANDS` preference (on by default; `SCRIPTCOMMANDS 0`
|
||||||
|
at the command line): while it is off, every request except `Cancel` is refused (so a command a script left
|
||||||
|
waiting can still be closed). A script cannot change
|
||||||
|
it, because the runner refuses that command. The runner does not consult the automation
|
||||||
|
on/off switch, which governs the external MCP and serve channels. The Python layer cancels
|
||||||
|
any step sequence that leaves a command waiting.
|
||||||
|
|
||||||
|
## Python surface
|
||||||
|
|
||||||
|
`ocs.active_document` exposes `entities`, `create_entity`, `delete_entity`,
|
||||||
|
`transaction`, `selection`, `solids`, `layers`, `text_styles`, `dim_styles`, `blocks`,
|
||||||
|
`linetypes`, `layouts`, `command`, `start_command` and `modify` (offset, trim, extend,
|
||||||
|
fillet, chamfer, move, copy, rotate, scale, mirror, erase, rectangular, polar, path and
|
||||||
|
3-D arrays, explode, join, break, stretch, lengthen and polyline edits). `doc.coverage()`
|
||||||
|
lists the catalog, and `doc.entities[handle].coverage` one entry, with the readable and
|
||||||
|
editable keys and the fields the typed snapshot carries but the model does not map.
|
||||||
|
|
||||||
|
Interactive picks use a token-based request and poll API because `PY_RUN` uses a
|
||||||
|
fresh interpreter per invocation and a script cannot suspend while the user clicks.
|
||||||
|
Drawing, selection and command notifications are kept in a bounded 256-event queue
|
||||||
|
per tab between runs and drained with `doc.poll_events()`; an overflow is reported
|
||||||
|
as `{"type": "overflow", "dropped": n}`. Tokens are bound to the tab that asked.
|
||||||
|
|
||||||
|
## Known limits
|
||||||
|
|
||||||
|
- Twelve of the 43 canvas kinds are not yet `Complete`; each has a named blocker in the
|
||||||
|
ledger. Seven are cadcodec DXF bugs whose fixes are submitted upstream but not yet adopted.
|
||||||
|
- The DXF codec also drops some table properties (text style generation flags, block
|
||||||
|
descriptions, a dimension style's text-style name) and mis-scales one angle; these are
|
||||||
|
pinned by canaries and listed in `cadcodec-reader-gaps.md`.
|
||||||
|
- Not available from a script: complex (text and shape) linetypes, plot devices and named
|
||||||
|
page setups, PEDIT's fit and spline options, and interactive-only commands such as HATCH.
|
||||||
|
- A command step nests inside the editor's message handling. In a debug build a deep step
|
||||||
|
(PEDIT converting a line to a polyline) needs between 2 and 4 MiB of stack; the native
|
||||||
|
builds link with at least 8 MiB (16 MiB on Windows, `.cargo/config.toml`), the nesting depth
|
||||||
|
is fixed rather than recursive (`PY_*` is refused), and a release build uses far less.
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
# Reviewer guide: scripting host model and the bundled Python plugin
|
||||||
|
|
||||||
|
This is written for a reviewer who has not followed the work and may not have a Mac.
|
||||||
|
It says what the change is, how to check it on Linux or Windows in a few minutes, where
|
||||||
|
it touches existing code, what to read first, and what is deliberately left out.
|
||||||
|
|
||||||
|
## What it is
|
||||||
|
|
||||||
|
The bundled `opencad.python` plugin (RustPython, in its own process) can now control OCS
|
||||||
|
through the versioned plugin API (v7), not only add lines and circles:
|
||||||
|
|
||||||
|
- **Entities.** Create, read, edit, delete and undo for all 43 canvas kinds (41 creatable),
|
||||||
|
validated by the host, each with a DWG and DXF round-trip audit.
|
||||||
|
- **Drawing tables.** Layers, text and dimension styles, blocks and their contents,
|
||||||
|
linetypes and layouts, and kernel-backed solids.
|
||||||
|
- **Commands.** Scripts can run OCS's own commands step by step (offset, trim, fillet,
|
||||||
|
arrays, PEDIT and so on), with guards.
|
||||||
|
|
||||||
|
**The host owns the drawing.** It validates every request, records the undo step and
|
||||||
|
refuses without changing anything when it cannot honour a request. The Python adapter is a
|
||||||
|
thin translation layer. The design and its guarantees are in
|
||||||
|
[plugin-host-model.md](plugin-host-model.md).
|
||||||
|
|
||||||
|
**Size.** 72 files, +30,705 / −178, against current `main`. About 15,000 added lines are the
|
||||||
|
new plugin crate (including a 3,000-line lockfile and a generator), 5,600 are the API crate
|
||||||
|
(3,500 of them the entity coverage validator), and 8,800 are in `src/`, of which roughly 6,200
|
||||||
|
are tests in `plugin_host.rs`. Existing OCS code changes by **178 deleted lines in total** (151 of them outside docs, plugin and API);
|
||||||
|
everything else is additive.
|
||||||
|
|
||||||
|
## Check it without a Mac
|
||||||
|
|
||||||
|
Nothing here needs macOS. The plugin tests are headless: they build the plugin and the
|
||||||
|
application, then spawn the application as the plugin runner and talk to it over the real IPC.
|
||||||
|
`stage-bundled.sh` already handles Linux (`.so`) and Windows (`.dll`), and the host looks for the
|
||||||
|
plugin in `plugins/opencad.python/` next to the executable.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bash plugins/opencad-python/tools/stage-bundled.sh work/plugin --debug
|
||||||
|
cargo build --bin OpenCADStudio
|
||||||
|
OCS_TEST_PYTHON_PLUGIN=work/plugin/libopencad_python.so \
|
||||||
|
OCS_PLUGIN_RUNNER_EXE=target/debug/OpenCADStudio \
|
||||||
|
cargo test --lib -- --test-threads=1 python
|
||||||
|
```
|
||||||
|
|
||||||
|
(`opencad_python.dll` and `OpenCADStudio.exe` on Windows.) Expect 60 passed. **Without the two
|
||||||
|
environment variables these tests are skipped and still report success**; `python-host-check.yml` fails
|
||||||
|
instead of skipping.
|
||||||
|
|
||||||
|
Already run for you:
|
||||||
|
|
||||||
|
| Check | Where | Result |
|
||||||
|
|---|---|---|
|
||||||
|
| `python-host-check.yml` on the pull request | Linux and Windows | 115 plugin API tests, 20 plugin tests, 16 Python model tests, 60 host tests over real IPC, on each |
|
||||||
|
| Release build with the plugin staged (a fork-only workflow, not in this PR) | Linux and Windows | 60 of 60 host tests on each; unsigned portable packages were produced and can be shared on request |
|
||||||
|
| Local | macOS | the same, plus the wasm check |
|
||||||
|
|
||||||
|
`main` now has its own `Tests` workflow (`cargo test --workspace --locked` on Linux), which will also run on
|
||||||
|
this pull request. Run locally on macOS against the merged tree with the same command and `LC_ALL=C` and
|
||||||
|
`--no-fail-fast`, the whole workspace gives **1,805 passed and 1 failed**. The one failure,
|
||||||
|
`scene::text::lff::tests::fonts_parse_and_resolve`, also fails on pristine `main` in that environment (it
|
||||||
|
needs font data) and is not part of this change; I expect it passes on the Linux runner but have not seen that.
|
||||||
|
|
||||||
|
What has **not** been done: launching the GUI on Linux or Windows (the runners have no display), running the
|
||||||
|
whole workspace suite on Windows, and building an AppImage or MSI that contains the plugin.
|
||||||
|
|
||||||
|
## Reading order
|
||||||
|
|
||||||
|
Read the contract first, then the host, then the adapter. The commits are in dependency order but
|
||||||
|
several kinds and features are interleaved, so read by area rather than commit by commit.
|
||||||
|
|
||||||
|
1. **The contract: `crates/ocs_plugin_api`.**
|
||||||
|
- `src/host.rs`: the new types and default-refusing methods: `SolidOperation`, `TableOperation`,
|
||||||
|
`CommandRequest` and `CommandOutcome`, `update_entities_transaction`, `selection`, `set_selection`,
|
||||||
|
`solid_operation`, `table_operation`, `run_command`.
|
||||||
|
- `src/ipc/**`: one additive request and response variant per method. The new variants are appended
|
||||||
|
after the existing ones so existing wire positions do not move. `v4/protocol.rs` has a bincode round-trip
|
||||||
|
test for each.
|
||||||
|
- `src/entity_coverage.rs`, `entity_coverage_policy.json`, `build.rs`: the per-kind validation and the
|
||||||
|
generated coverage catalog. This is the largest file and the most mechanical; the tests in it are the
|
||||||
|
rules in executable form.
|
||||||
|
2. **The host: `src/app/plugin_host.rs`**, lines 1 to about 2,700 (the rest is tests). Sections in order:
|
||||||
|
scripted-entity normalization (host-derived state), solid operations, `table_operation` (layers, then
|
||||||
|
styles, blocks, linetypes, layouts), `run_command`, and the `HostApi` delegation at the end.
|
||||||
|
3. **The adapter: `plugins/opencad-python`.** `entity_manifest.json` and `build/generate.rs` generate the
|
||||||
|
dict-to-entity conversions from the host's type registry; `src/ocs_module.rs` is the `ocs.*` bindings;
|
||||||
|
`src/document_model.py` is the script-facing document model; `PLUGIN.md` is the reference.
|
||||||
|
4. **The small edits to existing OCS files** (this is where behaviour of existing code could change):
|
||||||
|
|
||||||
|
| File | Change |
|
||||||
|
|---|---|
|
||||||
|
| `src/plugin/external.rs`, `src/ui/window/plugin_manager.rs` | Bundled-plugin discovery (`bundled_plugins_dir`, `OCS_BUNDLED_PLUGINS_DIR`, a "Bundled with Open CAD Studio" label). A per-user plugin with the same id still overrides the bundled one. |
|
||||||
|
| `src/plugin/v4_support.rs`, `src/app/update/mod.rs`, `src/app/automation.rs` | New `DrawingChanged` and `CommandStateChanged` notifications; a drawing-changed notification after automation ops. |
|
||||||
|
| `src/entities/{mline,table,helix,dimension}.rs` | `normalize_scripted_*`: derived state a script must not set (MLine geometry, Table merges, Helix spline, Dimension measurement). Called only from the plugin host. |
|
||||||
|
| `src/scene/selection.rs`, `src/scene/entity.rs`, `src/app/layers.rs` | `replace_selection_exact`, preserving storage data on entity replacement, `set_current_layer_name`. |
|
||||||
|
| `src/app/style_ops.rs`, `src/app/control/mod.rs` | Four methods and one function widened to `pub(super)` so the host reuses OCS's own style rename, delete and in-use logic. |
|
||||||
|
| `src/app/settings.rs`, `src/app/mod.rs`, `src/app/update/file.rs`, `src/app/commands/styleprops.rs` | The `SCRIPTCOMMANDS` preference and command (see the decisions below). |
|
||||||
|
| `packaging/build_macos_signed.sh`, `.github/workflows/release.yml` | Stage (and, in the signed script, sign) the plugin in the macOS bundle; one added step in `release.yml`. |
|
||||||
|
|
||||||
|
## What each area proves
|
||||||
|
|
||||||
|
| Area | Evidence |
|
||||||
|
|---|---|
|
||||||
|
| 43 entity kinds | One real-IPC audit per kind (create, read, edit two properties, delete, undo and redo, invalid input with an atomic rollback, canvas geometry, DWG and DXF reopen and re-edit). [The ledger](plugin-host-model-coverage-ledger.md) records each kind's exact evidence or its blocker. |
|
||||||
|
| Solids | Kernel primitives, moves, booleans, extrusions and regions, each verified to lift back from its ACIS payload; refusals leave operands untouched. |
|
||||||
|
| Tables | `audit_python_layer_table`, `_text_and_dim_styles`, `_blocks`, `_block_contents`, `_linetypes_and_layouts`: dozens of refusals each, live and DWG and DXF persistence, one-step undo. |
|
||||||
|
| Commands | `audit_python_modify_wrappers`: exact geometry for every wrapper (offset, trim, extend, fillet, chamfer, arrays, explode, join, break, stretch, lengthen, PEDIT edits), guards, an interactive session, undo. |
|
||||||
|
| Nested input | `audit_python_nested_input_is_validated`: a mistyped vertex key or a missing location is refused instead of becoming a zero coordinate. |
|
||||||
|
| Guardrail | `script_commands_setting_gates_the_runner` and a settings round-trip test. |
|
||||||
|
|
||||||
|
## Decisions that are yours
|
||||||
|
|
||||||
|
1. **`run_command` and the automation switch.** Script-driven commands do not consult the automation on/off
|
||||||
|
switch, which governs the external MCP and serve channels; a script is something the user chose to run. Say
|
||||||
|
if you would rather they respected it.
|
||||||
|
2. **`SCRIPTCOMMANDS`.** A saved preference (on by default) toggled by a command turns script-driven commands off
|
||||||
|
entirely. It has no Options-page control; adding one needs locale and layout work outside this change.
|
||||||
|
3. **Denylist.** A script cannot run `QUIT`, `EXIT`, `CLOSE*`, `NEW`, `QNEW`, `OPEN`, `SAVE*`, `RECOVER`,
|
||||||
|
`SCRIPT`, `RUNSCRIPT`, `SCRIPTCOMMANDS` or any `PY_*`, and only one command may be active. Tell me about any
|
||||||
|
other command that should be refused.
|
||||||
|
4. **Nesting depth.** A command step runs inside the editor's message handling. It is not recursive, but a debug
|
||||||
|
build of one step (PEDIT converting a line to a polyline) needs 2 to 4 MiB of stack; the native builds link
|
||||||
|
with at least 8 MiB (16 MiB on Windows).
|
||||||
|
5. **Splitting.** If 79 commits is too much, the natural seams are: the API and host core, the entity kinds,
|
||||||
|
the tables, and the command runner. Tell me and I will cut it that way.
|
||||||
|
|
||||||
|
## What is deliberately not done
|
||||||
|
|
||||||
|
- **Twelve of the 43 kinds are not `Complete`** (see the ledger). Seven are blocked by DXF bugs in
|
||||||
|
cadcodec, whose fixes are submitted as [cadcodec#48](https://github.com/HakanSeven12/cadcodec/pull/48) and
|
||||||
|
[#51](https://github.com/HakanSeven12/cadcodec/pull/51). **This change still pins the unfixed cadcodec revision**,
|
||||||
|
so its canary tests assert the old behaviour; once those merge, the pin moves, the canaries flip and those kinds
|
||||||
|
can be marked complete. The other five are held by the DWG format, a kind change on DXF save, an image-reactor
|
||||||
|
structure that cannot be verified, an update-only decision, and a missing creation path.
|
||||||
|
- Not available from a script: complex (text and shape) linetypes, plot devices and named page setups, PEDIT's
|
||||||
|
fit and spline options, and interactive-only commands such as HATCH.
|
||||||
|
- Two DXF gaps are not filed upstream because they need the exact XDATA layout AutoCAD expects (the TrueType
|
||||||
|
family name and the block description); they are listed in [cadcodec-reader-gaps.md](cadcodec-reader-gaps.md).
|
||||||
|
- The AppImage, snap and MSI still ship without the plugin: `release.yml` stages it only in the macOS bundle
|
||||||
|
(one added step, part of this change). Bundling it for Linux and Windows means adding the same staging step
|
||||||
|
(`stage-bundled.sh`) to those jobs, which is small but I could not test the installers here.
|
||||||
@@ -89,6 +89,8 @@ cp "target/$TARGET/release/OpenCADStudio" "$APP/Contents/MacOS/OpenCADStudio-App
|
|||||||
chmod +x "$APP/Contents/MacOS/OpenCADStudio" "$APP/Contents/MacOS/OpenCADStudio-App"
|
chmod +x "$APP/Contents/MacOS/OpenCADStudio" "$APP/Contents/MacOS/OpenCADStudio-App"
|
||||||
cp "$DIST/AppIcon.icns" "$DIST/DWG.icns" "$DIST/DXF.icns" "$APP/Contents/Resources/"
|
cp "$DIST/AppIcon.icns" "$DIST/DWG.icns" "$DIST/DXF.icns" "$APP/Contents/Resources/"
|
||||||
cp -R "$EXT" "$APP/Contents/PlugIns/"
|
cp -R "$EXT" "$APP/Contents/PlugIns/"
|
||||||
|
bash plugins/opencad-python/tools/stage-bundled.sh \
|
||||||
|
"$APP/Contents/Resources/plugins/opencad.python" --target "$TARGET"
|
||||||
sed "s/__VERSION__/$VERSION/g" packaging/Info.plist > "$APP/Contents/Info.plist"
|
sed "s/__VERSION__/$VERSION/g" packaging/Info.plist > "$APP/Contents/Info.plist"
|
||||||
|
|
||||||
echo "==> codesign"
|
echo "==> codesign"
|
||||||
@@ -97,6 +99,8 @@ if [ "$DEVELOPER_ID" = "-" ]; then
|
|||||||
# Ad-hoc signing cannot be notarized.
|
# Ad-hoc signing cannot be notarized.
|
||||||
codesign --force --sign - --timestamp=none \
|
codesign --force --sign - --timestamp=none \
|
||||||
"$APP/Contents/MacOS/OpenCADStudio-App"
|
"$APP/Contents/MacOS/OpenCADStudio-App"
|
||||||
|
codesign --force --sign - --timestamp=none \
|
||||||
|
"$APP/Contents/Resources/plugins/opencad.python/libopencad_python.dylib"
|
||||||
codesign --force --sign - --timestamp=none \
|
codesign --force --sign - --timestamp=none \
|
||||||
--entitlements crates/dwg-thumbnailer/macos/entitlements.plist \
|
--entitlements crates/dwg-thumbnailer/macos/entitlements.plist \
|
||||||
"$APP/Contents/PlugIns/DWGThumbnail.appex"
|
"$APP/Contents/PlugIns/DWGThumbnail.appex"
|
||||||
@@ -107,6 +111,9 @@ else
|
|||||||
# and a secure timestamp on every layer for notarization.
|
# and a secure timestamp on every layer for notarization.
|
||||||
codesign --force --timestamp --options runtime \
|
codesign --force --timestamp --options runtime \
|
||||||
-s "$DEVELOPER_ID" "$APP/Contents/MacOS/OpenCADStudio-App"
|
-s "$DEVELOPER_ID" "$APP/Contents/MacOS/OpenCADStudio-App"
|
||||||
|
codesign --force --timestamp --options runtime \
|
||||||
|
-s "$DEVELOPER_ID" \
|
||||||
|
"$APP/Contents/Resources/plugins/opencad.python/libopencad_python.dylib"
|
||||||
codesign --force --timestamp --options runtime \
|
codesign --force --timestamp --options runtime \
|
||||||
--entitlements crates/dwg-thumbnailer/macos/entitlements.plist \
|
--entitlements crates/dwg-thumbnailer/macos/entitlements.plist \
|
||||||
-s "$DEVELOPER_ID" "$APP/Contents/PlugIns/DWGThumbnail.appex"
|
-s "$DEVELOPER_ID" "$APP/Contents/PlugIns/DWGThumbnail.appex"
|
||||||
|
|||||||
Generated
+3059
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,47 @@
|
|||||||
|
[package]
|
||||||
|
name = "opencad-python"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
description = "Python scripting for Open CAD Studio (embeds RustPython)."
|
||||||
|
license = "GPL-3.0-only"
|
||||||
|
|
||||||
|
[workspace]
|
||||||
|
resolver = "2"
|
||||||
|
|
||||||
|
# A plugin is a C-ABI dynamic library the host loads at runtime.
|
||||||
|
[lib]
|
||||||
|
crate-type = ["cdylib"]
|
||||||
|
|
||||||
|
[features]
|
||||||
|
default = []
|
||||||
|
# Requires an external HostApi patch providing run_command/set_selection.
|
||||||
|
# Never enable against the released OCS host: nested command replay can hang.
|
||||||
|
experimental-command-replay = []
|
||||||
|
# Requires the general HostApi system-variable methods in this OCS fork.
|
||||||
|
experimental-host-settings = []
|
||||||
|
# Requires the in-tree OCS host API v7.
|
||||||
|
experimental-host-model = ["dep:serde_json"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
# The stable contract, with the runtime `host` surface (HostApi / BuiltinPlugin).
|
||||||
|
ocs_plugin_api = { path = "../../crates/ocs_plugin_api", features = ["host"] }
|
||||||
|
# Embedded interpreter for Phase 1 (see this crate's PLUGIN.md and ROADMAP.md).
|
||||||
|
# default-features = false, no "host_env": that default feature bakes `posix`
|
||||||
|
# (full filesystem access, confirmed: open('/etc/passwd').read() works with
|
||||||
|
# it on) and `_ctypes` (raw native-code-calling primitives) into every
|
||||||
|
# interpreter unconditionally, regardless of never adding rustpython-stdlib —
|
||||||
|
# see this crate's PLUGIN.md's sandboxing section for the audit that found
|
||||||
|
# this. "compiler" is required (Vm::compile); "gc" matches the default set
|
||||||
|
# for normal memory behavior. "wasmbind"/"stdio" are irrelevant off-web.
|
||||||
|
rustpython-vm = { version = "0.5", default-features = false, features = ["compiler", "gc"] }
|
||||||
|
serde_json = { version = "1", optional = true }
|
||||||
|
|
||||||
|
[build-dependencies]
|
||||||
|
# No "host" feature: `type_registry`/`type_registry_types` (the only modules
|
||||||
|
# build.rs touches, via `get_embedded_type_registry_json`) are unconditionally
|
||||||
|
# compiled and depend on nothing but `serde` — the "host" feature only adds
|
||||||
|
# the acadrust-typed runtime surface build.rs has no use for. See this crate's
|
||||||
|
# own `src/lib.rs` doc comment on the module split.
|
||||||
|
ocs_plugin_api = { path = "../../crates/ocs_plugin_api" }
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
serde_json = "1"
|
||||||
@@ -0,0 +1,563 @@
|
|||||||
|
# Python Scripting (`opencad.python`)
|
||||||
|
|
||||||
|
## Sandboxing (Phase 1.5)
|
||||||
|
|
||||||
|
**Audited, not assumed — and the assumption was wrong.** Earlier phases
|
||||||
|
claimed "no stdlib is loaded, so `import os`/`socket`/`subprocess` is
|
||||||
|
already impossible." True for those three names, but incomplete: RustPython
|
||||||
|
0.5.0's `host_env` Cargo feature — **on by default**, and `rustpython-vm =
|
||||||
|
"0.5"` in this crate's `Cargo.toml` used to pull in the full default set —
|
||||||
|
bakes `posix`/`_ctypes` (and `os`/`nt` on other platforms) into every
|
||||||
|
interpreter's *core* module registry, entirely independent of ever adding
|
||||||
|
the separate `rustpython-stdlib` crate. Confirmed by actually running it,
|
||||||
|
not by reading feature flags: with `host_env` on, `PY_EVAL
|
||||||
|
__import__('posix').getcwd()` and `PY_EVAL open('/etc/passwd').read()` both
|
||||||
|
worked — full filesystem read (and write) access from any script.
|
||||||
|
|
||||||
|
**Fixed**: `Cargo.toml` now depends on `rustpython-vm` with
|
||||||
|
`default-features = false, features = ["compiler", "gc"]` — no `host_env`.
|
||||||
|
Re-verified the full matrix after the fix, all blocked
|
||||||
|
(`ModuleNotFoundError` or, for `open()`, `UnsupportedOperation`):
|
||||||
|
`os`, `posix`, `nt`, `subprocess`, `socket`, `ctypes`, `_ctypes`, `_socket`,
|
||||||
|
`_subprocess`, `_signal`, `pwd`, and both read and write through the
|
||||||
|
built-in `open()` — its `FileIO` backing turned out to depend on
|
||||||
|
`host_env`-gated code internally too, even though the `_io` module itself
|
||||||
|
is always registered. Confirmed no functional regression: `ocs.add_line`
|
||||||
|
and the full `examples/example.py` (including both real constraints) still
|
||||||
|
run correctly with `host_env` off.
|
||||||
|
|
||||||
|
What's left in `sys.modules` after that fix, for a fresh interpreter —
|
||||||
|
audited exhaustively, not just "fewer than before": `_ast`, `_codecs`,
|
||||||
|
`_frozen_importlib`, `_imp`, `_io`, `_thread`, `_typing`, `_warnings`,
|
||||||
|
`_weakref`, `builtins`, `codecs`, `encodings_ascii`, `encodings_utf_8`,
|
||||||
|
`ocs`, `sys` — core language/import/codec plumbing needed to run Python at
|
||||||
|
all, plus `ocs`. None of it reaches the filesystem, network, or another
|
||||||
|
process.
|
||||||
|
|
||||||
|
**One known, accepted residual gap, not silently ignored: `_thread` is
|
||||||
|
real and functional** (`_thread.start_new_thread` exists and is callable,
|
||||||
|
verified — not a stub). It's registered unconditionally in `rustpython-vm`
|
||||||
|
0.5.0's `stdlib/mod.rs` with no feature guard at all — not `host_env`, not
|
||||||
|
even its own `threading` Cargo feature — so there is no dependency-level
|
||||||
|
way to remove it short of patching RustPython itself, which is out of
|
||||||
|
scope here. It grants no filesystem/network/process access (everything
|
||||||
|
that would matter for *that* is confirmed blocked above); the realistic
|
||||||
|
risk is a script spawning a thread that busy-loops or otherwise misbehaves
|
||||||
|
inside the plugin's own process — a resource/stability concern local to
|
||||||
|
the already crash-isolated plugin process (per `plugin-architecture.md`'s
|
||||||
|
out-of-process design), not a host compromise or data exfiltration path.
|
||||||
|
Deleting `_thread` from `sys.modules` after interpreter setup was
|
||||||
|
considered and rejected as a fix: the module stays *registered* at the VM
|
||||||
|
level regardless, so a script could just re-import it — the deletion would
|
||||||
|
be security theater, not a real control.
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
| Command | Description |
|
||||||
|
|---------|-------------|
|
||||||
|
| `PY_EVAL <expr>` | Evaluate one Python expression and print the result (or error) to the command line. Example: `PY_EVAL 1 + 1`. |
|
||||||
|
| `PY_RUN <path.py>` | Run a `.py` file as a script (statements, not just one expression). Reports an error the same way as `PY_EVAL` (missing file, syntax error, exception) — never a silent no-op. |
|
||||||
|
|
||||||
|
## The `ocs` module
|
||||||
|
|
||||||
|
Pre-bound as `ocs` in both commands — no `import` needed (and for `PY_EVAL`,
|
||||||
|
none is possible: it compiles in `Mode::Eval`, which only accepts a single
|
||||||
|
expression, not statements). Phases 1.2 (read), 1.3 (2D write) and part of
|
||||||
|
1.4 (`Run Script…`) of this plugin's `ROADMAP.md`.
|
||||||
|
|
||||||
|
| Function | Returns |
|
||||||
|
|----------|---------|
|
||||||
|
| `ocs.selection()` | List of the selected entities' handles (`int`), as of the last selection change — see note below. |
|
||||||
|
| `ocs.get(handle)` | Dict of `{handle, kind, layer, point}` for that entity, or `None` if it doesn't exist. `point` is `{x, y, z}` or `None` for non-point entities. |
|
||||||
|
| `ocs.get_text(handle)` | For single-line TEXT, returns its active alignment point, OCS normal, rotation, direction, and height; otherwise `None`. Reads the host's full document snapshot. |
|
||||||
|
| `ocs.text_entities()` | Lists top-level TEXT/MTEXT entities as `{handle, kind, value}` dictionaries from the active document. |
|
||||||
|
| `ocs.block_references()` | Lists top-level INSERT entities as `{handle, name, effective_name, count, is_xref, is_dynamic, visibility}` dictionaries; `count` includes MINSERT row × column multiplicity and unresolved visibility is `None`. |
|
||||||
|
| `ocs.layers()` | Lists active-document layer names, off/frozen/locked flags, and top-level entity counts. |
|
||||||
|
| `ocs.set_entity_layer(handle, layer_name)` | Moves an existing top-level entity to an existing layer, preserving its handle and layout ownership. |
|
||||||
|
| `ocs.export_layer_dwg(layer_name, output_path)` | Writes a new DWG containing one layer's top-level entities plus needed block definitions; requires an existing directory and refuses overwrite. |
|
||||||
|
| `ocs.current_layer()` | Returns the active document's current layer name (`CLAYER`). |
|
||||||
|
| `ocs.layout_for_entity(handle)` | Returns an entity's owning layout name, tab order, and paperspace sheet count; `None` when unresolved. |
|
||||||
|
| `ocs.viewport_model_outline(handle)` | Returns four XY modelspace corners and elevation for a rectangular, unclipped +Z paperspace viewport; otherwise `None`. |
|
||||||
|
| `ocs.add_closed_polyline(vertices, elevation)` | Adds a closed lightweight polyline from at least three finite `[x, y]` vertices. |
|
||||||
|
| `ocs.text_box_vertices(handle, padding)` | Returns an approximate rotated XY box for left/baseline +Z TEXT; otherwise `None`. |
|
||||||
|
| `ocs.update_closed_polyline(handle, vertices, elevation)` | Replaces a closed lightweight polyline's vertices/elevation, preserving its handle and common properties. |
|
||||||
|
| `ocs.copy_model_to_paper(handles, viewport_handle)` | Copies planar modelspace LINE/ARC/CIRCLE/LWPolyline geometry through a rectangular +Z viewport to its paperspace layout. |
|
||||||
|
| `ocs.mirror_xy_entities(handles, axis_handle, erase_source)` | Mirrors planar LINE/ARC/CIRCLE/LWPolyline entities across an existing XY LINE; optionally removes sources in the same undo group. |
|
||||||
|
| `ocs.mirror_xy_about_line(handles, point, tangent, erase_source)` | Mirrors planar curves across the XY line through a point in a tangent direction; supports curved-axis midpoint workflows. |
|
||||||
|
| `ocs.break_xy_line(handle, first, second)` | Removes the span between two interior XY points on a LINE, preserving its first fragment's handle and properties. |
|
||||||
|
| `ocs.break_xy_arc(handle, first, second)` | Removes the angular span between two interior XY ARC points, retaining the first fragment's handle. |
|
||||||
|
| `ocs.break_xy_circle(handle, first, second)` | Replaces an XY CIRCLE with the complementary ARC after removing the counterclockwise span from first to second. |
|
||||||
|
| `ocs.break_xy_polyline(handle, first, second)` | Removes a path interval from an open, straight, zero-width XY LWPolyline, keeping the first fragment's handle. |
|
||||||
|
| `ocs.align_xy_entities(handles, source, destination, source_direction, target_direction, copy_mode)` | Rigidly moves and rotates planar LINE/ARC/CIRCLE/LWPolyline entities in XY; `copy_mode=True` adds transformed copies instead of changing originals. |
|
||||||
|
| `ocs.block_insert_point(handle)` | Returns `[x, y, z]` for an INSERT, or `None`. |
|
||||||
|
| `ocs.block_bounds_xy(handle)` | Returns `[xmin, ymin, xmax, ymax]` for a simple unrotated single INSERT whose definition contains only LINE/ARC/CIRCLE/LWPolyline geometry; otherwise `None`. |
|
||||||
|
| `ocs.block_attributes(handle)` | Lists `{tag, value}` pairs for one INSERT, or `None` for another entity. |
|
||||||
|
| `ocs.set_block_attribute(handle, tag, value)` | Updates one INSERT attribute by case-insensitive tag, preserving the block's other data. |
|
||||||
|
| `ocs.set_text_value(handle, value)` | Replaces one TEXT/MTEXT entity's content, preserving other properties. Raises if the entity cannot be updated. |
|
||||||
|
| `ocs.set_mtext_mask(handle, mode, scale)` | Sets one MTEXT background mode (`off`, `mask`, or `fill`) and border scale; raises if invalid or not MTEXT. |
|
||||||
|
| `ocs.move_text(handle, x, y, z)` | Moves only a TEXT entity's active alignment point, preserving its other properties. Raises if it cannot update the entity. |
|
||||||
|
| `ocs.set_text_pose(handle, x, y, z, rotation)` | Moves and rotates one XY TEXT entity while preserving its other properties. |
|
||||||
|
| `ocs.get_area(handle)` | Returns `{area, point}` for a circle or straight, closed lightweight polyline in the world XY plane; otherwise `None`. `point` is suitable for an area-number label. |
|
||||||
|
| `ocs.get_curve_measure(handle)` | Returns `{length, point, rotation, tangent}` at half length for an XY line, circle, arc, or straight lightweight polyline; `tangent` is an XY unit vector. Otherwise `None`. |
|
||||||
|
| `ocs.line_endpoints(handle)` | Returns two `[x, y, z]` points for a nonzero XY LINE; otherwise `None`. |
|
||||||
|
| `ocs.polyline_segments(handle)` | Returns segment endpoint, width, length, and optional bulge-arc centre/radius dictionaries for an XY lightweight polyline; otherwise `None`. |
|
||||||
|
| `ocs.write_new_text_file(path, content)` | Writes a new UTF-8 report file at an explicit path during a `PY_` command. Refuses to overwrite or create parent directories. |
|
||||||
|
| `ocs.curve_samples(handle, segments)` | Returns equally spaced XY sample vertices, elevation, and closure for a line, arc, or circle; otherwise `None`. |
|
||||||
|
| `ocs.replace_with_polyline(handle, vertices, elevation, closed)` | Replaces a line, arc, or circle in place with a lightweight polyline, preserving the handle and common drawing properties. |
|
||||||
|
| `ocs.add_line(x1, y1, x2, y2)` | Adds a 2D line (z=0, layer `"0"`); returns its handle. |
|
||||||
|
| `ocs.add_circle(x, y, radius)` | Adds a 2D circle (z=0, layer `"0"`); returns its handle. |
|
||||||
|
| `ocs.add_arc(x, y, radius, start_deg, end_deg)` | Adds a 2D arc (z=0, layer `"0"`), angles in degrees; returns its handle. |
|
||||||
|
| `ocs.add_polyline(vertices, elevation)` | Adds an open 2D lightweight polyline. Each vertex is `[x, y, start_width, end_width]`; returns its handle. |
|
||||||
|
| `ocs.add_text_centered(value, x, y, z, height, rotation_radians)` | Adds middle-center aligned single-line text; returns its handle. |
|
||||||
|
| `ocs.add_text_left(value, x, y, z, height, rotation_radians)` | Adds left/baseline single-line text at its insertion point; returns its handle. |
|
||||||
|
| `ocs.add_mtext(value, point, height, width, rotation_radians)` | Adds top-left anchored MTEXT at `[x, y, z]` using Standard style; returns its handle. |
|
||||||
|
| `ocs.add_points(points)` | Adds many 3D points (each `[x, y, z]`) in one `HostApi::add_entities` batch call; returns the new handles in order. |
|
||||||
|
| `ocs.remove_entity(handle)` | Deletes one entity in the script's undo group; raises if the handle cannot be removed. |
|
||||||
|
| `ocs.add_table(rows, x, y, z, row_height, column_width)` | Adds a native table from a rectangular list of string rows; returns its handle. |
|
||||||
|
| `ocs.read_record(handle, app_name)` | Returns `{app_name, values}` for the XDATA record `app_name` on `handle`, or `None` if the entity or the record doesn't exist. See "XDATA" below for the `values` shape. |
|
||||||
|
| `ocs.write_record(handle, app_name, values)` | Attaches an XDATA record to `handle` for `app_name`, replacing any existing record for that application. Raises if `handle` doesn't exist. |
|
||||||
|
| `ocs.remove_record(handle, app_name)` | Removes the XDATA record for `app_name` from `handle`, if any. Returns `True` if a record was actually removed. |
|
||||||
|
| `ocs.command(cmd)` | Superseded. Only the `experimental-command-replay` build has it (the old fire-and-forget replay). Use `doc.command`, `doc.start_command` and `doc.modify` from the document model (see "Running OCS commands" below). |
|
||||||
|
| `ocs.select(handles)` | Replaces the selection with exactly these handles, in order (document-model build); `doc.selection = [...]` is the same. |
|
||||||
|
| `ocs.system_variable(name)` / `ocs.set_system_variable(name, value)` | Development-only `experimental-host-settings` feature. Reads or sets host-managed CLAYER (text) and SNAPANG (degrees) without nested command dispatch. Needs the host API v7 build that provides `system_variable`; absent from the portable default build. |
|
||||||
|
|
||||||
|
`add_line`/`add_circle`/`add_arc` take plain Python numbers —
|
||||||
|
`ocs.add_line(0, 0, 10, 10)` works with ints, not just floats. (Needed an
|
||||||
|
explicit fix: a bare `f64` `#[pyfunction]` parameter in RustPython, unlike
|
||||||
|
CPython's C-function argument parsing, does *not* implicitly coerce an
|
||||||
|
`int` — it raises `TypeError`. Using `rustpython_vm::function::ArgIntoFloat`
|
||||||
|
instead accepts anything with `__float__`/`__index__`, matching how a script
|
||||||
|
author actually writes coordinates.)
|
||||||
|
|
||||||
|
### Layers: `ocs.active_document.layers`
|
||||||
|
|
||||||
|
The layer table, with every change validated by the host, recorded as one undo
|
||||||
|
step, and refused (a `RuntimeError`, nothing changed) when it cannot be honoured.
|
||||||
|
|
||||||
|
```python
|
||||||
|
L = ocs.active_document.layers
|
||||||
|
L.create("Walls", color=1, lineweight=50, description="load bearing")
|
||||||
|
L.create("Grid", color=(10, 200, 30), linetype="Continuous", off=True)
|
||||||
|
L.modify("Walls", color=5, locked=True) # only the properties given
|
||||||
|
L.rename("Walls", "Structure") # entities on it follow
|
||||||
|
L.set_current("Grid")
|
||||||
|
L.delete("Structure", erase_objects=True) # refused if it holds objects otherwise
|
||||||
|
"Grid" in L, L["Grid"]["color"], L.current, L.names()
|
||||||
|
```
|
||||||
|
|
||||||
|
Properties: `color` (ACI 1-255, an `(r, g, b)` tuple or a Color dict), `linetype`
|
||||||
|
(must exist in the drawing), `lineweight` (1/100 mm, 0-211; -1 ByLayer, -2 ByBlock,
|
||||||
|
-3 Default), `off`, `frozen`, `locked`, `plottable`, `transparency` (percent 0-90),
|
||||||
|
`description`. Records also carry `handle`, `entity_count` and `current`.
|
||||||
|
Refused: an existing or invalid name (empty, over 255 characters, or containing
|
||||||
|
`<>/\":;?*|=` or a backquote), a color of ByLayer/ByBlock/0, an unknown property,
|
||||||
|
renaming or deleting layer `0` or `Defpoints`, deleting or freezing the current
|
||||||
|
layer, deleting an externally referenced layer, and modifying with no properties.
|
||||||
|
Making a layer current is a setting, not an undo step.
|
||||||
|
|
||||||
|
### Text and dimension styles: `doc.text_styles`, `doc.dim_styles`
|
||||||
|
|
||||||
|
```python
|
||||||
|
S, D = ocs.active_document.text_styles, ocs.active_document.dim_styles
|
||||||
|
S.create("Title", height=5, width_factor=0.8, oblique=15, font="romans", annotative=True)
|
||||||
|
S.modify("Title", height=6)
|
||||||
|
D.create("Metric", dimscale=2, dimtxt=3.5, dimtxsty="Title") # DimStyle field names
|
||||||
|
D.create("Metric2", copy_from="Metric", dimtxt=4)
|
||||||
|
S.rename("Title", "Heading") # entities, dimension styles and tables follow
|
||||||
|
S.set_current("Heading"); D.set_current("Metric")
|
||||||
|
D.delete("Metric2"); S["Heading"]["height"]; D.current["name"]; S.names()
|
||||||
|
```
|
||||||
|
|
||||||
|
Same guarantees as layers: host-validated, one undo step, a refusal raises
|
||||||
|
`RuntimeError` and changes nothing (making a style current is a setting).
|
||||||
|
Text properties: `height` (0 = each text chooses), `width_factor` (0-100),
|
||||||
|
`oblique` (degrees, within 85), `font`, `big_font`, `backward`, `upside_down`,
|
||||||
|
`vertical`, `annotative`; use `font="arial.ttf"` for a TrueType face, because
|
||||||
|
the codec does not persist a separate family name. Dimension styles use the
|
||||||
|
`DimStyle` field names (`dimscale`, `dimtxt`, `dimasz`, ...); records list all
|
||||||
|
of them. Handles, `xref_*` fields and `name` are host-managed and refused, unknown
|
||||||
|
fields and wrongly typed values are refused, `dimscale` and `dimtxt` must be
|
||||||
|
positive, and `dimtxsty` must name an existing text style. `Standard` is never
|
||||||
|
renamed or deleted; a style that is current or still referenced is never deleted;
|
||||||
|
a case-only rename is refused. Style operations act on the active document.
|
||||||
|
|
||||||
|
Known persistence limits (cadcodec, see `docs/cadcodec-reader-gaps.md`; the first two are fixed in
|
||||||
|
an open upstream pull request but OCS has not yet adopted it): a DXF
|
||||||
|
save drops the backward/upside-down flags of a text style and does not restore a
|
||||||
|
dimension style's `dimtxsty` name (the handle link survives); DWG keeps both.
|
||||||
|
|
||||||
|
### Blocks: `ocs.active_document.blocks`
|
||||||
|
|
||||||
|
```python
|
||||||
|
doc = ocs.active_document
|
||||||
|
line = doc.create_entity("Line", start=..., end=...)
|
||||||
|
circle = doc.create_entity("Circle", center=..., radius=1)
|
||||||
|
B = doc.blocks
|
||||||
|
B.create("Widget", [line, circle], base_point=(1, 1, 0), description="a widget")
|
||||||
|
doc.create_entity("Insert", block_name="Widget", insert_point={"x": 10, "y": 0, "z": 0})
|
||||||
|
B.modify("Widget", explodable=False)
|
||||||
|
B.rename("Widget", "Gadget") # every insert follows
|
||||||
|
B["Gadget"]["entities"], B["Gadget"]["insert_count"], B.names()
|
||||||
|
B.delete("Gadget") # refused while an insert, style or leader uses it
|
||||||
|
```
|
||||||
|
|
||||||
|
`create` copies model or paper space entities (descriptors or handles) into a new
|
||||||
|
definition shifted by `-base_point`, so an insert at `p` puts the base point at
|
||||||
|
`p`. `erase_originals=True` removes the sources, as the BLOCK command does; the
|
||||||
|
default keeps them. No insert is placed. Refused: an empty, duplicate, invalid or
|
||||||
|
`*`-prefixed name, no entities, a missing or repeated entity, an entity inside a
|
||||||
|
block, a viewport, a non-finite base point, renaming or deleting layout,
|
||||||
|
anonymous or externally referenced blocks, and a case-only rename. Deleting also
|
||||||
|
removes the definition's contents. Records list user blocks only (`handle`,
|
||||||
|
`name`, `description`, `explodable`, `scale_uniformly`, `base_point`,
|
||||||
|
`insert_count`, `entities` as `{handle, kind}`). A DXF save drops the block
|
||||||
|
description (cadcodec); DWG keeps it.
|
||||||
|
|
||||||
|
**Block contents.** Add to a definition with `create_entity(kind, block="Part",
|
||||||
|
...)`. It is validated exactly like a model-space entity and the host sets the
|
||||||
|
owner (so attribute definitions work: `create_entity("AttributeDefinition",
|
||||||
|
block="Part", tag=..., prompt=..., default_value=..., insertion_point=...,
|
||||||
|
height=...)`). Members are read, edited (`entity.end = (8, 0, 0)` inside
|
||||||
|
`doc.transaction(...)`) and deleted (`doc.delete_entity`) with the ordinary entity
|
||||||
|
API, using the handles in `blocks["Part"]["entities"]`. Refused: an unknown,
|
||||||
|
layout, anonymous or external block, an invalid entity, a viewport, raster image,
|
||||||
|
block marker or nested attribute, an entity on a locked layer, and an insert that
|
||||||
|
would nest a block inside itself directly or through other blocks. Adding while the
|
||||||
|
block editor is open is refused. Each add or delete is one undo step.
|
||||||
|
|
||||||
|
### Linetypes and layouts: `doc.linetypes`, `doc.layouts`
|
||||||
|
|
||||||
|
```python
|
||||||
|
doc = ocs.active_document
|
||||||
|
LT, LY = doc.linetypes, doc.layouts
|
||||||
|
LT.create("Bracket", [12, -3, 2, -3], "bracket line") # dash 12, gap 3, dash 2, gap 3
|
||||||
|
LT.modify("Bracket", description="renamed"); LT.rename("Bracket", "Cut")
|
||||||
|
doc.layers.create("Cuts", linetype="Cut")
|
||||||
|
LT.delete("Cut") # refused while a layer uses it
|
||||||
|
|
||||||
|
LY.create("Sheet1")
|
||||||
|
LY.set_page("Sheet1", paper_size=(420, 297), rotation=0, scale=(1, 50))
|
||||||
|
LY.current = "Sheet1" # create_entity now draws on the sheet
|
||||||
|
doc.create_entity("Circle", center={"x": 50, "y": 50, "z": 0}, radius=5)
|
||||||
|
LY.current = "Model"
|
||||||
|
LY.rename("Sheet1", "Plan"); LY.delete("Plan") # deletes the sheet's entities too
|
||||||
|
LY.names(), LY.current["name"], LY["Plan"]["paper_size"]
|
||||||
|
```
|
||||||
|
|
||||||
|
Both follow the same rules as the other tables: host-validated, one undo step
|
||||||
|
(switching layout is not one), a refusal raises `RuntimeError` and changes
|
||||||
|
nothing. A linetype pattern is signed lengths (positive dash, negative gap, zero
|
||||||
|
dot; 2-12 elements with a gap and a dash or dot); text and shape linetypes can be
|
||||||
|
read (`complex`) but not created or edited. `Continuous`, `ByLayer` and `ByBlock`
|
||||||
|
are never changed, names of standard linetypes are taken, renaming updates the
|
||||||
|
layers and entities that use it, and a linetype used by a layer, entity, dimension
|
||||||
|
style or the current setting is never deleted. Layouts: `Model` cannot be created,
|
||||||
|
renamed or deleted; deleting the current layout falls back to `Model`; a
|
||||||
|
case-only rename is refused. `set_page` takes the sheet in millimetres, a rotation
|
||||||
|
of 0/90/180/270 and a custom scale `(numerator, denominator)`, and updates the
|
||||||
|
layout limits. Layout operations act on the active document. Records list
|
||||||
|
`current`, `tab_order`, `entity_count`, `viewport_count`, `paper_size`, `rotation`
|
||||||
|
and `scale`. Reordering layouts and plot devices or styles are not available yet.
|
||||||
|
|
||||||
|
### Running OCS commands: `doc.command`, `doc.start_command`, `doc.modify`
|
||||||
|
|
||||||
|
Scripts can drive OCS's own tools. The host runs the real command, so it behaves
|
||||||
|
exactly as at the command line (same prompts, same geometry, same undo), and does
|
||||||
|
it synchronously on the editor thread, so a step never waits on outside input.
|
||||||
|
|
||||||
|
```python
|
||||||
|
doc = ocs.active_document
|
||||||
|
doc.command("CIRCLE 5,5 3") # a whole line: tokens answer the prompts, then Enter
|
||||||
|
with doc.start_command("OFFSET") as c: # or answer prompt by prompt
|
||||||
|
c.text(2) # a typed value
|
||||||
|
c.entity(line, at=(5, 0, 0)) # an object pick
|
||||||
|
c.point((5, 4, 0)) # a point
|
||||||
|
c.enter()
|
||||||
|
print(c.outcome["status"], c.outcome["prompt"], c.outcome["added"])
|
||||||
|
|
||||||
|
M = doc.modify # the common tools as plain calls
|
||||||
|
M.offset(line, 2, side=(5, 5)) # returns the new entity
|
||||||
|
M.trim(target, at=(108, 0)); M.extend(target, at=(208, 0))
|
||||||
|
M.fillet(first, second, radius=2) # radius 0 squares the corner
|
||||||
|
M.move([a, b], (0, 0, 0), (5, 5, 0)); M.copy([a], base, target)
|
||||||
|
M.rotate([a], base, 90); M.scale([a], base, 2)
|
||||||
|
M.mirror([a], p1, p2, erase_source=False); M.erase([a])
|
||||||
|
M.chamfer(first, second, 2, 3) # distance 2 along first, 3 along second
|
||||||
|
M.array_rect([a], rows=2, columns=3, row_spacing=10, column_spacing=20)
|
||||||
|
M.array_polar([a], center, count=4, angle=360) # counts include the original
|
||||||
|
M.explode([polyline]); M.join([line1, line2])
|
||||||
|
M.break_entity(line, first_point, second_point)
|
||||||
|
M.stretch(corner1, corner2, base, target) # crossing window, then the displacement
|
||||||
|
M.lengthen(line, 5, at=near_the_end) # delta; negative shortens
|
||||||
|
M.array_path([a], path_curve, count=5) # evenly along a curve
|
||||||
|
M.array_3d([a], rows=2, columns=2, levels=2, row_spacing=10, column_spacing=20, level_spacing=30)
|
||||||
|
M.polyline_close(pl); M.polyline_open(pl); M.polyline_reverse(pl)
|
||||||
|
M.polyline_width(line_or_pl, 0.5) # a line or arc is turned into a polyline first
|
||||||
|
M.polyline_join(pl, [line1, arc1]) # returns the merged polyline
|
||||||
|
```
|
||||||
|
|
||||||
|
Each step returns an outcome dict: `status` (`completed` or `waiting_input`),
|
||||||
|
`blocked_by`, `command`, `prompt`, `accepts` (`point`, `entity`, `selection`,
|
||||||
|
`text`, `token`, `enter`), `options` (keyword tokens), `entities`, `added`,
|
||||||
|
`unconsumed` and `error`. `c.point`, `c.text`, `c.token`, `c.entity`,
|
||||||
|
`c.selection`, `c.enter` and `c.cancel` map to those prompts; an `error` raises
|
||||||
|
`RuntimeError`, and leaving the `with` block cancels a command that is still waiting,
|
||||||
|
also closing any editor or dialog it opened. `doc.command` cancels and raises when
|
||||||
|
the line leaves a prompt open.
|
||||||
|
|
||||||
|
Selection-based tools (`move`, `copy`, `rotate`, `scale`, `mirror`, `erase`, the arrays,
|
||||||
|
`explode` and `join`) select
|
||||||
|
the entities you pass first, so the command skips its own selection prompt. Pick
|
||||||
|
points default to the middle of a line, arc or circle and the first vertex of a polyline; give `at=` for anything else.
|
||||||
|
`trim` and `extend` cut or extend against every entity in the drawing. Each command is
|
||||||
|
undone as the editor would undo it.
|
||||||
|
|
||||||
|
Guards: a command is refused while another is active (cancel it first) or when the
|
||||||
|
line names a command that could end the session, re-enter Python or change this
|
||||||
|
setting: `QUIT`, `EXIT`, `CLOSE`, `CLOSEALL`, `NEW`, `QNEW`, `OPEN`, `SAVE`, `QSAVE`,
|
||||||
|
`SAVEAS`, `SAVEALL`, `RECOVER`, `SCRIPT`, `RUNSCRIPT`, `SCRIPTCOMMANDS` and any `PY_*`.
|
||||||
|
The user can switch the whole facility off with the `SCRIPTCOMMANDS 0` command (`1`
|
||||||
|
turns it back on, plain `SCRIPTCOMMANDS` shows it); it is a saved preference, on by
|
||||||
|
default, and while it is off every `doc.command`, `start_command` and `doc.modify` call
|
||||||
|
raises `RuntimeError`. Only the command line can change it, never a script. Commands run on the active
|
||||||
|
document only. Commands that need an interactive surface a script cannot fill
|
||||||
|
(the rich-text editor, a file dialog) report it in `blocked_by` and are cancelled.
|
||||||
|
PEDIT's fit, spline, decurve and vertex-edit options are not wrapped (reach them with
|
||||||
|
`start_command("PEDIT")`); `polyline_*` return the polyline entity, which is a new
|
||||||
|
entity when the command replaced the original. Hatching has no wrapper: create it with `create_entity("Hatch", ...)`, because the
|
||||||
|
HATCH command needs an interactive boundary pick. `ocs.command_step(kind, options)`
|
||||||
|
is the raw single step behind all of this.
|
||||||
|
|
||||||
|
### Historical command-replay experiment (not in the default build)
|
||||||
|
|
||||||
|
The following records an earlier experiment and is kept for the findings, not as
|
||||||
|
instructions. It used a fire-and-forget `ocs.command()` that replayed a line through the
|
||||||
|
message loop; on OCS 2026.37 that could hang. It has been superseded by
|
||||||
|
`doc.command` / `doc.start_command` (see "Running OCS commands" above), which run the
|
||||||
|
real command synchronously through the host's `run_command` step API and were exercised
|
||||||
|
against every command tried without a hang. The prompt-sequence findings below (selection
|
||||||
|
prompts, `ALIGN`'s extra Enters) still describe how the commands behave.
|
||||||
|
|
||||||
|
**`ocs.command()` + `ocs.select()` together can apply a real, persistent
|
||||||
|
constraint, entirely from a script** — this required two host changes
|
||||||
|
(`HostApi::run_command` and `HostApi::set_selection`, `ocs_plugin_api`
|
||||||
|
v0.2.1+ built from a worktree that isn't upstream yet — see the note at the
|
||||||
|
bottom of this file), not something achievable from the plugin alone.
|
||||||
|
Verified end-to-end against a real running host, not just "it compiles":
|
||||||
|
```python
|
||||||
|
ocs.select([line1_handle, line2_handle])
|
||||||
|
ocs.command("PCONSTRAINT")
|
||||||
|
```
|
||||||
|
run as a plain `.py` file via `PY_RUN` — no automation-API help, no manual
|
||||||
|
pre-selection — ran the actual geometric solver and visibly adjusted both
|
||||||
|
lines' coordinates to be genuinely parallel (checked numerically:
|
||||||
|
direction-vector cross product ≈ 0 after, nonzero before). A real,
|
||||||
|
persistent `PCONSTRAINT` object. Same result verified for `TCONSTRAINT`
|
||||||
|
(circle-to-line tangency): center-to-line distance equals the radius
|
||||||
|
exactly after. `examples/example.py` does both — its "parallel" lines and
|
||||||
|
"tangent" circle are real constraint objects, not geometry computed once.
|
||||||
|
|
||||||
|
Why two calls, not one: constraint commands read a prior *selection* (a
|
||||||
|
`"Select objects:"` prompt), not picks fed as command-line tokens the way
|
||||||
|
`LINE`'s points are — feeding `ocs.command("PCONSTRAINT {h1} {h2}")` with
|
||||||
|
handles as trailing tokens starts the command but ends in "Command
|
||||||
|
cancelled", not a constraint. `ocs.select()` sets that selection state
|
||||||
|
first; `ocs.command()` then reads it.
|
||||||
|
|
||||||
|
**Not every command completes cleanly this way — `ALIGN` is the found
|
||||||
|
counterexample.** `ocs.command()`'s point-feeding sends exactly *one*
|
||||||
|
trailing Enter after the fed tokens, to finish the command. `ALIGN` needs
|
||||||
|
two after its point pairs (skip the optional 3rd source/destination pair,
|
||||||
|
then answer a "Scale objects? [Yes/No]" question) — so
|
||||||
|
`ocs.command("ALIGN 0,0 20,20 2,0 22,22")` **does** apply the actual
|
||||||
|
move/rotate transform correctly (verified: the entities land at the right
|
||||||
|
transformed coordinates), but leaves that Scale prompt open instead of
|
||||||
|
cleanly finishing the command. Not attempted in `examples/example.py` —
|
||||||
|
shipping something that half-completes seemed worse than leaving it out.
|
||||||
|
A general fix would need `ocs.command()` to accept a trailing-Enter *count*
|
||||||
|
(or an explicit terminator convention) instead of always exactly one;
|
||||||
|
not implemented.
|
||||||
|
|
||||||
|
**`ocs.command()` cannot invoke itself or any other plugin's command** —
|
||||||
|
only built-ins. This call is a nested plugin→host request arriving while the
|
||||||
|
plugin's own `dispatch()` is still running (its one runner thread is
|
||||||
|
blocked waiting for this exact call to return); routing it back through
|
||||||
|
normal plugin dispatch would hand that same plugin (or any plugin) a second
|
||||||
|
`Dispatch` request it has no free thread to answer, deadlocking both sides.
|
||||||
|
Found this the hard way — `ocs.command("LINE 0,0 10,10")` hung completely
|
||||||
|
before the host-side fix. `run_command` skips plugin dispatch entirely, by
|
||||||
|
design, not as an oversight.
|
||||||
|
|
||||||
|
### Which built-in commands `ocs.command()` can reach
|
||||||
|
|
||||||
|
`ocs.command()` goes through the exact same dispatcher as the interactive
|
||||||
|
command line — `HostApi::run_command` → the host's
|
||||||
|
`run_command_line_no_plugin_reentry` → `dispatch_command_inner(cmd,
|
||||||
|
allow_suggest=false, try_plugins=false)` — so almost everything typeable in
|
||||||
|
OCS also works from a script, minus one deliberate carve-out.
|
||||||
|
|
||||||
|
**Reachable: the full built-in command set**, spread across ten dispatch
|
||||||
|
families in the host's `src/app/commands/` (`fileops`, `layers`, `blocks`,
|
||||||
|
`draw`, `dim`, `inquiry`, `view`, `layerprops`, `styleprops`, `display`).
|
||||||
|
That covers everything AutoCAD-compatible the host implements natively —
|
||||||
|
drawing entities and constraints (`LINE`, `CIRCLE`, `ARC`, `POLYLINE`,
|
||||||
|
`MOVE`, `ROTATE`, `ALIGN`, `PCONSTRAINT`, `TCONSTRAINT`, in `dispatch_draw`),
|
||||||
|
dimensions (`DIMLINEAR`, `DIMALIGNED`, `DIMSTYLE`, ...), blocks (`BLOCK`,
|
||||||
|
`INSERT`, `WBLOCK`, `ATTSYNC`, ...), layers/properties (`LAYER`, `LAYISO`,
|
||||||
|
`LAYDEL`, `CHPROP`, `PROPERTIES`, ...), file ops (`NEW`, `OPEN`, `SAVE`,
|
||||||
|
`SAVEAS`, `EXPORT...`, `PLOT`, ...), inquiry (`LIST`, `DIST`, `AREA`,
|
||||||
|
`DBLIST`, ...), view (`ZOOM`, `PAN`, `VIEW`, `REGEN`, ...), and
|
||||||
|
directly-settable system variables typed as commands (`PICKBOX 5`,
|
||||||
|
`MIRRTEXT 1`, `LUPREC 4`, ...). Aliases still resolve too (`ocs.command("L
|
||||||
|
0,0 10,10")` works the same as `LINE`), since alias expansion happens before
|
||||||
|
the plugin-skip.
|
||||||
|
|
||||||
|
**Not reachable: any plugin-provided command, including this plugin's own**
|
||||||
|
(`PYTHONSHELL`, `PY_EVAL`, `PY_RUN`) — see the paragraph above for why. This
|
||||||
|
is the *only* restriction versus the interactive command line; there is no
|
||||||
|
narrower allow-list beyond it. `allow_suggest=false` also means no
|
||||||
|
autocomplete/fuzzy-matching of partial verbs (unlike typing `BAC` and
|
||||||
|
pressing Enter for `BACKGROUND`) — a script must spell out the exact command
|
||||||
|
name or a real alias.
|
||||||
|
|
||||||
|
Usage notes already verified end-to-end (see the constraint example above
|
||||||
|
and `examples/example.py`):
|
||||||
|
|
||||||
|
- Multi-point/interactive commands take their args inline on one string,
|
||||||
|
exactly as if typed then Enter: `ocs.command("LINE 0,0 10,10")`.
|
||||||
|
- A command that reads a *prior selection* rather than inline picks
|
||||||
|
(constraint commands are the concrete case) needs `ocs.select(handles)`
|
||||||
|
called first — `ocs.command()` alone can't feed a "Select objects:"
|
||||||
|
prompt.
|
||||||
|
- `ALIGN` needs two trailing Enters (skip the optional 3rd point pair, then
|
||||||
|
answer the Scale prompt); `ocs.command()` only ever sends one, so it
|
||||||
|
applies the transform but leaves that prompt dangling — see above.
|
||||||
|
|
||||||
|
For the exhaustive, exact list rather than this summary, the source of
|
||||||
|
truth is the `inventory::submit!(CommandRegistration { names: &[...] })`
|
||||||
|
blocks scattered across the host's `src/app/commands/*.rs` (105 files
|
||||||
|
register at least one command as of this writing); the largest single block
|
||||||
|
— everything without its own interactive command module — is
|
||||||
|
`src/app/commands/mod.rs`'s command-line autocomplete registry. Since it's
|
||||||
|
the same dispatcher, OCS's own command-line autocomplete is also a live
|
||||||
|
index of what `ocs.command()` can run.
|
||||||
|
|
||||||
|
**One `push_undo` group per script, not per `ocs.add_*` call.** A `PY_RUN`
|
||||||
|
script that calls `ocs.add_line` ten times undoes as one step. Verified
|
||||||
|
end-to-end: a two-line script undoes both lines in a single `undo`.
|
||||||
|
Implemented via `host_ctx::ensure_undo_started`, called lazily by the first
|
||||||
|
write in a given `PY_EVAL`/`PY_RUN` — a read-only script never touches the
|
||||||
|
undo stack. Note: `ocs.command()` does *not* go through this — a built-in
|
||||||
|
command manages its own undo the same way it would if typed, so `ocs.command`
|
||||||
|
calls are not folded into the script's shared undo group.
|
||||||
|
|
||||||
|
**`ocs.selection()` is a cache, not a live query.** `HostApi` has no
|
||||||
|
synchronous "give me the current selection" call — only a best-effort
|
||||||
|
`SelectionChanged` / `SelectionChangedV4` notification. It reflects the
|
||||||
|
selection as of the last time it changed, not necessarily the instant the
|
||||||
|
script calls it.
|
||||||
|
|
||||||
|
That cache is populated via `BuiltinPlugin::on_notification`, **not** by
|
||||||
|
calling `HostApi::try_recv_notification()` from `dispatch()`. Found the hard
|
||||||
|
way: `ocs_plugin_api::runner`'s own V4 event loop (`run_v4` in `runner.rs`)
|
||||||
|
drains that queue itself on every iteration and forwards each notification to
|
||||||
|
`on_notification` *before* a `Dispatch` request ever reaches `dispatch()` — so
|
||||||
|
polling it from inside `dispatch` always finds it empty. This plugin
|
||||||
|
overrides `on_notification` and stashes the latest selection in a
|
||||||
|
process-wide cache (`selection_cache.rs`); `ocs.selection()` reads that.
|
||||||
|
Verified end-to-end against a real host build: select an entity, then
|
||||||
|
`PY_EVAL ocs.selection()` returns its handle.
|
||||||
|
|
||||||
|
Each `PY_EVAL`/`PY_RUN` runs in a fresh interpreter (no stdlib, no session
|
||||||
|
state across calls) — REPL/session persistence is an open question for a
|
||||||
|
later phase.
|
||||||
|
|
||||||
|
**Typing or pasting `PY_EVAL`/`PY_RUN` directly into the interactive command
|
||||||
|
line is broken for anything beyond trivial arithmetic — a host issue, not
|
||||||
|
this plugin.** `Message::CommandInput` in `src/app/update/mod.rs` (this
|
||||||
|
repo) uppercases the *entire* input line on every keystroke *and* on paste,
|
||||||
|
and auto-submits the instant it contains a space (both deliberate, for
|
||||||
|
classic single-line CAD commands like `LINE 0,0 10,10`). That mangles case
|
||||||
|
(`ocs.add_line` → `OCS.ADD_LINE`, a `NameError`) and truncates arguments
|
||||||
|
(`PY_EVAL ` submits before you finish typing the expression) for *any*
|
||||||
|
multi-word, case-sensitive plugin argument — automation
|
||||||
|
(`ocs_execute`/`--mcp`) bypasses this UI path entirely, which is why it
|
||||||
|
never surfaced in this session's own testing until a live user tried typing
|
||||||
|
it by hand. **`Run Script…` (below) sidesteps this correctly** — the host
|
||||||
|
authors already solved the identical problem for file paths via
|
||||||
|
`ModuleEvent::PluginFileDialog`, which dispatches with original case intact.
|
||||||
|
There is no equivalent bypass for `PY_EVAL` today; typed/pasted `PY_EVAL`
|
||||||
|
only survives if it has no spaces and no case-sensitive identifiers.
|
||||||
|
|
||||||
|
## Ribbon
|
||||||
|
|
||||||
|
Two tools in the "Tools" group:
|
||||||
|
|
||||||
|
| Tool | Behavior |
|
||||||
|
|------|----------|
|
||||||
|
| Eval 1+1 | Dispatches `PY_EVAL 1 + 1` directly — a smoke test. |
|
||||||
|
| Run Script… | `ModuleEvent::PluginFileDialog` opens a native "pick a `.py` file" dialog; on selection the host dispatches `PY_RUN <chosen path>` back to the plugin. Cancel does nothing. |
|
||||||
|
|
||||||
|
**A real script manager UI (list/run/save scripts, or a dockable REPL
|
||||||
|
console) is not possible with today's `ocs_plugin_api`.** This was an open
|
||||||
|
question in `ROADMAP.md` — now answered by reading
|
||||||
|
`ribbon.rs`: `CadModule` exposes exactly one hook, `ribbon_groups()`, which
|
||||||
|
returns a **static** set of ribbon buttons/dropdowns (`RibbonItem`). There is
|
||||||
|
no API for a plugin to host a persistent custom panel, list dynamic content,
|
||||||
|
or render arbitrary UI — the ribbon vocabulary is deliberately "plain data
|
||||||
|
the host renders," not a widget toolkit. Getting a script list or REPL panel
|
||||||
|
would need a new `HostApi`/`CadModule` capability, i.e. an `ocs_plugin_api`
|
||||||
|
version bump — a host-side feature, out of scope for a plugin repo. `Run
|
||||||
|
Script…` (above) is the most a plugin can do today: reuse the host's own
|
||||||
|
native file picker via the existing `PluginFileDialog` event, which was
|
||||||
|
already there for other plugins to import files.
|
||||||
|
|
||||||
|
## AutoLISP migration
|
||||||
|
|
||||||
|
An AutoLISP-to-Python translator is a separate project and is not part of this
|
||||||
|
repository: scripts written for this plugin use the `ocs` module and the document
|
||||||
|
model described above, and a translated macro would run through `PY_RUN` like any
|
||||||
|
other script. Nothing in the plugin depends on it.
|
||||||
|
|
||||||
|
## XDATA
|
||||||
|
|
||||||
|
`ocs.read_record`/`ocs.write_record`/`ocs.remove_record` wrap
|
||||||
|
`HostApi::read_record`/`write_record`/`remove_record` — already implemented
|
||||||
|
by the host (unlike `run_command`/`set_selection`, these needed no host
|
||||||
|
change or `[patch]` entry). A record is `{"app_name": str, "values": [...]}`;
|
||||||
|
each value is `{"kind": str, "value": ...}`. Supported kinds and their
|
||||||
|
Python `value` shape:
|
||||||
|
|
||||||
|
| `kind` | Python `value` |
|
||||||
|
|---|---|
|
||||||
|
| `String`, `ControlString`, `LayerName` | `str` |
|
||||||
|
| `BinaryData` | `bytes` |
|
||||||
|
| `Handle` | `int` |
|
||||||
|
| `Point3D`, `Position3D`, `Displacement3D`, `Direction3D` | `[x, y, z]` (`float`) |
|
||||||
|
| `Real`, `Distance`, `ScaleFactor` | `float` |
|
||||||
|
| `Integer16`, `Integer32` | `int` |
|
||||||
|
|
||||||
|
```python
|
||||||
|
ocs.write_record(handle, "MYAPP", [
|
||||||
|
{"kind": "String", "value": "part-042"},
|
||||||
|
{"kind": "Integer32", "value": 7},
|
||||||
|
])
|
||||||
|
record = ocs.read_record(handle, "MYAPP") # {"app_name": "MYAPP", "values": [...]}
|
||||||
|
ocs.remove_record(handle, "MYAPP")
|
||||||
|
```
|
||||||
|
|
||||||
|
This `{app_name, values}`/`{kind, value}` shape is deliberately the same one
|
||||||
|
`schoeller/ocs_python_repl` (a separate, out-of-process PyO3-based Python
|
||||||
|
plugin for OCS) uses in its `ocs.doc.read_record`/`write_record`, so a
|
||||||
|
script's XDATA handling ports between the two plugins unchanged. `write_record`
|
||||||
|
starts the script's shared undo group the same way `ocs.add_*` does (see
|
||||||
|
below); `remove_record` only starts it when a record actually existed to
|
||||||
|
remove.
|
||||||
|
|
||||||
|
## Build note: bundled host API
|
||||||
|
|
||||||
|
`Cargo.toml` uses the repository-relative `ocs_plugin_api` crate. Packaging
|
||||||
|
builds the plugin with the same compiler and CAD codec as the host and stages
|
||||||
|
matching metadata beside the library. The `experimental-command-replay` Cargo
|
||||||
|
feature keeps the old bridge code available, but the tested nested-command
|
||||||
|
path can hang. Do not enable it for production.
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
# opencad-python
|
||||||
|
|
||||||
|
Python scripting for Open CAD Studio, shipped as a bundled first-party plugin. Embeds
|
||||||
|
[RustPython](https://github.com/RustPython/RustPython) and exposes an `ocs`
|
||||||
|
module wrapping `HostApi`, so `PY_`-prefixed commands can run Python against
|
||||||
|
the open document.
|
||||||
|
|
||||||
|
The crate remains an independent process plugin under `plugins/` so Python
|
||||||
|
cannot crash the editor process and all writes still cross the versioned
|
||||||
|
`HostApi`. Its API dependency is repository relative, and the macOS packaging
|
||||||
|
flow builds and places it in the application bundle automatically.
|
||||||
|
|
||||||
|
Full design and phased plan: `ROADMAP.md` in this directory.
|
||||||
|
Command reference, the `ocs` module's functions, and every real gap/limit
|
||||||
|
found while building this: `PLUGIN.md` in this directory.
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
The API v7 build provides `PY_EVAL`/`PY_RUN`, the read/write `ocs` module, and
|
||||||
|
the ribbon integration. On top of that, the `experimental-host-model` feature
|
||||||
|
(the name stays until a later API cleanup; the staged bundled plugin is built with
|
||||||
|
it) adds a general Python document model over the host API:
|
||||||
|
|
||||||
|
- **Entities:** create, read, edit, delete and undo for all 43 canvas kinds
|
||||||
|
(41 creatable), validated by the host, with per-kind DWG/DXF round-trip audits.
|
||||||
|
- **Drawing tables:** `doc.layers`, `text_styles`, `dim_styles`, `blocks` (and their
|
||||||
|
contents), `linetypes` and `layouts`, plus kernel-backed solids (`doc.solids`).
|
||||||
|
- **Commands:** `doc.command`, `doc.start_command` and `doc.modify` (offset, trim,
|
||||||
|
extend, fillet, chamfer, move, copy, rotate, scale, mirror, arrays, explode, join,
|
||||||
|
break, stretch, lengthen, PEDIT polyline edits) drive the real OCS commands.
|
||||||
|
|
||||||
|
The design and guarantees are in `../../docs/plugin-host-model.md`, the per-kind
|
||||||
|
evidence in `../../docs/plugin-host-model-coverage-ledger.md`, and the script-facing
|
||||||
|
reference in `PLUGIN.md`. The older experimental `ocs.command()` replay is
|
||||||
|
superseded and not in the default build.
|
||||||
|
|
||||||
|
## Files
|
||||||
|
|
||||||
|
| File | Purpose |
|
||||||
|
|------|---------|
|
||||||
|
| `Cargo.toml` | `cdylib` crate depending on `ocs_plugin_api` (`host` feature) and `rustpython-vm` (stdlib disabled — see `PLUGIN.md`'s sandboxing section) |
|
||||||
|
| `src/lib.rs` | manifest + `CadModule` ribbon + `BuiltinPlugin` + `export_plugin!` + `PY_EVAL`/`PY_RUN` dispatch |
|
||||||
|
| `src/ocs_module.rs` | the `ocs` Python module (`selection`, `get`, drawing access; experimental `command`/`select` are feature-gated) |
|
||||||
|
| `src/host_ctx.rs` | thread-local bridge from `dispatch()`'s `HostApi` into the `#[pymodule]` native functions |
|
||||||
|
| `src/selection_cache.rs` | process-wide selection cache, populated via `on_notification` |
|
||||||
|
| `src/document_model.py` | API v7 Python document view and transaction context manager |
|
||||||
|
| `src/event_cache.rs`, `src/input_cache.rs` | bounded event queue and interactive-pick results |
|
||||||
|
| `tools/stage-bundled.sh` | build and stage the matching API v7 package |
|
||||||
|
| `plugin.toml` | metadata read by the host (mirrors the manifest) |
|
||||||
|
| `examples/example.py` | a script demonstrating shapes plus two real, persistent constraints |
|
||||||
|
| `../../.github/workflows/release.yml` | bundles the cdylib into the macOS application |
|
||||||
|
| `PLUGIN.md` | command reference, the `ocs` module, and every real gap/limit found |
|
||||||
|
|
||||||
|
## Build
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo build --release --locked --features experimental-host-model \
|
||||||
|
--manifest-path plugins/opencad-python/Cargo.toml
|
||||||
|
```
|
||||||
|
|
||||||
|
## Stage the bundled plugin
|
||||||
|
|
||||||
|
The staging script builds against the in-tree `ocs_plugin_api`, writes exact
|
||||||
|
compiler and CAD codec metadata, and creates the directory layout consumed by
|
||||||
|
bundled plugin discovery.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
bash plugins/opencad-python/tools/stage-bundled.sh /path/to/stage-directory
|
||||||
|
```
|
||||||
|
|
||||||
|
Add `--debug` for a faster local build. Build with the same Rust toolchain as
|
||||||
|
the OCS binary; the host checks the compiler version when loading plugins.
|
||||||
|
|
||||||
|
```python
|
||||||
|
doc = ocs.active_document
|
||||||
|
line = doc.create_entity("Line", start={"x": 0, "y": 0, "z": 0},
|
||||||
|
end={"x": 10, "y": 0, "z": 0})
|
||||||
|
line = doc.entities[handle]
|
||||||
|
print(line.start, line.end, line.layer, line.coverage)
|
||||||
|
with doc.transaction("Move line"):
|
||||||
|
line.start = (0, 0, 0)
|
||||||
|
line.end = (10, 0, 0)
|
||||||
|
|
||||||
|
doc.selection = [line]
|
||||||
|
token = doc.request_point("Pick destination")
|
||||||
|
# After the host has collected the click, run another script:
|
||||||
|
result = doc.poll_input(token)
|
||||||
|
events = doc.poll_events()
|
||||||
|
doc.delete_entity(line)
|
||||||
|
```
|
||||||
|
|
||||||
|
`doc.entities` iterates every document entity. The generated Python schema
|
||||||
|
currently edits Point, Line, Circle, Arc, Ellipse, Polyline, Polyline2D,
|
||||||
|
Polyline3D, LwPolyline, Spline, Text, MText, Ray, XLine, Solid, Face3D,
|
||||||
|
Insert, Tolerance, Shape, AttributeDefinition, AttributeEntity, and Hatch.
|
||||||
|
Insert block references support edits to placement and transform
|
||||||
|
properties; their block name is readable and creation is not yet exposed.
|
||||||
|
Other canvas kinds expose
|
||||||
|
handle, kind, and layer; their layer can be changed in a transaction. Internal
|
||||||
|
and opaque kinds remain read-only. Each
|
||||||
|
mapped entity reports its actual readable/editable keys through `coverage`.
|
||||||
|
The host-owned catalog classifies all 48 entity variants and tracks every
|
||||||
|
traced field, including fields marked `unmapped`. Query it with
|
||||||
|
`doc.coverage()` or `doc.coverage("Line")`; each row includes source field,
|
||||||
|
type, access, and current validation status. Geometry edits remain limited to
|
||||||
|
the 43 mapped kinds.
|
||||||
|
For any entity, `entity.snapshot` returns a detached dictionary of its raw
|
||||||
|
CAD fields, including `snapshot["common"]` and kind-specific nested values.
|
||||||
|
It can inspect an unmapped kind; editing the dictionary does
|
||||||
|
not commit changes to the drawing.
|
||||||
|
Point and entity requests return a token because `PY_RUN` uses a fresh
|
||||||
|
interpreter for each invocation; `poll_input` reports pending, picked, or
|
||||||
|
cancelled on a later run in the same drawing tab. Another tab cannot consume
|
||||||
|
that token. `doc.selection` preserves the exact requested handle order and
|
||||||
|
rejects duplicate or absent handles. `poll_events` drains tab-scoped drawing, selection,
|
||||||
|
and active-command state changes. Each tab retains up to 256 events; an
|
||||||
|
`{"type": "overflow", "dropped": n}` event means older events were lost, so
|
||||||
|
refresh the document and selection before acting on cached state.
|
||||||
|
|
||||||
|
## Test locally as a bundled plugin
|
||||||
|
|
||||||
|
```sh
|
||||||
|
bash plugins/opencad-python/tools/stage-bundled.sh \
|
||||||
|
work/bundled-plugins/opencad.python --debug
|
||||||
|
OCS_BUNDLED_PLUGINS_DIR="$PWD/work/bundled-plugins" cargo run -- --new
|
||||||
|
```
|
||||||
|
|
||||||
|
The macOS release and signed packaging scripts perform this staging inside
|
||||||
|
`OpenCADStudio.app/Contents/Resources/plugins/opencad.python` automatically.
|
||||||
@@ -0,0 +1,389 @@
|
|||||||
|
# Open CAD Studio — Python Scripting & AutoLISP Migration Plan
|
||||||
|
|
||||||
|
**Status:** Phase 1 is done and host-verified, and the general document model that
|
||||||
|
followed (entities, drawing tables, block contents and the command runner) is described in
|
||||||
|
[`../../docs/plugin-host-model.md`](../../docs/plugin-host-model.md). Phase 2 (an AutoLISP
|
||||||
|
translator) is a separate project that is not part of this repository. This file is kept as
|
||||||
|
the original planning document and Phase 1 build log.
|
||||||
|
|
||||||
|
**Author:** Open CAD Studio contributors
|
||||||
|
**Date:** September 2026
|
||||||
|
|
||||||
|
This document plans embedded Python scripting for Open CAD Studio as an
|
||||||
|
**external plugin** (not a host change), followed by a best-effort AutoLISP →
|
||||||
|
Python transpiler built on top of it. It supersedes the host-embedded design
|
||||||
|
sketched in an earlier draft of this document: scripting fits OCS's existing
|
||||||
|
plugin model better than it fits inside the host. OpenCADStudio's
|
||||||
|
`docs/plugin-architecture.md` explicitly lists "sandboxed scripting
|
||||||
|
(Python/Lua)" as a non-goal of the external-plugin *system* itself — this
|
||||||
|
plan doesn't touch that system, it just builds a plugin that happens to
|
||||||
|
embed an interpreter, same as any plugin embeds whatever dependency it
|
||||||
|
needs.
|
||||||
|
|
||||||
|
**Why a plugin, not a host feature:**
|
||||||
|
|
||||||
|
| | Host-embedded | Plugin (this plan) |
|
||||||
|
|---|---|---|
|
||||||
|
| Requires OCS core changes and maintainer sign-off | Yes | No — ships from an independent repo, installed via the existing Plugin Manager |
|
||||||
|
| Crash isolation | Relies on RustPython's memory safety alone | Gets OS-process isolation for free (plugins already run out-of-process) |
|
||||||
|
| Distribution | Bundled into every OCS release, forever | Opt-in install, versioned independently, can iterate fast |
|
||||||
|
| Cost | New maintenance burden on the host | Same ABI-pinning cost every plugin already has (see Phase 1, Risk) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 1 — Python scripting plugin
|
||||||
|
|
||||||
|
**Goal:** a working bundled `opencad-python` plugin (`cdylib`) that embeds
|
||||||
|
RustPython and exposes an `ocs` module wrapping `HostApi` while retaining the
|
||||||
|
out-of-process runner boundary.
|
||||||
|
|
||||||
|
### 1.1 — Scaffold
|
||||||
|
|
||||||
|
- [x] New repo from OpenCADStudio's `docs/plugin-template/`; `plugin.toml`
|
||||||
|
+ `Cargo.toml` pinning `ocs_plugin_api` (`host` feature) and matching the
|
||||||
|
target host's `acadrust_source` / `rustc_version` (see Risks). Scaffolded
|
||||||
|
locally at `~/Documents/MacApps/opencad-python` (this repo — no remote
|
||||||
|
yet at the time, not pushed anywhere).
|
||||||
|
- [x] Add RustPython as a dependency; confirm it builds cleanly as part of a
|
||||||
|
`cdylib` on **macOS** (arm64) — Windows/Linux still unverified. Used
|
||||||
|
crates.io `rustpython-vm = "0.5"` (not the `rustpython` facade crate;
|
||||||
|
matches how the upstream `examples/hello_embed.rs` embeds it). Builds
|
||||||
|
clean, no warnings: `libopencad_python.dylib`, 17MB, ~80s from a cold
|
||||||
|
`cargo clean` release build. Exports the expected
|
||||||
|
`ocs_plugin_register` / `ocs_plugin_api_version` C-ABI symbols. A
|
||||||
|
`PY_HELLO` command runs a real RustPython smoke test (compiles and
|
||||||
|
evaluates `1 + 1` via `Interpreter::without_stdlib`) — confirms the
|
||||||
|
interpreter actually runs inside the cdylib, not just that it links.
|
||||||
|
One API gap vs. the upstream example: 0.5.0's `Vm::compile` takes an
|
||||||
|
owned `String` filename (not `&str`), and `CompileError` has no
|
||||||
|
`into_pyexception` method — worked around by matching on the `Result`
|
||||||
|
directly instead of using `?` with `PyResult`.
|
||||||
|
|
||||||
|
### 1.2 — Minimal `ocs` module (read-only)
|
||||||
|
|
||||||
|
- [x] `ocs.selection()` → list of entity handles. Implemented as a cache, not
|
||||||
|
a live query — `HostApi` has no synchronous "current selection" call
|
||||||
|
(only a best-effort `SelectionChanged`/`SelectionChangedV4`
|
||||||
|
notification). Populated via `BuiltinPlugin::on_notification` into a
|
||||||
|
process-wide static (`selection_cache.rs`) — see the host-runtime
|
||||||
|
verification note below for why `dispatch`-time polling doesn't work.
|
||||||
|
Documented as a real limitation in `PLUGIN.md`, not silently papered
|
||||||
|
over.
|
||||||
|
- [x] `ocs.get(handle)` → read-only geometry/property access, via
|
||||||
|
`HostApi::document_reader()` (zero-copy) + `for_each_entity`, matching
|
||||||
|
by handle. Returns `{handle, kind, layer, point}` or `None`.
|
||||||
|
- [x] `PY_EVAL <expr>` command (`command_prefixes = ["PY_"]`): evaluate one
|
||||||
|
inline expression, print the result via `host.push_output`. Runs a
|
||||||
|
fresh, stdlib-free `Interpreter` per call with only the `ocs` native
|
||||||
|
module registered (`Interpreter::builder(...).add_native_module(...)`)
|
||||||
|
— no `import os`/`socket`/etc. is even possible since no stdlib is
|
||||||
|
loaded, which happens to satisfy most of §1.5's sandboxing goal already
|
||||||
|
as a side effect of keeping this phase minimal, not a deliberate
|
||||||
|
Phase 1.5 pass yet.
|
||||||
|
- [x] Errors: both compile errors (`CompileError`, which implements
|
||||||
|
`Display` directly — no `into_pyexception` needed) and runtime
|
||||||
|
exceptions (formatted as `"<TypeName>: <message>"`, no traceback yet)
|
||||||
|
go to `host.push_error`.
|
||||||
|
- [ ] Bridging `host: &mut dyn HostApi` into the `#[pymodule]` native
|
||||||
|
functions needed a thread-local raw-pointer scratch slot
|
||||||
|
(`host_ctx.rs`) with a documented safety argument, since
|
||||||
|
`add_native_module` wants `&'static PyModuleDef` — there's no closure
|
||||||
|
capture available to a native pyfunction. Worth a second pair of eyes;
|
||||||
|
it's sound as written (guard clears the slot before the real borrow
|
||||||
|
ends, single-threaded, non-reentrant) but is the one genuinely
|
||||||
|
load-bearing `unsafe` block in the plugin so far.
|
||||||
|
- [x] Verified: `cargo build`/`--release` clean, zero warnings, against the
|
||||||
|
real `ocs_plugin_api`/`rustpython-vm` 0.5.0 APIs (not guessed — traced
|
||||||
|
through the actual crate sources for `HostApi`, `DocumentReader`,
|
||||||
|
`InterpreterBuilder`, `ToPyObject`/`DictKey` impls, etc.).
|
||||||
|
- [x] **Host-runtime verified**, not just "compiles": built the actual OCS
|
||||||
|
host (debug, ~1m43s), installed the plugin, drove it through the real
|
||||||
|
`--mcp` automation API with an isolated `$HOME` (so the test couldn't
|
||||||
|
collide with an already-running instance — see below, that mistake cost
|
||||||
|
real time). Confirmed working end-to-end:
|
||||||
|
- `PY_EVAL 6 * 7` → `"42"`.
|
||||||
|
- `PY_EVAL 1 / 0` → `"ZeroDivisionError: division by zero"` via
|
||||||
|
`host.push_error` — not a silent no-op.
|
||||||
|
- `ocs.get(handle)` on a drawn `LINE` → correct
|
||||||
|
`{'handle': 98, 'kind': 'line', 'layer': '0', 'point': None}`.
|
||||||
|
- Along the way found and fixed a real bug: `PY_EVAL`'s `ocs` name was
|
||||||
|
never bound in scope (scripts would need `import ocs`, impossible
|
||||||
|
under `Mode::Eval`, which only accepts one expression). Fixed by
|
||||||
|
`vm.import("ocs", 0)` + `scope.globals.set_item` before compiling —
|
||||||
|
`ocs` is now pre-bound, no import needed or possible.
|
||||||
|
- **Found and fixed a second real bug, this one plugin-side, not the
|
||||||
|
host's**: `ocs.selection()` always returned `[]`. Root cause (found by
|
||||||
|
temporarily instrumenting the host, then reverted — no host changes
|
||||||
|
were needed): `ocs_plugin_api::runner`'s own V4 event loop (`run_v4`
|
||||||
|
in `runner.rs`) drains `HostApi::try_recv_notification()` on every
|
||||||
|
iteration and forwards each notification to
|
||||||
|
`BuiltinPlugin::on_notification` — *before* a `Dispatch` request ever
|
||||||
|
reaches `dispatch()`. Polling `try_recv_notification()` from inside
|
||||||
|
`dispatch` (what the plugin did) therefore always sees an empty
|
||||||
|
queue; the host's `SelectionChangedV4` broadcast
|
||||||
|
(`notify_plugins_selection_changed` /
|
||||||
|
`publish_selection_changed_v4` in `src/plugin/v4_support.rs`) was
|
||||||
|
firing correctly the whole time. Fix: override `on_notification` and
|
||||||
|
stash the selection in a process-wide cache instead
|
||||||
|
(`opencad-python`'s `selection_cache.rs`); `dispatch` and
|
||||||
|
`ocs.selection()` just read that. Verified end-to-end: select an
|
||||||
|
entity, then `PY_EVAL ocs.selection()` returns its handle.
|
||||||
|
- Worth folding into this doc's guidance for anyone writing a V4+
|
||||||
|
plugin: **notifications must be consumed via `on_notification`, not
|
||||||
|
by polling `try_recv_notification()` from `dispatch`** — the stock
|
||||||
|
runner loop already drains that queue for you.
|
||||||
|
- **Testing pitfall worth remembering**: `--mcp` doesn't run headless —
|
||||||
|
it's a thin JSON-RPC client that reuses any already-running OCS
|
||||||
|
instance it finds under `$HOME/Library/Application Support/
|
||||||
|
OpenCADStudio/automation` (`descriptors()` in `src/mcp.rs`), spawning
|
||||||
|
a fresh one only if none exists. First test run silently talked to
|
||||||
|
the *user's own already-running production app* (which obviously had
|
||||||
|
never seen this plugin — plugins load once at startup) instead of the
|
||||||
|
freshly built debug binary. Fix: override `$HOME` for the test
|
||||||
|
subprocess to a scratch directory, which isolates `config_dir()`,
|
||||||
|
`plugins_dir()` and the automation discovery directory all at once.
|
||||||
|
- macOS only, per current scope; Windows/Linux still unverified.
|
||||||
|
|
||||||
|
### 1.3 — Write access + scripts
|
||||||
|
|
||||||
|
- [x] `ocs.add_line(x1, y1, x2, y2)` / `ocs.add_circle(x, y, radius)` — 2D
|
||||||
|
only for now (z=0, layer `"0"`), wrapped so a whole script is **one**
|
||||||
|
`host.push_undo` group, not one per call (`host_ctx::ensure_undo_started`,
|
||||||
|
called lazily by the first write). Verified end-to-end: a `PY_RUN`
|
||||||
|
script that calls `ocs.add_line` twice undoes both lines in one `undo`.
|
||||||
|
Take `rustpython_vm::function::ArgIntoFloat`, not a bare `f64` — found
|
||||||
|
by actually running `ocs.add_line(0, 0, 10, 10)` (plain ints, the
|
||||||
|
natural way to write it) and hitting a `TypeError`: unlike CPython's
|
||||||
|
C-function argument parsing, a bare `f64` `#[pyfunction]` parameter in
|
||||||
|
RustPython does not implicitly coerce an `int`.
|
||||||
|
- [x] `PY_RUN <path.py>` to run a file (`Mode::Exec`, so statements are
|
||||||
|
allowed, unlike `PY_EVAL`'s `Mode::Eval`). Same error reporting as
|
||||||
|
`PY_EVAL`: a missing file or a raised exception is never a silent
|
||||||
|
no-op. Reusing the automation `run` op needed no transport changes, as
|
||||||
|
expected — `{"op":"run","cmd":"PY_RUN <path>"}` just works.
|
||||||
|
- [x] `ocs.command(cmd)` to invoke existing built-in commands by name —
|
||||||
|
**implemented, required a host change**. Added `HostApi::run_command`
|
||||||
|
(default `Err` impl, no forced version bump) by reusing
|
||||||
|
`run_command_line` + `drive_headless_task` — the exact machinery
|
||||||
|
`--serve`/`--mcp` automation's `"run"` op already uses — via a new
|
||||||
|
`PluginRequest::RunCommand` and one match arm in
|
||||||
|
`handle_plugin_request`. Full detail: OpenCADStudio's
|
||||||
|
`docs/plugin-architecture.md`'s `HostApi` table, and this plugin's own
|
||||||
|
`PLUGIN.md`.
|
||||||
|
- **Found and fixed a real deadlock along the way**: the naive version
|
||||||
|
routed back through normal plugin dispatch, which — since this call
|
||||||
|
is a nested plugin→host request arriving *while* the calling
|
||||||
|
plugin's `dispatch()` is still running on its one runner thread —
|
||||||
|
sends that same plugin a second `Dispatch` it has no free thread to
|
||||||
|
answer. Both sides wait forever. Fixed by skipping plugin dispatch
|
||||||
|
entirely for this one call path
|
||||||
|
(`dispatch_command_no_plugin_reentry` /
|
||||||
|
`run_command_line_no_plugin_reentry`); confirmed via the full
|
||||||
|
`cargo test --lib` suite (1040 passed, 1 pre-existing unrelated
|
||||||
|
failure) that normal command-line/automation behavior is unchanged.
|
||||||
|
Consequence, by design: `ocs.command()` can reach built-ins only,
|
||||||
|
never another plugin's command.
|
||||||
|
- **Verified against a real, non-trivial case, not just `LINE`**:
|
||||||
|
pre-selecting two non-parallel lines then `ocs.command("PCONSTRAINT")`
|
||||||
|
ran the actual geometric solver and adjusted both lines to be
|
||||||
|
genuinely parallel — checked numerically (direction-vector cross
|
||||||
|
product ≈ 0 after), a real persistent constraint object.
|
||||||
|
- **Gap found, then closed same session**: constraint commands read a
|
||||||
|
prior *selection*, not picks fed as command tokens — feeding handles
|
||||||
|
as trailing `PCONSTRAINT` tokens starts the command but ends in
|
||||||
|
"Command cancelled", not a constraint. Added `HostApi::set_selection`
|
||||||
|
(same shape as `run_command`: new `PluginRequest::SetSelection`,
|
||||||
|
default-`Err` trait method, no forced version bump; validates every
|
||||||
|
handle exists before changing anything) and `ocs.select(handles)` on
|
||||||
|
top of it. Re-verified **fully scripted, no automation-API help**: a
|
||||||
|
plain `.py` file via `PY_RUN` calling `ocs.select([h1, h2])` then
|
||||||
|
`ocs.command("PCONSTRAINT")` produces the same genuinely-parallel
|
||||||
|
result as before, now reachable entirely from a script. Confirmed no
|
||||||
|
regressions via the full `cargo test --lib` suite both times (1040
|
||||||
|
passed, 1 pre-existing unrelated font-fallback failure).
|
||||||
|
- [x] **`ocs.add_points(points)` and XDATA CRUD
|
||||||
|
(`ocs.read_record`/`write_record`/`remove_record`), ported from
|
||||||
|
reviewing `schoeller/ocs_python_repl`** — a separate, independently
|
||||||
|
maintained out-of-process PyO3-based Python plugin for OCS (real
|
||||||
|
CPython + IPython in a terminal, generated typed bindings) reviewed for
|
||||||
|
reusable ideas. Both needed **no host change**: `HostApi::add_entities`
|
||||||
|
(batch add) and `read_record`/`write_record`/`remove_record` (XDATA)
|
||||||
|
already existed in `ocs_plugin_api`, unused by this plugin until now —
|
||||||
|
unlike `run_command`/`set_selection` in §1.3, which needed new `HostApi`
|
||||||
|
methods. `add_points` batches many points into one
|
||||||
|
`host.add_entities()` call instead of looping `add_entity`, so the host
|
||||||
|
pays for undo/dirty/geometry-rebuild bookkeeping once per batch, not
|
||||||
|
once per point — the in-process analogue of `ocs_python_repl`'s
|
||||||
|
`ocs.doc.add_many(...)`, which batches to avoid one IPC round trip per
|
||||||
|
point instead. The XDATA functions deliberately reuse
|
||||||
|
`ocs_python_repl`'s exact `{app_name, values}`/`{kind, value}` record
|
||||||
|
shape (see this plugin's `PLUGIN.md`'s XDATA section) so a script's
|
||||||
|
XDATA handling ports between the two plugins unchanged. Verified with
|
||||||
|
unit tests that run a real RustPython interpreter (no live `HostApi`)
|
||||||
|
and assert that every new function gets all the way through its own
|
||||||
|
argument/dict parsing — down to every `XDataValue` kind — before
|
||||||
|
failing on the expected "not running inside a PY_ command" sentinel;
|
||||||
|
`cargo test`/`cargo clippy --all-targets` both clean. Not yet verified
|
||||||
|
against a real running host (the "host-runtime verified" bar the rest
|
||||||
|
of this phase holds itself to) — that still needs a live OCS build, as
|
||||||
|
noted for `ocs.command()`/`ocs.select()` above.
|
||||||
|
|
||||||
|
### 1.4 — Usability
|
||||||
|
|
||||||
|
- [x] **Open question resolved by reading `ribbon.rs` end to end, not
|
||||||
|
assumed**: a script manager UI (or a dockable REPL console) is **not
|
||||||
|
possible** with today's `ocs_plugin_api`. `CadModule` exposes exactly
|
||||||
|
one hook, `ribbon_groups()`, returning a *static* set of
|
||||||
|
buttons/dropdowns (`RibbonItem`) — there is no API for a plugin to host
|
||||||
|
a persistent custom panel or render dynamic content (a script list, a
|
||||||
|
REPL buffer, ...). That needs a new `HostApi`/`CadModule` capability —
|
||||||
|
an `ocs_plugin_api` version bump, a host feature request. Out of scope
|
||||||
|
for a plugin repo; documented as a real, checked answer in this
|
||||||
|
plugin's own `PLUGIN.md`, not left open.
|
||||||
|
- [x] `ModuleEvent::PluginFileDialog` (already exists) for "Run Script…":
|
||||||
|
opens a native file picker filtered to `.py`, and on selection the host
|
||||||
|
dispatches `PY_RUN <path>` back to the plugin — no new plugin code
|
||||||
|
needed beyond the ribbon entry, since `PY_RUN` already exists from
|
||||||
|
§1.3. Verified the plugin still loads and dispatches correctly with the
|
||||||
|
new ribbon entry; the file-picker interaction itself isn't automatable
|
||||||
|
headlessly over `--mcp` (no way to drive a native OS dialog over
|
||||||
|
JSON-RPC), so that specific interaction is unverified beyond "doesn't
|
||||||
|
crash". "Save Script As…" was dropped — with no in-app editor (which
|
||||||
|
needs the same missing custom-panel capability above), there's no
|
||||||
|
script content to save.
|
||||||
|
|
||||||
|
### 1.5 — Sandboxing
|
||||||
|
|
||||||
|
- [x] Audit: the `ocs` module is the *only* thing a script can call — done,
|
||||||
|
and **the earlier assumption was wrong, which is exactly why this was
|
||||||
|
worth auditing instead of assuming**. Phase 1.2/1.3 claimed "no stdlib
|
||||||
|
is loaded, so `import os`/`socket`/`subprocess` is already impossible"
|
||||||
|
— true for those three names, but RustPython 0.5.0's `host_env` Cargo
|
||||||
|
feature is **on by default** and bakes `posix`/`_ctypes` into every
|
||||||
|
interpreter's core module registry regardless of `rustpython-stdlib`.
|
||||||
|
Confirmed by actually running it: with `host_env` on,
|
||||||
|
`PY_EVAL __import__('posix').getcwd()` and
|
||||||
|
`PY_EVAL open('/etc/passwd').read()` both worked — full filesystem
|
||||||
|
read/write from any script. Fixed: `rustpython-vm` now builds with
|
||||||
|
`default-features = false, features = ["compiler", "gc"]`.
|
||||||
|
Re-verified the full matrix after: `os`/`posix`/`nt`/`subprocess`/
|
||||||
|
`socket`/`ctypes`/`_ctypes`/`_socket`/`_subprocess`/`_signal`/`pwd`
|
||||||
|
all blocked, `open()` blocked for both read and write (its `FileIO`
|
||||||
|
needs `host_env` internally too, even though `_io` itself is always
|
||||||
|
registered). No functional regression — `ocs.add_line` and the full
|
||||||
|
`examples/example.py` (both real constraints) still run correctly.
|
||||||
|
Audited what remains exhaustively rather than assuming "fewer is
|
||||||
|
enough": 15 `sys.modules` entries, all core language/import/codec
|
||||||
|
plumbing plus `ocs`. One accepted, documented residual gap: `_thread`
|
||||||
|
is real and functional (verified callable) and has no feature guard
|
||||||
|
at all in this RustPython version — no dependency-level way to
|
||||||
|
remove it without patching RustPython. Grants no filesystem/network/
|
||||||
|
process access; worst case is a resource/stability issue local to
|
||||||
|
the already crash-isolated plugin process. Full detail in this
|
||||||
|
plugin's own `PLUGIN.md`.
|
||||||
|
|
||||||
|
### 1.6 — Distribution
|
||||||
|
|
||||||
|
- [ ] Publish binaries per platform on GitHub Releases (matches every other
|
||||||
|
plugin's release shape already documented in OpenCADStudio's
|
||||||
|
`plugin-architecture.md`).
|
||||||
|
- [ ] Manual repo link works immediately (`owner/repo`, no OCS PR needed);
|
||||||
|
listing in OpenCADStudio's curated `plugins/registry.json` is a
|
||||||
|
separate, optional later step once the plugin is stable.
|
||||||
|
|
||||||
|
**Risk to track continuously:** a plugin must match the host's exact
|
||||||
|
`rustc_version` and `acadrust_source` (API v4+ enforces this at load time).
|
||||||
|
Every OCS host release potentially requires a matching rebuild + republish of
|
||||||
|
this plugin, or users get a version-mismatch refusal. Budget for this as an
|
||||||
|
ongoing CI job (build matrix triggered off OCS's release tags), not a one-time
|
||||||
|
cost.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 2 — AutoLISP → Python parser/translator
|
||||||
|
|
||||||
|
**This phase lives in a separate project that is not part of this repository.** The sub-goals below are the original
|
||||||
|
scoping; §2.2/2.3 shipped with substantially wider builtin coverage than
|
||||||
|
first planned (measured from a real AutoLISP corpus sample, not just the
|
||||||
|
constructs listed here).
|
||||||
|
|
||||||
|
**Goal:** a best-effort, offline source-to-source translator from `.lsp` to
|
||||||
|
the Phase 1 plugin's Python dialect. It is explicitly **not** an interpreter —
|
||||||
|
output is a draft a human reviews and finishes, not a guaranteed-correct
|
||||||
|
program. That's what makes this tractable where a live AutoLISP runtime isn't
|
||||||
|
(see the earlier discussion: the language core is easy, AutoCAD's builtin
|
||||||
|
library is the hard, open-ended part — a translator only needs a lookup table
|
||||||
|
for the builtins it recognizes, not a faithful live implementation of all of
|
||||||
|
them).
|
||||||
|
|
||||||
|
### 2.1 — Corpus & scoping
|
||||||
|
|
||||||
|
- [x] Pull a representative sample from [Lee Mac's routines](https://lee-mac.com/)
|
||||||
|
and the [Whole-Spec catalog](https://whole-spec.com/en/cad-tips/lisp-catalog/)
|
||||||
|
(157 curated routines) to find the actual distribution of constructs
|
||||||
|
used in real scripts — don't guess coverage priorities, measure them.
|
||||||
|
- [x] From that sample, explicitly decide and document what's out of scope:
|
||||||
|
**`vla-*`/`vlax-*` (COM/ActiveX)** — doesn't run in AutoCAD for Mac
|
||||||
|
either, so this isn't a new limitation — and **DCL dialogs** (no
|
||||||
|
renderer in OCS). Both get left as commented-out LISP with a
|
||||||
|
`# TODO: manual port needed` marker in the generated output, never
|
||||||
|
silently dropped.
|
||||||
|
|
||||||
|
### 2.2 — Reader & core-language transform
|
||||||
|
|
||||||
|
- [x] S-expression tokenizer/parser (standalone, no OCS runtime dependency).
|
||||||
|
- [x] AST-to-AST transform for the Lisp core: `setq`, `defun`
|
||||||
|
(`C:CMDNAME` → a Python function), `if`/`cond`, `lambda`/`function`,
|
||||||
|
arithmetic, string/list operations, `foreach`/`while`.
|
||||||
|
|
||||||
|
### 2.3 — Builtin mapping table
|
||||||
|
|
||||||
|
- [x] `entget` → `ocs.get(handle)`; `ssget` (no-arg) → `ocs.selection()`.
|
||||||
|
- [x] `command` sequences → `ocs.command("...")`.
|
||||||
|
- [x] `getvar`/`setvar` — confirmed no host system-variable surface exists;
|
||||||
|
documented as unsupported rather than guessed at.
|
||||||
|
- [x] Widened well past this original list via measured corpus frequency —
|
||||||
|
see that project's own README for the full table.
|
||||||
|
|
||||||
|
### 2.4 — Validation loop
|
||||||
|
|
||||||
|
- [ ] Run translated output through the Phase 1 plugin's interpreter against
|
||||||
|
the same corpus; every failure either fixes the mapping table or gets
|
||||||
|
added to the documented unsupported list. This is the actual acceptance
|
||||||
|
criterion for "done" — not 100% translation, but every gap being a known,
|
||||||
|
documented one.
|
||||||
|
|
||||||
|
### 2.5 — Packaging
|
||||||
|
|
||||||
|
- [x] Ship as a standalone CLI (`ocs-lisp2py file.lsp > file.py`) — needs
|
||||||
|
nothing from the OCS runtime, useful even to someone not running OCS yet.
|
||||||
|
- [ ] Optionally surface as an "Import AutoLISP Macro…" button in the Phase 1
|
||||||
|
plugin's ribbon, calling the same conversion logic in-process.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 3 — polish (not yet scoped in detail)
|
||||||
|
|
||||||
|
- [ ] Decide the open question from Phase 1.4: dockable console REPL vs.
|
||||||
|
run-only. Depends on what `HostApi` can support without a version bump.
|
||||||
|
- [ ] Versioning story for the `ocs` module surface as it grows: same strict
|
||||||
|
`ApiVersion` gate as `ocs_plugin_api`, or a looser contract since scripts
|
||||||
|
aren't compiled artifacts and can tolerate softer compatibility breaks?
|
||||||
|
- [ ] Whether scripts should ever be able to register permanent ribbon tools
|
||||||
|
(leaning: no — keep that exclusive to compiled plugins, per
|
||||||
|
OpenCADStudio's `plugin-architecture.md`'s "one package, one entry
|
||||||
|
point" goal).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Reference
|
||||||
|
|
||||||
|
| Piece | Location |
|
||||||
|
|-------|----------|
|
||||||
|
| Existing plugin architecture (non-goal note) | OpenCADStudio's `docs/plugin-architecture.md` |
|
||||||
|
| Plugin host API this plugin wraps | OpenCADStudio's `crates/ocs_plugin_api` (`HostApi` trait) |
|
||||||
|
| Plugin scaffold this was started from | OpenCADStudio's `docs/plugin-template/` |
|
||||||
|
| Existing automation/headless surface | OpenCADStudio's `src/app/control/transport.rs` |
|
||||||
|
| RustPython | https://github.com/RustPython/RustPython |
|
||||||
|
| AutoLISP corpus — Lee Mac | https://lee-mac.com/ |
|
||||||
|
| AutoLISP corpus — Whole-Spec catalog (157 routines) | https://whole-spec.com/en/cad-tips/lisp-catalog/ |
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
//! Generates `OUT_DIR/entity_crud.rs` — the `dict_to_entity`/`entity_to_dict`
|
||||||
|
//! conversion functions `ocs_module.rs` `include!`s — from `entity_manifest.json`
|
||||||
|
//! plus the type registry `ocs_plugin_api` embeds at its own build time (see
|
||||||
|
//! `crates/ocs_plugin_api::get_embedded_type_registry_json`, always compiled,
|
||||||
|
//! not gated behind the `host` feature — see that crate's `src/lib.rs`). See
|
||||||
|
//! `build/generate.rs` for the actual codegen.
|
||||||
|
|
||||||
|
use std::env;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
include!("build/generate.rs");
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
println!("cargo:rerun-if-changed=entity_manifest.json");
|
||||||
|
println!("cargo:rerun-if-changed=build/generate.rs");
|
||||||
|
|
||||||
|
let registry_json = ocs_plugin_api::get_embedded_type_registry_json();
|
||||||
|
let registry: TypeRegistry = serde_json::from_str(registry_json)
|
||||||
|
.expect("ocs_plugin_api's embedded type registry should be valid JSON");
|
||||||
|
|
||||||
|
let manifest = Manifest::load(include_str!("entity_manifest.json"));
|
||||||
|
|
||||||
|
let generated = generate_entity_crud(&manifest, ®istry);
|
||||||
|
|
||||||
|
let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR set by cargo"));
|
||||||
|
std::fs::write(out_dir.join("entity_crud.rs"), generated)
|
||||||
|
.expect("failed to write generated entity_crud.rs");
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,54 @@
|
|||||||
|
//! Create one disposable DWG with a paper layout and rectangular viewport.
|
||||||
|
//! Usage: cargo run --example create_layout_fixture -- /absolute/output.dwg
|
||||||
|
|
||||||
|
use std::io::Write;
|
||||||
|
|
||||||
|
use ocs_plugin_api::host::acadrust::{
|
||||||
|
entities::{Line, Text, Viewport},
|
||||||
|
CadDocument, DwgWriter, EntityType, Vector3,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let output = std::env::args().nth(1).ok_or("expected output DWG path")?;
|
||||||
|
let output = std::path::PathBuf::from(output);
|
||||||
|
let twisted = std::env::args().nth(2).as_deref() == Some("--twisted");
|
||||||
|
if output.extension().is_none_or(|value| value != "dwg")
|
||||||
|
|| output.parent().is_none_or(|parent| !parent.is_dir())
|
||||||
|
{
|
||||||
|
return Err("output must be a .dwg in an existing directory".into());
|
||||||
|
}
|
||||||
|
let mut document = CadDocument::new();
|
||||||
|
document.add_layout("Sheet")?;
|
||||||
|
document.add_entity(EntityType::Line(Line::from_coords(
|
||||||
|
-50.0, 0.0, 0.0, 50.0, 0.0, 0.0,
|
||||||
|
)))?;
|
||||||
|
document.add_entity_to_layout(
|
||||||
|
EntityType::Text(Text::with_value(
|
||||||
|
"Sheet note",
|
||||||
|
Vector3::new(20.0, 20.0, 0.0),
|
||||||
|
)),
|
||||||
|
"Sheet",
|
||||||
|
)?;
|
||||||
|
let mut viewport = Viewport::new();
|
||||||
|
viewport.id = 2;
|
||||||
|
viewport.center = Vector3::new(100.0, 80.0, 0.0);
|
||||||
|
viewport.width = 100.0;
|
||||||
|
viewport.height = 50.0;
|
||||||
|
viewport.view_height = 100.0;
|
||||||
|
viewport.view_center = Vector3::new(10.0, 20.0, 0.0);
|
||||||
|
viewport.view_target = Vector3::ZERO;
|
||||||
|
if twisted {
|
||||||
|
viewport.twist_angle = std::f64::consts::FRAC_PI_2;
|
||||||
|
viewport.view_target = Vector3::new(5.0, 10.0, 0.0);
|
||||||
|
}
|
||||||
|
document.add_entity_to_layout(EntityType::Viewport(viewport), "Sheet")?;
|
||||||
|
|
||||||
|
let mut file = std::fs::OpenOptions::new()
|
||||||
|
.write(true)
|
||||||
|
.create_new(true)
|
||||||
|
.open(&output)?;
|
||||||
|
DwgWriter::write_to_writer(&mut file, &document)?;
|
||||||
|
file.flush()?;
|
||||||
|
println!("Created {}", output.display());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
# Example script for opencad-python's PY_RUN command.
|
||||||
|
#
|
||||||
|
# Historical experimental command-replay example. The portable default
|
||||||
|
# build omits ocs.command()/ocs.select(); nested replay may hang in OCS 2026.37.
|
||||||
|
#
|
||||||
|
# Draws two rectangles, a triangle, an arc, a pair of lines made parallel by
|
||||||
|
# a real PCONSTRAINT, a circle made tangent to a line by a real TCONSTRAINT,
|
||||||
|
# and a row of points added in one ocs.add_points() batch call, one of which
|
||||||
|
# gets an XDATA record written, read back, and removed. Every ocs.add_*/
|
||||||
|
# ocs.write_record call in one PY_RUN shares a script undo group. Command
|
||||||
|
# replay has separate host undo semantics.
|
||||||
|
#
|
||||||
|
# These ARE real, persistent constraint objects, not just geometrically
|
||||||
|
# correct-looking shapes: drag one of the two "parallel" lines afterward and
|
||||||
|
# the other follows to stay parallel, same for the tangent circle. Verified
|
||||||
|
# end-to-end (not just "it compiles"): after ocs.command("PCONSTRAINT") /
|
||||||
|
# ("TCONSTRAINT"), the geometry visibly changes and satisfies the
|
||||||
|
# relationship exactly (checked numerically — direction-vector cross
|
||||||
|
# product ~0 for parallel, center-to-line distance == radius for tangent).
|
||||||
|
#
|
||||||
|
# ocs.select(handles) + ocs.command(name) is what makes this possible:
|
||||||
|
# constraint commands read a prior *selection* (a "Select objects:"
|
||||||
|
# prompt), not picks fed as command-line tokens the way LINE's points are —
|
||||||
|
# select the entities first, then run the bare command name. See PLUGIN.md
|
||||||
|
# for the two host-side additions (HostApi::run_command / set_selection)
|
||||||
|
# this needed and exactly what they do and don't cover.
|
||||||
|
|
||||||
|
if not hasattr(ocs, "command") or not hasattr(ocs, "select"):
|
||||||
|
raise RuntimeError("This example requires experimental command replay host APIs")
|
||||||
|
|
||||||
|
def rectangle(x, y, w, h):
|
||||||
|
l1 = ocs.add_line(x, y, x + w, y)
|
||||||
|
l2 = ocs.add_line(x + w, y, x + w, y + h)
|
||||||
|
l3 = ocs.add_line(x + w, y + h, x, y + h)
|
||||||
|
l4 = ocs.add_line(x, y + h, x, y)
|
||||||
|
return [l1, l2, l3, l4]
|
||||||
|
|
||||||
|
# ── Two rectangles (not aligned to each other — see the note below) ───────
|
||||||
|
rectangle(0, 0, 20, 10)
|
||||||
|
rectangle(30, 2, 18, 9)
|
||||||
|
|
||||||
|
# ── A triangle (three lines closing a loop) ────────────────────────────────
|
||||||
|
ocs.add_line(60, 0, 75, 0)
|
||||||
|
ocs.add_line(75, 0, 67.5, 12)
|
||||||
|
ocs.add_line(67.5, 12, 60, 0)
|
||||||
|
|
||||||
|
# ── An arc, for variety ─────────────────────────────────────────────────────
|
||||||
|
ocs.add_arc(67.5, 20, 8, 0, 180)
|
||||||
|
|
||||||
|
# ── Two lines, deliberately NOT parallel — then made parallel by a real ───
|
||||||
|
# ── persistent PCONSTRAINT (not just recomputed coordinates).
|
||||||
|
line_a = ocs.add_line(0, 20, 20, 24)
|
||||||
|
line_b = ocs.add_line(0, 30, 20, 33)
|
||||||
|
ocs.select([line_a, line_b])
|
||||||
|
ocs.command("PCONSTRAINT")
|
||||||
|
|
||||||
|
# ── A line and a circle, deliberately NOT touching — then made tangent by ──
|
||||||
|
# ── a real persistent TCONSTRAINT.
|
||||||
|
tangent_line = ocs.add_line(0, 40, 20, 40)
|
||||||
|
tangent_circle = ocs.add_circle(10, 44, 3)
|
||||||
|
ocs.select([tangent_line, tangent_circle])
|
||||||
|
ocs.command("TCONSTRAINT")
|
||||||
|
|
||||||
|
# ── What's NOT in this script: aligning the two rectangles to each other ──
|
||||||
|
# ── (a real ALIGN, not just matching coordinates). Tried it separately:
|
||||||
|
# ── ocs.command("ALIGN <points...>") DOES apply the transform correctly,
|
||||||
|
# ── but ALIGN asks a trailing "Scale objects? [Yes/No]" question that
|
||||||
|
# ── ocs.command()'s point-feeding doesn't answer (it sends exactly one
|
||||||
|
# ── trailing Enter, and ALIGN needs two — one to skip the optional 3rd
|
||||||
|
# ── point pair, one for the scale question) — it leaves that prompt open
|
||||||
|
# ── instead of cleanly finishing. Left out of this script rather than
|
||||||
|
# ── shipping something that half-works; see PLUGIN.md for the detail.
|
||||||
|
|
||||||
|
# ── A batch of points, added in one HostApi::add_entities() call instead ──
|
||||||
|
# ── of one ocs.add_line-style call per point.
|
||||||
|
point_handles = ocs.add_points([[x, 50, 0] for x in range(0, 21, 2)])
|
||||||
|
|
||||||
|
# ── Tag one of those points with an XDATA record, read it back, then ───────
|
||||||
|
# ── remove it — round-tripping every supported value kind.
|
||||||
|
tagged = point_handles[0]
|
||||||
|
ocs.write_record(tagged, "OPENCAD_EXAMPLE", [
|
||||||
|
{"kind": "String", "value": "origin marker"},
|
||||||
|
{"kind": "Point3D", "value": [0.0, 50.0, 0.0]},
|
||||||
|
{"kind": "Integer32", "value": 1},
|
||||||
|
])
|
||||||
|
record = ocs.read_record(tagged, "OPENCAD_EXAMPLE")
|
||||||
|
assert record["app_name"] == "OPENCAD_EXAMPLE"
|
||||||
|
assert record["values"][0] == {"kind": "String", "value": "origin marker"}
|
||||||
|
ocs.remove_record(tagged, "OPENCAD_EXAMPLE")
|
||||||
|
assert ocs.read_record(tagged, "OPENCAD_EXAMPLE") is None
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
[plugin]
|
||||||
|
id = "opencad.python"
|
||||||
|
name = "Python Scripting"
|
||||||
|
version = "0.1.0"
|
||||||
|
description = "Embedded Python scripting (RustPython) for Open CAD Studio."
|
||||||
|
author = "Felix Riestra"
|
||||||
|
license = "GPL-3.0-only"
|
||||||
|
repository = "HakanSeven12/OpenCADStudio"
|
||||||
|
|
||||||
|
[opencad]
|
||||||
|
api_version = 7
|
||||||
|
# Both filled by release.yml at build time from the actual compiler and
|
||||||
|
# Cargo.lock's resolved acadrust source. Declare acadrust_source even though
|
||||||
|
# it's optional: the host's compatibility check only runs at all if this
|
||||||
|
# field is present, so an omitted field is silently treated as compatible
|
||||||
|
# rather than rejected (see OpenCADStudio's plugin-architecture.md,
|
||||||
|
# "Build-time ABI metadata").
|
||||||
|
rustc_version = "__RUSTC_VERSION__"
|
||||||
|
acadrust_source = "__ACADRUST_SOURCE__"
|
||||||
|
ribbon_order = 60
|
||||||
|
command_prefixes = ["PY_"]
|
||||||
|
xdata_apps = []
|
||||||
@@ -0,0 +1,327 @@
|
|||||||
|
// Hand-written Dimension model, `include!`d next to the generated CRUD code.
|
||||||
|
//
|
||||||
|
// `EntityType::Dimension` wraps a nine-variant enum, so the generator cannot
|
||||||
|
// map it. Python sees one flat dict: `subtype` (fixed at creation), the
|
||||||
|
// shared base fields, and the fields of that subtype only. Fields that belong
|
||||||
|
// to another subtype are rejected rather than ignored. `actual_measurement`
|
||||||
|
// and the base `definition_point` are host-derived, never scripted.
|
||||||
|
|
||||||
|
enum DimField<'a> {
|
||||||
|
V(&'a mut Vector3),
|
||||||
|
F(&'a mut f64),
|
||||||
|
B(&'a mut bool),
|
||||||
|
}
|
||||||
|
|
||||||
|
const DIM_SUBTYPES: &[&str] = &[
|
||||||
|
"Aligned", "Linear", "Radius", "Diameter", "Angular2Ln", "Angular3Pt", "Ordinate", "Arc",
|
||||||
|
"LargeRadial",
|
||||||
|
];
|
||||||
|
const DIM_BASE_KEYS: &[&str] = &[
|
||||||
|
"text", "style_name", "normal", "text_middle_point", "attachment_point", "text_rotation",
|
||||||
|
"horizontal_direction", "flip_arrow1", "flip_arrow2", "text_user_positioned",
|
||||||
|
];
|
||||||
|
const DIM_READ_ONLY_KEYS: &[&str] = &["subtype", "actual_measurement"];
|
||||||
|
|
||||||
|
fn dimension_subtype_name(dim: &acadrust::entities::Dimension) -> &'static str {
|
||||||
|
use acadrust::entities::Dimension as D;
|
||||||
|
match dim {
|
||||||
|
D::Aligned(_) => "Aligned",
|
||||||
|
D::Linear(_) => "Linear",
|
||||||
|
D::Radius(_) => "Radius",
|
||||||
|
D::Diameter(_) => "Diameter",
|
||||||
|
D::Angular2Ln(_) => "Angular2Ln",
|
||||||
|
D::Angular3Pt(_) => "Angular3Pt",
|
||||||
|
D::Ordinate(_) => "Ordinate",
|
||||||
|
D::Arc(_) => "Arc",
|
||||||
|
D::LargeRadial(_) => "LargeRadial",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Subtype-specific fields in stable order.
|
||||||
|
fn dimension_fields(dim: &mut acadrust::entities::Dimension) -> Vec<(&'static str, DimField<'_>)> {
|
||||||
|
use acadrust::entities::Dimension as D;
|
||||||
|
use DimField::{B, F, V};
|
||||||
|
match dim {
|
||||||
|
D::Aligned(d) => vec![
|
||||||
|
("definition_point", V(&mut d.definition_point)),
|
||||||
|
("first_point", V(&mut d.first_point)),
|
||||||
|
("second_point", V(&mut d.second_point)),
|
||||||
|
("ext_line_rotation", F(&mut d.ext_line_rotation)),
|
||||||
|
],
|
||||||
|
D::Linear(d) => vec![
|
||||||
|
("definition_point", V(&mut d.definition_point)),
|
||||||
|
("first_point", V(&mut d.first_point)),
|
||||||
|
("second_point", V(&mut d.second_point)),
|
||||||
|
("rotation", F(&mut d.rotation)),
|
||||||
|
("ext_line_rotation", F(&mut d.ext_line_rotation)),
|
||||||
|
],
|
||||||
|
D::Radius(d) => vec![
|
||||||
|
("definition_point", V(&mut d.definition_point)),
|
||||||
|
("angle_vertex", V(&mut d.angle_vertex)),
|
||||||
|
("leader_length", F(&mut d.leader_length)),
|
||||||
|
],
|
||||||
|
D::Diameter(d) => vec![
|
||||||
|
("definition_point", V(&mut d.definition_point)),
|
||||||
|
("angle_vertex", V(&mut d.angle_vertex)),
|
||||||
|
("leader_length", F(&mut d.leader_length)),
|
||||||
|
],
|
||||||
|
D::Angular2Ln(d) => vec![
|
||||||
|
("definition_point", V(&mut d.definition_point)),
|
||||||
|
("dimension_arc", V(&mut d.dimension_arc)),
|
||||||
|
("first_point", V(&mut d.first_point)),
|
||||||
|
("second_point", V(&mut d.second_point)),
|
||||||
|
("angle_vertex", V(&mut d.angle_vertex)),
|
||||||
|
],
|
||||||
|
D::Angular3Pt(d) => vec![
|
||||||
|
("definition_point", V(&mut d.definition_point)),
|
||||||
|
("first_point", V(&mut d.first_point)),
|
||||||
|
("second_point", V(&mut d.second_point)),
|
||||||
|
("angle_vertex", V(&mut d.angle_vertex)),
|
||||||
|
],
|
||||||
|
D::Ordinate(d) => vec![
|
||||||
|
("definition_point", V(&mut d.definition_point)),
|
||||||
|
("feature_location", V(&mut d.feature_location)),
|
||||||
|
("leader_endpoint", V(&mut d.leader_endpoint)),
|
||||||
|
("is_ordinate_type_x", B(&mut d.is_ordinate_type_x)),
|
||||||
|
],
|
||||||
|
D::Arc(d) => vec![
|
||||||
|
("definition_point", V(&mut d.definition_point)),
|
||||||
|
("first_extension_point", V(&mut d.first_extension_point)),
|
||||||
|
("second_extension_point", V(&mut d.second_extension_point)),
|
||||||
|
("center_point", V(&mut d.center_point)),
|
||||||
|
("is_partial", B(&mut d.is_partial)),
|
||||||
|
("arc_start_parameter", F(&mut d.arc_start_parameter)),
|
||||||
|
("arc_end_parameter", F(&mut d.arc_end_parameter)),
|
||||||
|
("has_leader", B(&mut d.has_leader)),
|
||||||
|
("first_leader_point", V(&mut d.first_leader_point)),
|
||||||
|
("second_leader_point", V(&mut d.second_leader_point)),
|
||||||
|
],
|
||||||
|
D::LargeRadial(d) => vec![
|
||||||
|
("definition_point", V(&mut d.definition_point)),
|
||||||
|
("chord_point", V(&mut d.chord_point)),
|
||||||
|
("jog_angle", F(&mut d.jog_angle)),
|
||||||
|
("override_center", V(&mut d.override_center)),
|
||||||
|
("jog_point", V(&mut d.jog_point)),
|
||||||
|
],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fields `ocs.add()` must receive (the geometry that defines the dimension).
|
||||||
|
fn dimension_required(subtype: &str) -> &'static [&'static str] {
|
||||||
|
match subtype {
|
||||||
|
"Aligned" | "Linear" => &["definition_point", "first_point", "second_point"],
|
||||||
|
"Radius" | "Diameter" => &["definition_point", "angle_vertex"],
|
||||||
|
"Angular2Ln" => &["definition_point", "dimension_arc", "first_point", "second_point", "angle_vertex"],
|
||||||
|
"Angular3Pt" => &["definition_point", "first_point", "second_point", "angle_vertex"],
|
||||||
|
"Ordinate" => &["feature_location", "leader_endpoint"],
|
||||||
|
"Arc" => &["definition_point", "first_extension_point", "second_extension_point", "center_point"],
|
||||||
|
"LargeRadial" => &["definition_point", "chord_point"],
|
||||||
|
_ => &[],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dimension_base_mut(dim: &mut acadrust::entities::Dimension) -> &mut acadrust::entities::DimensionBase {
|
||||||
|
dim.base_mut()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dim_attachment_point_name(value: acadrust::entities::AttachmentPointType) -> &'static str {
|
||||||
|
use acadrust::entities::AttachmentPointType as A;
|
||||||
|
match value {
|
||||||
|
A::TopLeft => "TopLeft",
|
||||||
|
A::TopCenter => "TopCenter",
|
||||||
|
A::TopRight => "TopRight",
|
||||||
|
A::MiddleLeft => "MiddleLeft",
|
||||||
|
A::MiddleCenter => "MiddleCenter",
|
||||||
|
A::MiddleRight => "MiddleRight",
|
||||||
|
A::BottomLeft => "BottomLeft",
|
||||||
|
A::BottomCenter => "BottomCenter",
|
||||||
|
A::BottomRight => "BottomRight",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_dim_attachment_point(
|
||||||
|
value: &str,
|
||||||
|
vm: &VirtualMachine,
|
||||||
|
) -> PyResult<acadrust::entities::AttachmentPointType> {
|
||||||
|
use acadrust::entities::AttachmentPointType as A;
|
||||||
|
Ok(match value {
|
||||||
|
"TopLeft" => A::TopLeft,
|
||||||
|
"TopCenter" => A::TopCenter,
|
||||||
|
"TopRight" => A::TopRight,
|
||||||
|
"MiddleLeft" => A::MiddleLeft,
|
||||||
|
"MiddleCenter" => A::MiddleCenter,
|
||||||
|
"MiddleRight" => A::MiddleRight,
|
||||||
|
"BottomLeft" => A::BottomLeft,
|
||||||
|
"BottomCenter" => A::BottomCenter,
|
||||||
|
"BottomRight" => A::BottomRight,
|
||||||
|
other => {
|
||||||
|
return Err(vm.new_value_error(format!("ocs: unsupported AttachmentPointType value: {other}")))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dimension_to_dict(
|
||||||
|
vm: &VirtualMachine,
|
||||||
|
dimension: &acadrust::entities::Dimension,
|
||||||
|
) -> PyResult<PyObjectRef> {
|
||||||
|
let mut dim = dimension.clone();
|
||||||
|
let dict = vm.ctx.new_dict();
|
||||||
|
let base = dimension.base();
|
||||||
|
dict.set_item("kind", vm.new_pyobj("Dimension"), vm)?;
|
||||||
|
dict.set_item("handle", vm.new_pyobj(base.common.handle.value()), vm)?;
|
||||||
|
dict.set_item("layer", vm.new_pyobj(base.common.layer.clone()), vm)?;
|
||||||
|
dict.set_item("owner_handle", vm.new_pyobj(base.common.owner_handle.value()), vm)?;
|
||||||
|
dict.set_item("subtype", vm.new_pyobj(dimension_subtype_name(dimension)), vm)?;
|
||||||
|
dict.set_item("actual_measurement", vm.new_pyobj(base.actual_measurement), vm)?;
|
||||||
|
dict.set_item("text", vm.new_pyobj(base.text.clone()), vm)?;
|
||||||
|
dict.set_item("style_name", vm.new_pyobj(base.style_name.clone()), vm)?;
|
||||||
|
dict.set_item("normal", vector3_to_py_dict(vm, &base.normal)?, vm)?;
|
||||||
|
dict.set_item("text_middle_point", vector3_to_py_dict(vm, &base.text_middle_point)?, vm)?;
|
||||||
|
dict.set_item("attachment_point", vm.new_pyobj(dim_attachment_point_name(base.attachment_point)), vm)?;
|
||||||
|
dict.set_item("text_rotation", vm.new_pyobj(base.text_rotation), vm)?;
|
||||||
|
dict.set_item("horizontal_direction", vm.new_pyobj(base.horizontal_direction), vm)?;
|
||||||
|
dict.set_item("flip_arrow1", vm.new_pyobj(base.flip_arrow1), vm)?;
|
||||||
|
dict.set_item("flip_arrow2", vm.new_pyobj(base.flip_arrow2), vm)?;
|
||||||
|
dict.set_item("text_user_positioned", vm.new_pyobj(base.text_user_positioned), vm)?;
|
||||||
|
for (name, field) in dimension_fields(&mut dim) {
|
||||||
|
let value: PyObjectRef = match field {
|
||||||
|
DimField::V(v) => vector3_to_py_dict(vm, v)?,
|
||||||
|
DimField::F(v) => vm.new_pyobj(*v),
|
||||||
|
DimField::B(v) => vm.new_pyobj(*v),
|
||||||
|
};
|
||||||
|
dict.set_item(name, value, vm)?;
|
||||||
|
}
|
||||||
|
Ok(dict.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Merge `dict` onto `dim`. With `creating`, geometry the subtype needs must
|
||||||
|
/// be present so a script cannot silently default a point to the origin.
|
||||||
|
fn dimension_merge(
|
||||||
|
dim: &mut acadrust::entities::Dimension,
|
||||||
|
dict: &rustpython_vm::builtins::PyDictRef,
|
||||||
|
creating: bool,
|
||||||
|
vm: &VirtualMachine,
|
||||||
|
) -> PyResult<()> {
|
||||||
|
let subtype = dimension_subtype_name(dim);
|
||||||
|
let applicable: Vec<&'static str> =
|
||||||
|
dimension_fields(&mut dim.clone()).into_iter().map(|(name, _)| name).collect();
|
||||||
|
for key in dict.keys_vec() {
|
||||||
|
let key = key.try_into_value::<String>(vm)?;
|
||||||
|
let key = key.as_str();
|
||||||
|
if matches!(key, "kind" | "handle" | "layer" | "owner_handle") || DIM_BASE_KEYS.contains(&key) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if key == "subtype" {
|
||||||
|
let value = dict.get_item("subtype", vm)?.try_into_value::<String>(vm)?;
|
||||||
|
if value != subtype {
|
||||||
|
return Err(vm.new_value_error("Dimension.subtype is read-only".to_owned()));
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if key == "actual_measurement" {
|
||||||
|
return Err(vm.new_value_error("Dimension.actual_measurement is read-only".to_owned()));
|
||||||
|
}
|
||||||
|
if !applicable.contains(&key) {
|
||||||
|
let known = [
|
||||||
|
"definition_point", "first_point", "second_point", "angle_vertex", "dimension_arc",
|
||||||
|
"feature_location", "leader_endpoint", "first_extension_point", "second_extension_point",
|
||||||
|
"center_point", "first_leader_point", "second_leader_point", "chord_point",
|
||||||
|
"override_center", "jog_point", "rotation", "ext_line_rotation", "leader_length",
|
||||||
|
"arc_start_parameter", "arc_end_parameter", "jog_angle", "is_ordinate_type_x",
|
||||||
|
"is_partial", "has_leader",
|
||||||
|
];
|
||||||
|
return Err(vm.new_value_error(if known.contains(&key) {
|
||||||
|
format!("Dimension.{key} does not apply to the {subtype} subtype")
|
||||||
|
} else {
|
||||||
|
format!("ocs: Dimension property {key:?} is outside the editable schema")
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if creating {
|
||||||
|
for name in dimension_required(subtype) {
|
||||||
|
if dict.get_item_opt(*name, vm)?.is_none() {
|
||||||
|
return Err(vm.new_value_error(format!("ocs.add: Dimension {subtype} requires {name}")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (name, field) in dimension_fields(dim) {
|
||||||
|
let Some(value) = dict.get_item_opt(name, vm)? else { continue };
|
||||||
|
match field {
|
||||||
|
DimField::V(target) => *target = py_to_vector3_dict(value, vm)?,
|
||||||
|
DimField::F(target) => *target = py_number_to_f64(value, vm)?,
|
||||||
|
DimField::B(target) => *target = value.try_into_value::<bool>(vm)?,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let base = dimension_base_mut(dim);
|
||||||
|
if let Some(v) = dict.get_item_opt("text", vm)? { base.text = v.try_into_value::<String>(vm)?; }
|
||||||
|
if let Some(v) = dict.get_item_opt("style_name", vm)? { base.style_name = v.try_into_value::<String>(vm)?; }
|
||||||
|
if let Some(v) = dict.get_item_opt("normal", vm)? { base.normal = py_to_vector3_dict(v, vm)?; }
|
||||||
|
if let Some(v) = dict.get_item_opt("text_middle_point", vm)? { base.text_middle_point = py_to_vector3_dict(v, vm)?; }
|
||||||
|
if let Some(v) = dict.get_item_opt("attachment_point", vm)? {
|
||||||
|
base.attachment_point = parse_dim_attachment_point(&v.try_into_value::<String>(vm)?, vm)?;
|
||||||
|
}
|
||||||
|
if let Some(v) = dict.get_item_opt("text_rotation", vm)? { base.text_rotation = py_number_to_f64(v, vm)?; }
|
||||||
|
if let Some(v) = dict.get_item_opt("horizontal_direction", vm)? { base.horizontal_direction = py_number_to_f64(v, vm)?; }
|
||||||
|
if let Some(v) = dict.get_item_opt("flip_arrow1", vm)? { base.flip_arrow1 = v.try_into_value::<bool>(vm)?; }
|
||||||
|
if let Some(v) = dict.get_item_opt("flip_arrow2", vm)? { base.flip_arrow2 = v.try_into_value::<bool>(vm)?; }
|
||||||
|
if let Some(v) = dict.get_item_opt("text_user_positioned", vm)? { base.text_user_positioned = v.try_into_value::<bool>(vm)?; }
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dimension_from_dict(
|
||||||
|
dict: &rustpython_vm::builtins::PyDictRef,
|
||||||
|
vm: &VirtualMachine,
|
||||||
|
) -> PyResult<acadrust::entities::Dimension> {
|
||||||
|
use acadrust::entities::*;
|
||||||
|
let subtype = match dict.get_item_opt("subtype", vm)? {
|
||||||
|
Some(v) => v.try_into_value::<String>(vm)?,
|
||||||
|
None => {
|
||||||
|
return Err(vm.new_value_error(format!(
|
||||||
|
"ocs.add: Dimension requires subtype, one of {DIM_SUBTYPES:?}"
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let mut dim = match subtype.as_str() {
|
||||||
|
"Aligned" => Dimension::Aligned(DimensionAligned::default()),
|
||||||
|
"Linear" => Dimension::Linear(DimensionLinear::default()),
|
||||||
|
"Radius" => Dimension::Radius(DimensionRadius::default()),
|
||||||
|
"Diameter" => Dimension::Diameter(DimensionDiameter::default()),
|
||||||
|
"Angular2Ln" => Dimension::Angular2Ln(DimensionAngular2Ln::default()),
|
||||||
|
"Angular3Pt" => Dimension::Angular3Pt(DimensionAngular3Pt::default()),
|
||||||
|
"Ordinate" => Dimension::Ordinate(DimensionOrdinate::default()),
|
||||||
|
"Arc" => Dimension::Arc(DimensionArc::default()),
|
||||||
|
"LargeRadial" => Dimension::LargeRadial(DimensionLargeRadial::default()),
|
||||||
|
other => {
|
||||||
|
return Err(vm.new_value_error(format!(
|
||||||
|
"ocs.add: unsupported Dimension subtype {other:?}, expected one of {DIM_SUBTYPES:?}"
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
dimension_merge(&mut dim, dict, true, vm)?;
|
||||||
|
let base = dimension_base_mut(&mut dim);
|
||||||
|
base.common.handle = acadrust::Handle::new(get_opt_u64(dict, "handle", vm)?);
|
||||||
|
base.common.layer = get_opt_string(dict, "layer", "0", vm)?;
|
||||||
|
base.common.owner_handle = acadrust::Handle::new(get_opt_u64(dict, "owner_handle", vm)?);
|
||||||
|
Ok(dim)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dimension_apply(
|
||||||
|
existing: &acadrust::entities::Dimension,
|
||||||
|
dict: &rustpython_vm::builtins::PyDictRef,
|
||||||
|
vm: &VirtualMachine,
|
||||||
|
) -> PyResult<acadrust::entities::Dimension> {
|
||||||
|
let mut dim = existing.clone();
|
||||||
|
dimension_merge(&mut dim, dict, false, vm)?;
|
||||||
|
let base = dimension_base_mut(&mut dim);
|
||||||
|
if let Some(v) = dict.get_item_opt("layer", vm)? {
|
||||||
|
if !vm.is_none(&v) {
|
||||||
|
base.common.layer = v.try_into_value::<String>(vm)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(owner) = dict.get_item_opt("owner_handle", vm)? {
|
||||||
|
if owner.try_into_value::<u64>(vm)? != base.common.owner_handle.value() {
|
||||||
|
return Err(vm.new_value_error("owner_handle is read-only after creation".to_owned()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(dim)
|
||||||
|
}
|
||||||
@@ -0,0 +1,993 @@
|
|||||||
|
"""Thin Python view over OCS host API v7 entity transactions and coverage."""
|
||||||
|
|
||||||
|
def _coordinates(value, width):
|
||||||
|
return dict(zip("xyz"[:width], (float(axis) for axis in value)))
|
||||||
|
|
||||||
|
|
||||||
|
def _coerce_points(kind, properties):
|
||||||
|
"""Let create_entity take (x, y, z) tuples for point properties, as
|
||||||
|
transaction edits already do, by using the property types in the schema."""
|
||||||
|
schema = ocs.entity_coverage(kind)
|
||||||
|
types = {row["name"]: row for row in schema.get("properties", [])} if schema else {}
|
||||||
|
result = {}
|
||||||
|
for name, value in properties.items():
|
||||||
|
row = types.get(name)
|
||||||
|
if row is not None and row["type"] in ("Vector2", "Vector3"):
|
||||||
|
width = 2 if row["type"] == "Vector2" else 3
|
||||||
|
if row["sequence"]:
|
||||||
|
value = [_coordinates(item, width) if isinstance(item, (tuple, list)) else item for item in value]
|
||||||
|
elif isinstance(value, (tuple, list)):
|
||||||
|
value = _coordinates(value, width)
|
||||||
|
result[name] = value
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
class _Entity:
|
||||||
|
def __init__(self, document, handle):
|
||||||
|
object.__setattr__(self, "_document", document)
|
||||||
|
object.__setattr__(self, "handle", handle)
|
||||||
|
|
||||||
|
def _data(self):
|
||||||
|
data = ocs.entity_descriptor(self.handle)
|
||||||
|
if data is None:
|
||||||
|
raise KeyError("entity %s is absent or outside the Python schema" % self.handle)
|
||||||
|
return data
|
||||||
|
|
||||||
|
def __getattr__(self, name):
|
||||||
|
data = self._data()
|
||||||
|
if name not in data:
|
||||||
|
raise AttributeError("property %s is not in the Python entity schema" % name)
|
||||||
|
pending = self._document._pending or {}
|
||||||
|
value = pending.get(self.handle, {}).get(name, data[name])
|
||||||
|
if isinstance(value, dict) and all(axis in value for axis in ("x", "y")):
|
||||||
|
return tuple(value[axis] for axis in ("x", "y", "z") if axis in value)
|
||||||
|
return value
|
||||||
|
|
||||||
|
@property
|
||||||
|
def coverage(self):
|
||||||
|
return ocs.entity_coverage(self._data()["kind"])
|
||||||
|
|
||||||
|
@property
|
||||||
|
def snapshot(self):
|
||||||
|
"""Detached copy of all serialized CAD fields for this entity."""
|
||||||
|
data = ocs.entity_snapshot(self.handle)
|
||||||
|
if data is None:
|
||||||
|
raise KeyError("entity %s is absent" % self.handle)
|
||||||
|
return data[self._data()["kind"]]
|
||||||
|
|
||||||
|
def __setattr__(self, name, value):
|
||||||
|
if self._document._pending is None:
|
||||||
|
raise RuntimeError("entity writes require doc.transaction(...)")
|
||||||
|
data = self._data()
|
||||||
|
can_edit = name in self.coverage["editable"]
|
||||||
|
if not can_edit or name not in data or name in ("kind", "handle", "_editable"):
|
||||||
|
raise AttributeError("property %s is not editable through this schema" % name)
|
||||||
|
old = data[name]
|
||||||
|
if isinstance(old, dict) and all(axis in old for axis in ("x", "y")):
|
||||||
|
axes = tuple(axis for axis in ("x", "y", "z") if axis in old)
|
||||||
|
if not isinstance(value, (tuple, list)) or len(value) != len(axes):
|
||||||
|
raise ValueError("%s expects %s coordinates" % (name, len(axes)))
|
||||||
|
value = dict(zip(axes, value))
|
||||||
|
self._document._pending.setdefault(self.handle, {})[name] = value
|
||||||
|
|
||||||
|
|
||||||
|
class _Entities:
|
||||||
|
def __init__(self, document):
|
||||||
|
self._document = document
|
||||||
|
|
||||||
|
def __getitem__(self, handle):
|
||||||
|
entity = _Entity(self._document, int(handle))
|
||||||
|
entity._data()
|
||||||
|
return entity
|
||||||
|
|
||||||
|
def __iter__(self):
|
||||||
|
for handle in ocs.entity_handles():
|
||||||
|
yield self[handle]
|
||||||
|
|
||||||
|
def __len__(self):
|
||||||
|
return len(ocs.entity_handles())
|
||||||
|
|
||||||
|
|
||||||
|
class _Transaction:
|
||||||
|
def __init__(self, document, label):
|
||||||
|
self.document, self.label = document, label
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
if self.document._pending is not None:
|
||||||
|
raise RuntimeError("nested document transactions are unsupported")
|
||||||
|
self.document._pending = {}
|
||||||
|
return self.document
|
||||||
|
|
||||||
|
def __exit__(self, exc_type, exc, tb):
|
||||||
|
updates = self.document._pending
|
||||||
|
self.document._pending = None
|
||||||
|
if exc_type is None and updates:
|
||||||
|
ocs.update_many(self.label, [dict(handle=handle, **patch) for handle, patch in updates.items()])
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
class _Solids:
|
||||||
|
"""Kernel-backed solid creation and rigid moves.
|
||||||
|
|
||||||
|
The host builds and edits the geometry; a script never sees the ACIS
|
||||||
|
payload. Every call is its own operation in the script's undo group and
|
||||||
|
fails, leaving the drawing unchanged, when the kernel cannot do it.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, document):
|
||||||
|
self._document = document
|
||||||
|
|
||||||
|
def _create(self, primitive, values, layer):
|
||||||
|
handle = ocs.solid_create(primitive, [float(v) for v in values], layer)
|
||||||
|
return self._document.entities[handle]
|
||||||
|
|
||||||
|
def box(self, center=(0, 0, 0), size=(1, 1, 1), layer=None):
|
||||||
|
return self._create("box", tuple(center) + tuple(size), layer)
|
||||||
|
|
||||||
|
def wedge(self, origin=(0, 0, 0), size=(1, 1, 1), layer=None):
|
||||||
|
return self._create("wedge", tuple(origin) + tuple(size), layer)
|
||||||
|
|
||||||
|
def cylinder(self, center=(0, 0, 0), radius=1, height=1, layer=None):
|
||||||
|
return self._create("cylinder", tuple(center) + (radius, height), layer)
|
||||||
|
|
||||||
|
def sphere(self, center=(0, 0, 0), radius=1, layer=None):
|
||||||
|
return self._create("sphere", tuple(center) + (radius,), layer)
|
||||||
|
|
||||||
|
def torus(self, center=(0, 0, 0), major=2, minor=0.5, layer=None):
|
||||||
|
return self._create("torus", tuple(center) + (major, minor), layer)
|
||||||
|
|
||||||
|
def pyramid(self, center=(0, 0, 0), radius=1, height=1, sides=4, layer=None):
|
||||||
|
return self._create("pyramid", tuple(center) + (radius, height, sides), layer)
|
||||||
|
|
||||||
|
def region(self, profile, layer=None, delete_source=False):
|
||||||
|
"""Make a planar region from one closed planar profile (a circle,
|
||||||
|
ellipse, closed polyline or spline). Keeps the profile unless
|
||||||
|
`delete_source` is true, and uses the profile's layer by default."""
|
||||||
|
handle = profile.handle if isinstance(profile, _Entity) else int(profile)
|
||||||
|
return self._document.entities[ocs.solid_region(handle, layer, bool(delete_source))]
|
||||||
|
|
||||||
|
def _boolean(self, operation, first, second, layer, keep_operands):
|
||||||
|
a = first.handle if isinstance(first, _Entity) else int(first)
|
||||||
|
b = second.handle if isinstance(second, _Entity) else int(second)
|
||||||
|
return self._document.entities[ocs.solid_boolean(a, b, operation, layer, bool(keep_operands))]
|
||||||
|
|
||||||
|
def union(self, first, second, layer=None, keep_operands=False):
|
||||||
|
"""Join two solids into a new one. The operands are consumed unless
|
||||||
|
`keep_operands`. The kernel may refuse (the error says why) and a
|
||||||
|
refusal changes nothing. Curved operands can take a second or two,
|
||||||
|
and a whole script has a 30 second budget."""
|
||||||
|
return self._boolean("union", first, second, layer, keep_operands)
|
||||||
|
|
||||||
|
def subtract(self, first, second, layer=None, keep_operands=False):
|
||||||
|
"""Remove `second` from `first`, giving a new solid."""
|
||||||
|
return self._boolean("subtract", first, second, layer, keep_operands)
|
||||||
|
|
||||||
|
def intersect(self, first, second, layer=None, keep_operands=False):
|
||||||
|
"""Keep only the volume both solids share, as a new solid."""
|
||||||
|
return self._boolean("intersect", first, second, layer, keep_operands)
|
||||||
|
|
||||||
|
def surface(self, profile, layer=None, delete_source=False):
|
||||||
|
"""Make a plane surface from one closed planar profile."""
|
||||||
|
handle = profile.handle if isinstance(profile, _Entity) else int(profile)
|
||||||
|
return self._document.entities[ocs.solid_surface(handle, layer, bool(delete_source))]
|
||||||
|
|
||||||
|
def extrude(self, profile, direction, layer=None, delete_source=False):
|
||||||
|
"""Extrude a planar profile along `direction`: a Solid3D when the
|
||||||
|
profile is closed, a Surface when it is open."""
|
||||||
|
handle = profile.handle if isinstance(profile, _Entity) else int(profile)
|
||||||
|
vector = [float(v) for v in direction]
|
||||||
|
return self._document.entities[ocs.solid_extrude(handle, vector, layer, bool(delete_source))]
|
||||||
|
|
||||||
|
def transform(self, entity, matrix):
|
||||||
|
"""Apply a column-major 4x4 rigid transform (16 numbers) in place."""
|
||||||
|
handle = entity.handle if isinstance(entity, _Entity) else int(entity)
|
||||||
|
ocs.solid_transform(handle, [float(v) for v in matrix])
|
||||||
|
return self._document.entities[handle]
|
||||||
|
|
||||||
|
def translate(self, entity, offset):
|
||||||
|
dx, dy, dz = (float(v) for v in offset)
|
||||||
|
return self.transform(entity, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, dx, dy, dz, 1])
|
||||||
|
|
||||||
|
def rotate(self, entity, axis, angle, about=(0, 0, 0)):
|
||||||
|
"""Turn about the world axis 'x', 'y' or 'z' through `about`."""
|
||||||
|
index = {"x": 0, "y": 1, "z": 2}[axis]
|
||||||
|
return self.transform(entity, ocs.rotation_matrix(index, float(angle), [float(v) for v in about]))
|
||||||
|
|
||||||
|
def mirror(self, entity, axis, about=(0, 0, 0)):
|
||||||
|
"""Reflect across the plane normal to the world axis through `about`."""
|
||||||
|
index = {"x": 0, "y": 1, "z": 2}[axis]
|
||||||
|
return self.transform(entity, ocs.mirror_matrix(index, [float(v) for v in about]))
|
||||||
|
|
||||||
|
|
||||||
|
class _Layers:
|
||||||
|
"""The drawing's layer table. Every change goes through the host: it is
|
||||||
|
validated, becomes one undo step, and a refusal raises `RuntimeError`
|
||||||
|
without changing the drawing."""
|
||||||
|
|
||||||
|
_KEYS = ("color", "linetype", "lineweight", "off", "frozen", "locked",
|
||||||
|
"plottable", "transparency", "description")
|
||||||
|
|
||||||
|
def _records(self):
|
||||||
|
return ocs.layer_records()
|
||||||
|
|
||||||
|
def __iter__(self):
|
||||||
|
return iter(self._records())
|
||||||
|
|
||||||
|
def __len__(self):
|
||||||
|
return len(self._records())
|
||||||
|
|
||||||
|
def __contains__(self, name):
|
||||||
|
wanted = str(name).strip().upper()
|
||||||
|
return any(r["name"].upper() == wanted for r in self._records())
|
||||||
|
|
||||||
|
def __getitem__(self, name):
|
||||||
|
wanted = str(name).strip().upper()
|
||||||
|
for record in self._records():
|
||||||
|
if record["name"].upper() == wanted:
|
||||||
|
return record
|
||||||
|
raise KeyError(name)
|
||||||
|
|
||||||
|
def get(self, name, default=None):
|
||||||
|
try:
|
||||||
|
return self[name]
|
||||||
|
except KeyError:
|
||||||
|
return default
|
||||||
|
|
||||||
|
def names(self):
|
||||||
|
return [r["name"] for r in self._records()]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def current(self):
|
||||||
|
for record in self._records():
|
||||||
|
if record["current"]:
|
||||||
|
return record
|
||||||
|
return None
|
||||||
|
|
||||||
|
@current.setter
|
||||||
|
def current(self, name):
|
||||||
|
self.set_current(name)
|
||||||
|
|
||||||
|
def _options(self, properties):
|
||||||
|
unknown = [k for k in properties if k not in self._KEYS]
|
||||||
|
if unknown:
|
||||||
|
raise TypeError("unknown layer propert%s: %s" % ("y" if len(unknown) == 1 else "ies", ", ".join(sorted(unknown))))
|
||||||
|
return {k: v for k, v in properties.items() if v is not None}
|
||||||
|
|
||||||
|
def create(self, name, **properties):
|
||||||
|
"""Create a layer and return its record. `color` is an ACI index
|
||||||
|
(1-255), an (r, g, b) tuple or a Color dict; `lineweight` is in
|
||||||
|
1/100 mm (-1 ByLayer, -2 ByBlock, -3 Default); `transparency` is a
|
||||||
|
percentage 0-90."""
|
||||||
|
ocs.layer_operation("create", str(name), self._options(properties))
|
||||||
|
return self[name]
|
||||||
|
|
||||||
|
def modify(self, name, **properties):
|
||||||
|
"""Change only the properties given and return the updated record."""
|
||||||
|
ocs.layer_operation("modify", str(name), self._options(properties))
|
||||||
|
return self[name]
|
||||||
|
|
||||||
|
def rename(self, name, new_name):
|
||||||
|
ocs.layer_operation("rename", str(name), {"to": str(new_name)})
|
||||||
|
return self[new_name]
|
||||||
|
|
||||||
|
def delete(self, name, erase_objects=False):
|
||||||
|
"""Delete a layer. A layer that still holds objects is refused unless
|
||||||
|
`erase_objects=True`. Layer 0, Defpoints and the current layer stay."""
|
||||||
|
ocs.layer_operation("delete", str(name), {"erase_objects": bool(erase_objects)})
|
||||||
|
|
||||||
|
def set_current(self, name):
|
||||||
|
ocs.layer_operation("set_current", str(name), None)
|
||||||
|
return self[name]
|
||||||
|
|
||||||
|
|
||||||
|
class _Styles:
|
||||||
|
"""Common lookup, rename, delete and current-style handling for the text
|
||||||
|
and dimension style tables. Every change is validated by the host, is one
|
||||||
|
undo step (making a style current is a setting), and a refusal raises
|
||||||
|
`RuntimeError` without changing the drawing. `Standard` is never renamed
|
||||||
|
or deleted, and a style that is current or in use is never deleted."""
|
||||||
|
|
||||||
|
_KIND = None
|
||||||
|
_RECORDS = None
|
||||||
|
|
||||||
|
def _records(self):
|
||||||
|
return getattr(ocs, self._RECORDS)()
|
||||||
|
|
||||||
|
def __iter__(self):
|
||||||
|
return iter(self._records())
|
||||||
|
|
||||||
|
def __len__(self):
|
||||||
|
return len(self._records())
|
||||||
|
|
||||||
|
def __contains__(self, name):
|
||||||
|
wanted = str(name).strip().upper()
|
||||||
|
return any(r["name"].upper() == wanted for r in self._records())
|
||||||
|
|
||||||
|
def __getitem__(self, name):
|
||||||
|
wanted = str(name).strip().upper()
|
||||||
|
for record in self._records():
|
||||||
|
if record["name"].upper() == wanted:
|
||||||
|
return record
|
||||||
|
raise KeyError(name)
|
||||||
|
|
||||||
|
def get(self, name, default=None):
|
||||||
|
try:
|
||||||
|
return self[name]
|
||||||
|
except KeyError:
|
||||||
|
return default
|
||||||
|
|
||||||
|
def names(self):
|
||||||
|
return [r["name"] for r in self._records()]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def current(self):
|
||||||
|
for record in self._records():
|
||||||
|
if record["current"]:
|
||||||
|
return record
|
||||||
|
return None
|
||||||
|
|
||||||
|
@current.setter
|
||||||
|
def current(self, name):
|
||||||
|
self.set_current(name)
|
||||||
|
|
||||||
|
def _run(self, op, name, options=None):
|
||||||
|
ocs.style_operation(self._KIND, op, str(name), options)
|
||||||
|
|
||||||
|
def rename(self, name, new_name):
|
||||||
|
self._run("rename", name, {"to": str(new_name)})
|
||||||
|
return self[new_name]
|
||||||
|
|
||||||
|
def delete(self, name):
|
||||||
|
self._run("delete", name)
|
||||||
|
|
||||||
|
def set_current(self, name):
|
||||||
|
self._run("set_current", name)
|
||||||
|
return self[name]
|
||||||
|
|
||||||
|
|
||||||
|
class _TextStyles(_Styles):
|
||||||
|
"""`ocs.active_document.text_styles`. Properties: `height` (0 = each text
|
||||||
|
chooses), `width_factor`, `oblique` (degrees, within 85), `font` (SHX file),
|
||||||
|
`big_font`, `backward`, `upside_down`, `vertical`, `annotative`. Give a
|
||||||
|
TrueType face as a font file name such as `font="arial.ttf"`: the codec does
|
||||||
|
not persist a separate TrueType family name, so it is not exposed."""
|
||||||
|
|
||||||
|
_KIND = "text"
|
||||||
|
_RECORDS = "text_style_records"
|
||||||
|
_KEYS = ("height", "width_factor", "oblique", "font", "big_font",
|
||||||
|
"backward", "upside_down", "vertical", "annotative")
|
||||||
|
|
||||||
|
def _options(self, properties):
|
||||||
|
unknown = [k for k in properties if k not in self._KEYS]
|
||||||
|
if unknown:
|
||||||
|
raise TypeError("unknown text style propert%s: %s" % ("y" if len(unknown) == 1 else "ies", ", ".join(sorted(unknown))))
|
||||||
|
return {k: v for k, v in properties.items() if v is not None}
|
||||||
|
|
||||||
|
def create(self, name, **properties):
|
||||||
|
self._run("create", name, self._options(properties))
|
||||||
|
return self[name]
|
||||||
|
|
||||||
|
def modify(self, name, **properties):
|
||||||
|
self._run("modify", name, self._options(properties))
|
||||||
|
return self[name]
|
||||||
|
|
||||||
|
|
||||||
|
class _DimStyles(_Styles):
|
||||||
|
"""`ocs.active_document.dim_styles`. Records and properties use the DimStyle
|
||||||
|
field names (`dimscale`, `dimtxt`, `dimasz`, `dimtxsty` ...); handles and
|
||||||
|
xref fields are host-managed and refused. `create(..., copy_from="Other")`
|
||||||
|
starts from an existing style."""
|
||||||
|
|
||||||
|
_KIND = "dim"
|
||||||
|
_RECORDS = "dim_style_records"
|
||||||
|
|
||||||
|
def _options(self, properties):
|
||||||
|
return {k: v for k, v in properties.items() if v is not None or k == "dimclrd_true_color"}
|
||||||
|
|
||||||
|
def create(self, name, copy_from=None, **properties):
|
||||||
|
options = self._options(properties)
|
||||||
|
if copy_from is not None:
|
||||||
|
options["copy_from"] = str(copy_from)
|
||||||
|
self._run("create", name, options)
|
||||||
|
return self[name]
|
||||||
|
|
||||||
|
def modify(self, name, **properties):
|
||||||
|
self._run("modify", name, self._options(properties))
|
||||||
|
return self[name]
|
||||||
|
|
||||||
|
|
||||||
|
class _Blocks:
|
||||||
|
"""`ocs.active_document.blocks`: user block definitions (layout and
|
||||||
|
anonymous blocks are not listed). Every change is validated by the host, is
|
||||||
|
one undo step, and a refusal raises `RuntimeError` without changing the
|
||||||
|
drawing. Place a block with `create_entity("Insert", block_name=...)`."""
|
||||||
|
|
||||||
|
def _records(self):
|
||||||
|
return ocs.block_records()
|
||||||
|
|
||||||
|
def __iter__(self):
|
||||||
|
return iter(self._records())
|
||||||
|
|
||||||
|
def __len__(self):
|
||||||
|
return len(self._records())
|
||||||
|
|
||||||
|
def __contains__(self, name):
|
||||||
|
wanted = str(name).strip().upper()
|
||||||
|
return any(r["name"].upper() == wanted for r in self._records())
|
||||||
|
|
||||||
|
def __getitem__(self, name):
|
||||||
|
wanted = str(name).strip().upper()
|
||||||
|
for record in self._records():
|
||||||
|
if record["name"].upper() == wanted:
|
||||||
|
return record
|
||||||
|
raise KeyError(name)
|
||||||
|
|
||||||
|
def get(self, name, default=None):
|
||||||
|
try:
|
||||||
|
return self[name]
|
||||||
|
except KeyError:
|
||||||
|
return default
|
||||||
|
|
||||||
|
def names(self):
|
||||||
|
return [r["name"] for r in self._records()]
|
||||||
|
|
||||||
|
def create(self, name, entities, base_point=(0, 0, 0), erase_originals=False, description=None):
|
||||||
|
"""Define a block from existing model/paper-space entities (descriptors
|
||||||
|
or handles). They are copied into the definition shifted by
|
||||||
|
`-base_point`; `erase_originals=True` removes them from the drawing, as
|
||||||
|
the BLOCK command does. No insert is placed."""
|
||||||
|
handles = [e.handle if isinstance(e, _Entity) else int(e) for e in entities]
|
||||||
|
options = {"entities": handles, "base_point": [float(v) for v in base_point],
|
||||||
|
"erase_originals": bool(erase_originals)}
|
||||||
|
if description is not None:
|
||||||
|
options["description"] = str(description)
|
||||||
|
ocs.block_operation("create", str(name), options)
|
||||||
|
return self[name]
|
||||||
|
|
||||||
|
def modify(self, name, description=None, explodable=None, scale_uniformly=None):
|
||||||
|
options = {k: v for k, v in (("description", description), ("explodable", explodable),
|
||||||
|
("scale_uniformly", scale_uniformly)) if v is not None}
|
||||||
|
ocs.block_operation("modify", str(name), options)
|
||||||
|
return self[name]
|
||||||
|
|
||||||
|
def rename(self, name, new_name):
|
||||||
|
"""Rename a block; every insert of it follows."""
|
||||||
|
ocs.block_operation("rename", str(name), {"to": str(new_name)})
|
||||||
|
return self[new_name]
|
||||||
|
|
||||||
|
def delete(self, name):
|
||||||
|
"""Delete a block that no insert, style or leader still uses."""
|
||||||
|
ocs.block_operation("delete", str(name), None)
|
||||||
|
|
||||||
|
|
||||||
|
class _Named:
|
||||||
|
"""Shared lookup for the linetype and layout collections."""
|
||||||
|
|
||||||
|
_RECORDS = None
|
||||||
|
|
||||||
|
def _records(self):
|
||||||
|
return getattr(ocs, self._RECORDS)()
|
||||||
|
|
||||||
|
def __iter__(self):
|
||||||
|
return iter(self._records())
|
||||||
|
|
||||||
|
def __len__(self):
|
||||||
|
return len(self._records())
|
||||||
|
|
||||||
|
def __contains__(self, name):
|
||||||
|
wanted = str(name).strip().upper()
|
||||||
|
return any(r["name"].upper() == wanted for r in self._records())
|
||||||
|
|
||||||
|
def __getitem__(self, name):
|
||||||
|
wanted = str(name).strip().upper()
|
||||||
|
for record in self._records():
|
||||||
|
if record["name"].upper() == wanted:
|
||||||
|
return record
|
||||||
|
raise KeyError(name)
|
||||||
|
|
||||||
|
def get(self, name, default=None):
|
||||||
|
try:
|
||||||
|
return self[name]
|
||||||
|
except KeyError:
|
||||||
|
return default
|
||||||
|
|
||||||
|
def names(self):
|
||||||
|
return [r["name"] for r in self._records()]
|
||||||
|
|
||||||
|
|
||||||
|
class _Linetypes(_Named):
|
||||||
|
"""`ocs.active_document.linetypes`. A pattern is signed lengths in drawing
|
||||||
|
units: positive is a dash, negative a gap, zero a dot (2-12 elements with at
|
||||||
|
least one gap and one dash or dot). Text and shape linetypes can be read
|
||||||
|
but not created or edited. Every change is validated by the host, is one
|
||||||
|
undo step, and a refusal raises `RuntimeError` without changing anything.
|
||||||
|
`Continuous`, `ByLayer` and `ByBlock` are never changed; a linetype used by
|
||||||
|
a layer, an entity, a dimension style or the current setting is never
|
||||||
|
deleted."""
|
||||||
|
|
||||||
|
_RECORDS = "linetype_records"
|
||||||
|
|
||||||
|
def create(self, name, pattern, description=""):
|
||||||
|
ocs.linetype_operation("create", str(name), {"pattern": [float(v) for v in pattern],
|
||||||
|
"description": str(description)})
|
||||||
|
return self[name]
|
||||||
|
|
||||||
|
def modify(self, name, pattern=None, description=None):
|
||||||
|
options = {}
|
||||||
|
if pattern is not None:
|
||||||
|
options["pattern"] = [float(v) for v in pattern]
|
||||||
|
if description is not None:
|
||||||
|
options["description"] = str(description)
|
||||||
|
ocs.linetype_operation("modify", str(name), options)
|
||||||
|
return self[name]
|
||||||
|
|
||||||
|
def rename(self, name, new_name):
|
||||||
|
ocs.linetype_operation("rename", str(name), {"to": str(new_name)})
|
||||||
|
return self[new_name]
|
||||||
|
|
||||||
|
def delete(self, name):
|
||||||
|
ocs.linetype_operation("delete", str(name), None)
|
||||||
|
|
||||||
|
|
||||||
|
class _Layouts(_Named):
|
||||||
|
"""`ocs.active_document.layouts`: `Model` and the paper-space layouts in tab
|
||||||
|
order. Creation entities into a layout by making it current first
|
||||||
|
(`layouts.current = "Sheet1"`), then `create_entity(...)`. Every change is
|
||||||
|
validated by the host and is one undo step (switching layout is not); a
|
||||||
|
refusal raises `RuntimeError`. Layout operations act on the active
|
||||||
|
document."""
|
||||||
|
|
||||||
|
_RECORDS = "layout_records"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def current(self):
|
||||||
|
for record in self._records():
|
||||||
|
if record["current"]:
|
||||||
|
return record
|
||||||
|
return None
|
||||||
|
|
||||||
|
@current.setter
|
||||||
|
def current(self, name):
|
||||||
|
self.set_current(name)
|
||||||
|
|
||||||
|
def create(self, name):
|
||||||
|
ocs.layout_operation("create", str(name), None)
|
||||||
|
return self[name]
|
||||||
|
|
||||||
|
def rename(self, name, new_name):
|
||||||
|
ocs.layout_operation("rename", str(name), {"to": str(new_name)})
|
||||||
|
return self[new_name]
|
||||||
|
|
||||||
|
def delete(self, name):
|
||||||
|
"""Delete a paper-space layout and everything on it (never `Model`)."""
|
||||||
|
ocs.layout_operation("delete", str(name), None)
|
||||||
|
|
||||||
|
def set_current(self, name):
|
||||||
|
ocs.layout_operation("set_current", str(name), None)
|
||||||
|
return self[name]
|
||||||
|
|
||||||
|
def set_page(self, name, paper_size=None, rotation=None, scale=None):
|
||||||
|
"""`paper_size` is (width, height) in mm, `rotation` 0/90/180/270 degrees
|
||||||
|
and `scale` a custom plot scale (numerator, denominator)."""
|
||||||
|
options = {}
|
||||||
|
if paper_size is not None:
|
||||||
|
options["paper_size"] = [float(v) for v in paper_size]
|
||||||
|
if rotation is not None:
|
||||||
|
options["rotation"] = int(rotation)
|
||||||
|
if scale is not None:
|
||||||
|
options["scale"] = [float(v) for v in scale]
|
||||||
|
ocs.layout_operation("set_page", str(name), options)
|
||||||
|
return self[name]
|
||||||
|
|
||||||
|
|
||||||
|
def _pt(value):
|
||||||
|
"""A point as [x, y, z] from a tuple, list or {"x", "y", "z"} dict."""
|
||||||
|
if isinstance(value, dict):
|
||||||
|
return [float(value["x"]), float(value["y"]), float(value.get("z", 0.0))]
|
||||||
|
coords = [float(v) for v in value]
|
||||||
|
if len(coords) == 2:
|
||||||
|
coords.append(0.0)
|
||||||
|
if len(coords) != 3:
|
||||||
|
raise ValueError("a point needs 2 or 3 coordinates")
|
||||||
|
return coords
|
||||||
|
|
||||||
|
|
||||||
|
def _handle(value):
|
||||||
|
return value.handle if isinstance(value, _Entity) else int(value)
|
||||||
|
|
||||||
|
|
||||||
|
class _Command:
|
||||||
|
"""One running OCS command, driven a step at a time:
|
||||||
|
|
||||||
|
with doc.start_command("OFFSET") as c:
|
||||||
|
c.text(2); c.entity(line, at=(5, 0, 0)); c.point((5, 4, 0)); c.enter()
|
||||||
|
|
||||||
|
Each step returns the outcome dict (`status`, `prompt`, `accepts`,
|
||||||
|
`options`, `added`, `error`, ...) and raises `RuntimeError` when the command
|
||||||
|
reports an error. Leaving the `with` block cancels the command if it is still
|
||||||
|
waiting. The host runs the real command, refuses to start one while another
|
||||||
|
is active, and refuses commands that could end the session (QUIT, NEW, OPEN,
|
||||||
|
SAVE...) or re-enter Python (PY_*)."""
|
||||||
|
|
||||||
|
def __init__(self, name):
|
||||||
|
self.name = str(name)
|
||||||
|
self.outcome = None
|
||||||
|
self._send("start", name=self.name)
|
||||||
|
|
||||||
|
def _send(self, kind, **options):
|
||||||
|
outcome = ocs.command_step(kind, options)
|
||||||
|
self.outcome = outcome
|
||||||
|
if outcome["error"]:
|
||||||
|
raise RuntimeError("%s: %s" % (self.name, outcome["error"]))
|
||||||
|
return outcome
|
||||||
|
|
||||||
|
@property
|
||||||
|
def waiting(self):
|
||||||
|
return self.outcome is not None and self.outcome["status"] == "waiting_input"
|
||||||
|
|
||||||
|
def point(self, point):
|
||||||
|
return self._send("point", point=_pt(point))
|
||||||
|
|
||||||
|
def text(self, value):
|
||||||
|
return self._send("text", text=str(value))
|
||||||
|
|
||||||
|
def token(self, keyword):
|
||||||
|
return self._send("token", text=str(keyword))
|
||||||
|
|
||||||
|
def entity(self, entity, at):
|
||||||
|
return self._send("entity", handle=_handle(entity), point=_pt(at))
|
||||||
|
|
||||||
|
def selection(self):
|
||||||
|
"""Complete an object-selection prompt with the current selection."""
|
||||||
|
return self._send("selection")
|
||||||
|
|
||||||
|
def enter(self):
|
||||||
|
return self._send("enter")
|
||||||
|
|
||||||
|
def cancel(self):
|
||||||
|
return self._send("cancel")
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, *exc):
|
||||||
|
if self.waiting:
|
||||||
|
ocs.command_step("cancel", None)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _finished(command, what):
|
||||||
|
"""Require that `command` ended by itself; cancel and raise if it did not."""
|
||||||
|
if command.waiting:
|
||||||
|
prompt = command.outcome["prompt"]
|
||||||
|
command.cancel()
|
||||||
|
raise RuntimeError("%s did not finish: still asking %r" % (what, prompt))
|
||||||
|
|
||||||
|
|
||||||
|
class _Modify:
|
||||||
|
"""Modify tools as plain calls. Each drives the real OCS command, so it
|
||||||
|
behaves exactly as at the command line, and returns the entities it added.
|
||||||
|
A tool that needs a pick point takes `at=` (a point on or near the entity);
|
||||||
|
without it the middle of a line, arc or circle is used."""
|
||||||
|
|
||||||
|
def __init__(self, document):
|
||||||
|
self._document = document
|
||||||
|
|
||||||
|
def _at(self, entity, at):
|
||||||
|
if at is not None:
|
||||||
|
return _pt(at)
|
||||||
|
samples = ocs.curve_samples(_handle(entity), 4)
|
||||||
|
if samples is None:
|
||||||
|
# A polyline: its first vertex lies on it.
|
||||||
|
data = ocs.entity_descriptor(_handle(entity)) or {}
|
||||||
|
vertices = data.get("vertices")
|
||||||
|
if vertices:
|
||||||
|
first = vertices[0]
|
||||||
|
where = first.get("location") or first.get("position") if isinstance(first, dict) else None
|
||||||
|
if where:
|
||||||
|
return [float(where["x"]), float(where["y"]), float(where.get("z", 0.0))]
|
||||||
|
raise ValueError("pass at=(x, y, z): the middle of this kind of entity is not known")
|
||||||
|
middle = samples["vertices"][len(samples["vertices"]) // 2]
|
||||||
|
return [middle[0], middle[1], samples["elevation"]]
|
||||||
|
|
||||||
|
def _select(self, entities):
|
||||||
|
ocs.select([_handle(e) for e in entities])
|
||||||
|
|
||||||
|
def _added(self, before):
|
||||||
|
before = set(before)
|
||||||
|
return [self._document.entities[h] for h in ocs.entity_handles() if h not in before]
|
||||||
|
|
||||||
|
def _run(self, name, steps, entities=None):
|
||||||
|
before = list(ocs.entity_handles())
|
||||||
|
if entities is not None:
|
||||||
|
self._select(entities)
|
||||||
|
with _Command(name) as command:
|
||||||
|
for step in steps:
|
||||||
|
step(command)
|
||||||
|
_finished(command, name)
|
||||||
|
return self._added(before)
|
||||||
|
|
||||||
|
def offset(self, entity, distance, side, at=None):
|
||||||
|
"""Offset one entity by `distance` towards the point `side`; returns the new entity."""
|
||||||
|
result = self._run("OFFSET", [
|
||||||
|
lambda c: c.text(distance),
|
||||||
|
lambda c: c.entity(entity, self._at(entity, at)),
|
||||||
|
lambda c: c.point(side),
|
||||||
|
lambda c: c.enter(),
|
||||||
|
])
|
||||||
|
if not result:
|
||||||
|
raise RuntimeError("OFFSET produced nothing")
|
||||||
|
return result[0]
|
||||||
|
|
||||||
|
def trim(self, target, at):
|
||||||
|
"""Trim `target` at the crossing nearest the click point `at`, against every entity in the drawing."""
|
||||||
|
return self._run("TRIM", [lambda c: c.entity(target, at), lambda c: c.enter()])
|
||||||
|
|
||||||
|
def extend(self, target, at):
|
||||||
|
"""Extend `target` from the end nearest `at` to the next entity in its way."""
|
||||||
|
return self._run("EXTEND", [lambda c: c.entity(target, at), lambda c: c.enter()])
|
||||||
|
|
||||||
|
def fillet(self, first, second, radius=0, at1=None, at2=None):
|
||||||
|
"""Round (or, with radius 0, square) the corner between two entities."""
|
||||||
|
return self._run("FILLET", [
|
||||||
|
lambda c: c.token("R"),
|
||||||
|
lambda c: c.text(radius),
|
||||||
|
lambda c: c.entity(first, self._at(first, at1)),
|
||||||
|
lambda c: c.entity(second, self._at(second, at2)),
|
||||||
|
lambda c: c.enter(),
|
||||||
|
])
|
||||||
|
|
||||||
|
def move(self, entities, base, target):
|
||||||
|
self._run("MOVE", [lambda c: c.point(base), lambda c: c.point(target)], entities)
|
||||||
|
|
||||||
|
def copy(self, entities, base, target):
|
||||||
|
"""Copy the entities once from `base` to `target`; returns the copies."""
|
||||||
|
return self._run("COPY", [lambda c: c.point(base), lambda c: c.point(target), lambda c: c.enter()], entities)
|
||||||
|
|
||||||
|
def rotate(self, entities, base, angle):
|
||||||
|
"""Rotate about `base` by `angle` degrees."""
|
||||||
|
self._run("ROTATE", [lambda c: c.point(base), lambda c: c.text(angle)], entities)
|
||||||
|
|
||||||
|
def scale(self, entities, base, factor):
|
||||||
|
self._run("SCALE", [lambda c: c.point(base), lambda c: c.text(factor)], entities)
|
||||||
|
|
||||||
|
def mirror(self, entities, first, second, erase_source=False):
|
||||||
|
"""Mirror about the line through two points; returns the mirrored copies."""
|
||||||
|
return self._run("MIRROR", [
|
||||||
|
lambda c: c.point(first),
|
||||||
|
lambda c: c.point(second),
|
||||||
|
lambda c: c.token("Y" if erase_source else "N"),
|
||||||
|
], entities)
|
||||||
|
|
||||||
|
def chamfer(self, first, second, distance1, distance2=None, at1=None, at2=None):
|
||||||
|
"""Cut the corner between two lines; `distance1` is measured along `first`
|
||||||
|
and `distance2` (default the same) along `second`. Returns the new line."""
|
||||||
|
if distance2 is None:
|
||||||
|
distance2 = distance1
|
||||||
|
result = self._run("CHAMFER", [
|
||||||
|
lambda c: c.token("D"),
|
||||||
|
lambda c: c.text(distance1),
|
||||||
|
lambda c: c.text(distance2),
|
||||||
|
lambda c: c.entity(first, self._at(first, at1)),
|
||||||
|
lambda c: c.entity(second, self._at(second, at2)),
|
||||||
|
])
|
||||||
|
if not result:
|
||||||
|
raise RuntimeError("CHAMFER produced nothing")
|
||||||
|
return result[0]
|
||||||
|
|
||||||
|
def array_rect(self, entities, rows, columns, row_spacing, column_spacing):
|
||||||
|
"""Rectangular array of the entities: `rows` by `columns` copies counting
|
||||||
|
the original, spaced by `row_spacing` and `column_spacing`. Returns the copies."""
|
||||||
|
return self._run("ARRAYRECT", [
|
||||||
|
lambda c: c.text(rows),
|
||||||
|
lambda c: c.text(columns),
|
||||||
|
lambda c: c.text(row_spacing),
|
||||||
|
lambda c: c.text(column_spacing),
|
||||||
|
], entities)
|
||||||
|
|
||||||
|
def array_polar(self, entities, center, count, angle=360):
|
||||||
|
"""Polar array about `center`: `count` items counting the original, spread
|
||||||
|
over `angle` degrees. Returns the copies."""
|
||||||
|
return self._run("ARRAYPOLAR", [
|
||||||
|
lambda c: c.point(center),
|
||||||
|
lambda c: c.text(count),
|
||||||
|
lambda c: c.text(angle),
|
||||||
|
], entities)
|
||||||
|
|
||||||
|
def explode(self, entities):
|
||||||
|
"""Break polylines, blocks and similar entities into their parts; returns the parts."""
|
||||||
|
return self._run("EXPLODE", [], entities)
|
||||||
|
|
||||||
|
def join(self, entities):
|
||||||
|
"""Join end-to-end lines, arcs and polylines into one entity; returns it."""
|
||||||
|
return self._run("JOIN", [], entities)
|
||||||
|
|
||||||
|
def break_entity(self, entity, first, second):
|
||||||
|
"""Remove the part of `entity` between two points on it; returns the new piece."""
|
||||||
|
return self._run("BREAK", [
|
||||||
|
lambda c: c.entity(entity, first),
|
||||||
|
lambda c: c.point(second),
|
||||||
|
])
|
||||||
|
|
||||||
|
def stretch(self, corner1, corner2, base, target):
|
||||||
|
"""Stretch whatever the crossing window (two opposite corners) catches, moving
|
||||||
|
`base` to `target`; entities fully inside move, ones crossing the edge stretch."""
|
||||||
|
self._run("STRETCH", [
|
||||||
|
lambda c: c.point(corner1),
|
||||||
|
lambda c: c.point(corner2),
|
||||||
|
lambda c: c.enter(),
|
||||||
|
lambda c: c.point(base),
|
||||||
|
lambda c: c.point(target),
|
||||||
|
])
|
||||||
|
|
||||||
|
def lengthen(self, entity, delta, at=None):
|
||||||
|
"""Lengthen (or, negative, shorten) `entity` by `delta` at the end nearest `at`."""
|
||||||
|
self._run("LENGTHEN", [
|
||||||
|
lambda c: c.token("DE"),
|
||||||
|
lambda c: c.text(delta),
|
||||||
|
lambda c: c.entity(entity, self._at(entity, at)),
|
||||||
|
lambda c: c.enter(),
|
||||||
|
])
|
||||||
|
|
||||||
|
def array_path(self, entities, path, count, at=None):
|
||||||
|
"""Array the entities along the curve `path`: `count` items counting the
|
||||||
|
original. Returns the copies."""
|
||||||
|
return self._run("ARRAYPATH", [
|
||||||
|
lambda c: c.entity(path, self._at(path, at)),
|
||||||
|
lambda c: c.text(count),
|
||||||
|
], entities)
|
||||||
|
|
||||||
|
def array_3d(self, entities, rows, columns, levels, row_spacing, column_spacing, level_spacing):
|
||||||
|
"""Three-dimensional rectangular array (rows along Y, columns along X, levels
|
||||||
|
along Z); counts include the original. Returns the copies."""
|
||||||
|
return self._run("ARRAY3D", [
|
||||||
|
lambda c: c.text(rows),
|
||||||
|
lambda c: c.text(columns),
|
||||||
|
lambda c: c.text(levels),
|
||||||
|
lambda c: c.text(row_spacing),
|
||||||
|
lambda c: c.text(column_spacing),
|
||||||
|
lambda c: c.text(level_spacing),
|
||||||
|
], entities)
|
||||||
|
|
||||||
|
def _pedit(self, entity, steps, at=None):
|
||||||
|
"""Run PEDIT on one entity: pick it, accept the offer to turn a line or arc
|
||||||
|
into a polyline, apply `steps`, then exit. Returns the polyline entity."""
|
||||||
|
handle = _handle(entity)
|
||||||
|
before = list(ocs.entity_handles())
|
||||||
|
with _Command("PEDIT") as command:
|
||||||
|
command.entity(handle, self._at(entity, at))
|
||||||
|
if "Turn it into one" in command.outcome["prompt"]:
|
||||||
|
command.token("Y")
|
||||||
|
for step in steps:
|
||||||
|
step(command)
|
||||||
|
if command.waiting:
|
||||||
|
command.token("X")
|
||||||
|
_finished(command, "PEDIT")
|
||||||
|
if handle in set(ocs.entity_handles()):
|
||||||
|
return self._document.entities[handle]
|
||||||
|
added = self._added(before)
|
||||||
|
if not added:
|
||||||
|
raise RuntimeError("PEDIT left no polyline")
|
||||||
|
return added[0]
|
||||||
|
|
||||||
|
def polyline_close(self, entity, at=None):
|
||||||
|
"""Close an open polyline (a line or arc is first turned into one)."""
|
||||||
|
return self._pedit(entity, [lambda c: c.token("C")], at)
|
||||||
|
|
||||||
|
def polyline_open(self, entity, at=None):
|
||||||
|
"""Open a closed polyline."""
|
||||||
|
return self._pedit(entity, [lambda c: c.token("O")], at)
|
||||||
|
|
||||||
|
def polyline_width(self, entity, width, at=None):
|
||||||
|
"""Give every segment of a polyline the same width."""
|
||||||
|
return self._pedit(entity, [lambda c: c.token("W"), lambda c: c.text(width)], at)
|
||||||
|
|
||||||
|
def polyline_reverse(self, entity, at=None):
|
||||||
|
"""Reverse a polyline's direction."""
|
||||||
|
return self._pedit(entity, [lambda c: c.token("R")], at)
|
||||||
|
|
||||||
|
def polyline_join(self, entity, others, at=None):
|
||||||
|
"""Join lines, arcs and polylines that meet the polyline's ends into it."""
|
||||||
|
def join(c):
|
||||||
|
c.token("J")
|
||||||
|
self._select(others)
|
||||||
|
c.selection()
|
||||||
|
if c.waiting and "Join" in c.outcome["prompt"]:
|
||||||
|
c.enter()
|
||||||
|
return self._pedit(entity, [join], at)
|
||||||
|
|
||||||
|
def erase(self, entities):
|
||||||
|
before = len(list(ocs.entity_handles()))
|
||||||
|
self._select(entities)
|
||||||
|
with _Command("ERASE") as command:
|
||||||
|
_finished(command, "ERASE")
|
||||||
|
return before - len(list(ocs.entity_handles()))
|
||||||
|
|
||||||
|
|
||||||
|
class _Document:
|
||||||
|
def __init__(self):
|
||||||
|
self._pending = None
|
||||||
|
self.layers = _Layers()
|
||||||
|
self.text_styles = _TextStyles()
|
||||||
|
self.dim_styles = _DimStyles()
|
||||||
|
self.blocks = _Blocks()
|
||||||
|
self.linetypes = _Linetypes()
|
||||||
|
self.layouts = _Layouts()
|
||||||
|
self.modify = _Modify(self)
|
||||||
|
self.entities = _Entities(self)
|
||||||
|
self.solids = _Solids(self)
|
||||||
|
|
||||||
|
def command(self, line):
|
||||||
|
"""Run one whole OCS command line, e.g. `"CIRCLE 5,5 3"`; the tokens after
|
||||||
|
the name answer the prompts in order and a final Enter finishes. Returns
|
||||||
|
the outcome dict. If the line leaves the command waiting for more input the
|
||||||
|
command is cancelled and `RuntimeError` names the prompt; use
|
||||||
|
`start_command` to answer prompts one at a time."""
|
||||||
|
outcome = ocs.command_step("run", {"line": str(line)})
|
||||||
|
if outcome["error"]:
|
||||||
|
raise RuntimeError("%s: %s" % (line, outcome["error"]))
|
||||||
|
if outcome["status"] != "completed":
|
||||||
|
prompt = outcome["prompt"] or outcome["blocked_by"]
|
||||||
|
ocs.command_step("cancel", None)
|
||||||
|
raise RuntimeError("%r did not finish: still asking %r" % (line, prompt))
|
||||||
|
return outcome
|
||||||
|
|
||||||
|
def start_command(self, name):
|
||||||
|
"""Start a command and answer its prompts step by step (see `_Command`)."""
|
||||||
|
return _Command(name)
|
||||||
|
|
||||||
|
def transaction(self, label):
|
||||||
|
return _Transaction(self, label)
|
||||||
|
|
||||||
|
def create_entity(self, kind, block=None, **properties):
|
||||||
|
"""Create one mapped entity and return its live document descriptor.
|
||||||
|
With `block="Name"` the entity is added to that block definition
|
||||||
|
instead of the drawing (its owner is set by the host)."""
|
||||||
|
if "kind" in properties or "handle" in properties:
|
||||||
|
raise ValueError("kind and handle are managed by create_entity")
|
||||||
|
entity = dict(kind=kind, **_coerce_points(kind, properties))
|
||||||
|
if block is not None:
|
||||||
|
handle = ocs.add_to_block(str(block), entity)
|
||||||
|
else:
|
||||||
|
handle = ocs.add(entity)
|
||||||
|
return self.entities[handle]
|
||||||
|
|
||||||
|
def delete_entity(self, entity):
|
||||||
|
"""Delete an entity by descriptor or handle."""
|
||||||
|
handle = entity.handle if isinstance(entity, _Entity) else int(entity)
|
||||||
|
ocs.remove_entity(handle)
|
||||||
|
|
||||||
|
def embed_picture(self, path, origin=(0, 0, 0), width=1, layer=None):
|
||||||
|
"""Embed a picture file (PNG, JPEG, BMP or another format re-encoded as
|
||||||
|
PNG) as an OLE frame. `origin` is the bottom-left corner and `width`
|
||||||
|
the frame width; the height follows the picture's aspect ratio."""
|
||||||
|
handle = ocs.embed_picture(str(path), [float(v) for v in origin], float(width), layer)
|
||||||
|
return self.entities[handle]
|
||||||
|
|
||||||
|
def coverage(self, kind=None):
|
||||||
|
if kind is not None:
|
||||||
|
return ocs.entity_coverage(kind)
|
||||||
|
return {name: ocs.entity_coverage(name) for name in ocs.entity_kinds()}
|
||||||
|
|
||||||
|
def poll_events(self):
|
||||||
|
return ocs.poll_events(ocs.tab_id())
|
||||||
|
|
||||||
|
def request_point(self, prompt="Pick a point"):
|
||||||
|
return ocs.request_input(prompt, False)
|
||||||
|
|
||||||
|
def request_entity(self, prompt="Pick an entity"):
|
||||||
|
return ocs.request_input(prompt, True)
|
||||||
|
|
||||||
|
def poll_input(self, token):
|
||||||
|
return ocs.poll_input(token)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def selection(self):
|
||||||
|
return [self.entities[handle] for handle in ocs.selection()]
|
||||||
|
|
||||||
|
@selection.setter
|
||||||
|
def selection(self, entities):
|
||||||
|
ocs.select([entity.handle if isinstance(entity, _Entity) else int(entity) for entity in entities])
|
||||||
|
|
||||||
|
|
||||||
|
ocs.active_document = _Document()
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
//! Bounded, tab-scoped notifications retained between fresh Python runs.
|
||||||
|
|
||||||
|
use std::collections::{HashMap, VecDeque};
|
||||||
|
use std::sync::Mutex;
|
||||||
|
|
||||||
|
use ocs_plugin_api::host::HostNotification;
|
||||||
|
|
||||||
|
static EVENTS: Mutex<Option<HashMap<u64, TabEvents>>> = Mutex::new(None);
|
||||||
|
const CAPACITY_PER_TAB: usize = 256;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub(crate) enum Event {
|
||||||
|
Drawing {
|
||||||
|
tab_id: u64,
|
||||||
|
version: u64,
|
||||||
|
},
|
||||||
|
Selection {
|
||||||
|
tab_id: u64,
|
||||||
|
handles: Vec<u64>,
|
||||||
|
},
|
||||||
|
Command {
|
||||||
|
tab_id: u64,
|
||||||
|
command: Option<String>,
|
||||||
|
},
|
||||||
|
Overflow {
|
||||||
|
tab_id: u64,
|
||||||
|
dropped: u64,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Event {
|
||||||
|
fn tab_id(&self) -> u64 {
|
||||||
|
match self {
|
||||||
|
Event::Drawing { tab_id, .. }
|
||||||
|
| Event::Selection { tab_id, .. }
|
||||||
|
| Event::Command { tab_id, .. }
|
||||||
|
| Event::Overflow { tab_id, .. } => *tab_id,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct TabEvents {
|
||||||
|
queue: VecDeque<Event>,
|
||||||
|
dropped: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn observe(notification: &HostNotification) {
|
||||||
|
if let HostNotification::DocumentTabClosed { tab_id } = notification {
|
||||||
|
if let Ok(mut lock) = EVENTS.lock() {
|
||||||
|
if let Some(tabs) = lock.as_mut() {
|
||||||
|
tabs.remove(tab_id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let event = match notification {
|
||||||
|
#[cfg(feature = "experimental-host-model")]
|
||||||
|
HostNotification::DrawingChanged { tab_id, epoch } => Event::Drawing {
|
||||||
|
tab_id: *tab_id,
|
||||||
|
version: *epoch,
|
||||||
|
},
|
||||||
|
HostNotification::SelectionChangedV4 { tab_id, handles } => Event::Selection {
|
||||||
|
tab_id: *tab_id,
|
||||||
|
handles: handles.iter().map(|h| h.value()).collect(),
|
||||||
|
},
|
||||||
|
#[cfg(feature = "experimental-host-model")]
|
||||||
|
HostNotification::CommandStateChanged { tab_id, command } => Event::Command {
|
||||||
|
tab_id: *tab_id,
|
||||||
|
command: command.clone(),
|
||||||
|
},
|
||||||
|
_ => return,
|
||||||
|
};
|
||||||
|
if let Ok(mut lock) = EVENTS.lock() {
|
||||||
|
let tab = lock
|
||||||
|
.get_or_insert_with(HashMap::new)
|
||||||
|
.entry(event.tab_id())
|
||||||
|
.or_default();
|
||||||
|
if tab.queue.len() == CAPACITY_PER_TAB {
|
||||||
|
tab.queue.pop_front();
|
||||||
|
tab.dropped += 1;
|
||||||
|
}
|
||||||
|
tab.queue.push_back(event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn drain_for(tab_id: u64) -> Vec<Event> {
|
||||||
|
let Ok(mut lock) = EVENTS.lock() else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
let Some(tabs) = lock.as_mut() else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
let Some(tab) = tabs.remove(&tab_id) else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
let mut events = Vec::with_capacity(tab.queue.len() + usize::from(tab.dropped > 0));
|
||||||
|
if tab.dropped > 0 {
|
||||||
|
events.push(Event::Overflow {
|
||||||
|
tab_id,
|
||||||
|
dropped: tab.dropped,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
events.extend(tab.queue);
|
||||||
|
events
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn polling_one_tab_preserves_other_tabs_events() {
|
||||||
|
observe(&HostNotification::DrawingChanged {
|
||||||
|
tab_id: 101,
|
||||||
|
epoch: 1,
|
||||||
|
});
|
||||||
|
observe(&HostNotification::DrawingChanged {
|
||||||
|
tab_id: 102,
|
||||||
|
epoch: 2,
|
||||||
|
});
|
||||||
|
assert_eq!(
|
||||||
|
drain_for(101),
|
||||||
|
vec![Event::Drawing {
|
||||||
|
tab_id: 101,
|
||||||
|
version: 1
|
||||||
|
}]
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
drain_for(102),
|
||||||
|
vec![Event::Drawing {
|
||||||
|
tab_id: 102,
|
||||||
|
version: 2
|
||||||
|
}]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn noisy_tab_reports_its_own_overflow_without_evicting_another_tab() {
|
||||||
|
observe(&HostNotification::DrawingChanged {
|
||||||
|
tab_id: 201,
|
||||||
|
epoch: 7,
|
||||||
|
});
|
||||||
|
for epoch in 0..=CAPACITY_PER_TAB as u64 {
|
||||||
|
observe(&HostNotification::DrawingChanged { tab_id: 202, epoch });
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
drain_for(201),
|
||||||
|
vec![Event::Drawing {
|
||||||
|
tab_id: 201,
|
||||||
|
version: 7
|
||||||
|
}]
|
||||||
|
);
|
||||||
|
let events = drain_for(202);
|
||||||
|
assert_eq!(events.len(), CAPACITY_PER_TAB + 1);
|
||||||
|
assert_eq!(
|
||||||
|
events[0],
|
||||||
|
Event::Overflow {
|
||||||
|
tab_id: 202,
|
||||||
|
dropped: 1
|
||||||
|
}
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
events[1],
|
||||||
|
Event::Drawing {
|
||||||
|
tab_id: 202,
|
||||||
|
version: 1
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn closing_tab_discards_its_pending_events() {
|
||||||
|
observe(&HostNotification::DrawingChanged {
|
||||||
|
tab_id: 301,
|
||||||
|
epoch: 3,
|
||||||
|
});
|
||||||
|
observe(&HostNotification::DocumentTabClosed { tab_id: 301 });
|
||||||
|
assert!(drain_for(301).is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn drawing_selection_and_command_events_keep_delivery_order() {
|
||||||
|
use ocs_plugin_api::host::Handle;
|
||||||
|
observe(&HostNotification::DrawingChanged {
|
||||||
|
tab_id: 401,
|
||||||
|
epoch: 9,
|
||||||
|
});
|
||||||
|
observe(&HostNotification::SelectionChangedV4 {
|
||||||
|
tab_id: 401,
|
||||||
|
handles: vec![Handle::new(17)],
|
||||||
|
});
|
||||||
|
observe(&HostNotification::CommandStateChanged {
|
||||||
|
tab_id: 401,
|
||||||
|
command: Some("LINE".into()),
|
||||||
|
});
|
||||||
|
observe(&HostNotification::CommandStateChanged {
|
||||||
|
tab_id: 401,
|
||||||
|
command: None,
|
||||||
|
});
|
||||||
|
assert_eq!(
|
||||||
|
drain_for(401),
|
||||||
|
vec![
|
||||||
|
Event::Drawing {
|
||||||
|
tab_id: 401,
|
||||||
|
version: 9
|
||||||
|
},
|
||||||
|
Event::Selection {
|
||||||
|
tab_id: 401,
|
||||||
|
handles: vec![17]
|
||||||
|
},
|
||||||
|
Event::Command {
|
||||||
|
tab_id: 401,
|
||||||
|
command: Some("LINE".into())
|
||||||
|
},
|
||||||
|
Event::Command {
|
||||||
|
tab_id: 401,
|
||||||
|
command: None
|
||||||
|
},
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
//! Thread-local scratch slot that gives the `ocs` module's native functions
|
||||||
|
//! access to the `HostApi` for the currently running `PY_EVAL` call.
|
||||||
|
//!
|
||||||
|
//! RustPython native functions registered via `#[pymodule]` are plain free
|
||||||
|
//! functions — `add_native_module` takes a `&'static PyModuleDef`, so there is
|
||||||
|
//! no per-call closure environment to capture `host: &mut dyn HostApi` in.
|
||||||
|
//! This is the standard pattern for bridging an embedder's per-call context
|
||||||
|
//! into embedded callbacks (the same shape as Lua userdata or a C callback's
|
||||||
|
//! `void *ctx`): stash a pointer for the duration of one interpreter run, and
|
||||||
|
//! clear it before the run's borrow of `host` ends.
|
||||||
|
|
||||||
|
use std::cell::Cell;
|
||||||
|
|
||||||
|
use ocs_plugin_api::host::HostApi;
|
||||||
|
|
||||||
|
thread_local! {
|
||||||
|
static CURRENT_HOST: Cell<Option<*mut dyn HostApi>> = const { Cell::new(None) };
|
||||||
|
static UNDO_LABEL: Cell<&'static str> = const { Cell::new("") };
|
||||||
|
static UNDO_STARTED: Cell<bool> = const { Cell::new(false) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Holds the thread-local host pointer for its lifetime; clears it on drop.
|
||||||
|
/// Must not outlive the `&mut dyn HostApi` borrow it was constructed from.
|
||||||
|
pub(crate) struct HostGuard;
|
||||||
|
|
||||||
|
impl HostGuard {
|
||||||
|
/// `undo_label` is the label a later `ensure_undo_started()` call (from
|
||||||
|
/// an `ocs` write function) will pass to `host.push_undo` — see its doc
|
||||||
|
/// comment for why this is one group per script, not one per call.
|
||||||
|
pub(crate) fn set(host: &mut dyn HostApi, undo_label: &'static str) -> Self {
|
||||||
|
// SAFETY: erases `host`'s borrow lifetime so the fat pointer fits in a
|
||||||
|
// `'static` thread_local slot (same layout either way: two words,
|
||||||
|
// data + vtable). Sound only because `Drop` clears the slot before
|
||||||
|
// this borrow's real lifetime ends — see `with_host`'s safety note.
|
||||||
|
let ptr: *mut dyn HostApi =
|
||||||
|
unsafe { std::mem::transmute::<&mut dyn HostApi, *mut dyn HostApi>(host) };
|
||||||
|
CURRENT_HOST.with(|cell| cell.set(Some(ptr)));
|
||||||
|
UNDO_LABEL.with(|cell| cell.set(undo_label));
|
||||||
|
UNDO_STARTED.with(|cell| cell.set(false));
|
||||||
|
HostGuard
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for HostGuard {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
CURRENT_HOST.with(|cell| cell.set(None));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Call from an `ocs` write function (`add_line`, ...) right before it
|
||||||
|
/// mutates the document. Starts exactly one `host.push_undo` group per
|
||||||
|
/// `PY_EVAL`/`PY_RUN` call, however many entities the script adds — a script
|
||||||
|
/// that adds ten lines should undo as one step, not ten. A no-op for a
|
||||||
|
/// script that never writes, so a pure `PY_EVAL 1 + 1` doesn't clutter the
|
||||||
|
/// undo stack.
|
||||||
|
pub(crate) fn ensure_undo_started(host: &mut dyn HostApi) {
|
||||||
|
UNDO_STARTED.with(|started| {
|
||||||
|
if !started.get() {
|
||||||
|
host.push_undo(UNDO_LABEL.with(|label| label.get()));
|
||||||
|
started.set(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run `f` with the `HostApi` active for the current `PY_EVAL` call, if any.
|
||||||
|
/// Returns `None` outside of a `HostGuard`-covered call (a script should never
|
||||||
|
/// observe this in practice, since the guard spans the whole interpreter run).
|
||||||
|
///
|
||||||
|
/// Not reentrant: `f` must not call `with_host` again itself, since that would
|
||||||
|
/// materialize two live `&mut dyn HostApi` referring to the same host at once.
|
||||||
|
/// Fine for Phase 1.2's `selection()`/`get()`, which don't call each other.
|
||||||
|
pub(crate) fn with_host<R>(f: impl FnOnce(&mut dyn HostApi) -> R) -> Option<R> {
|
||||||
|
CURRENT_HOST.with(|cell| {
|
||||||
|
let ptr = cell.get()?;
|
||||||
|
// SAFETY: `ptr` is only ever set by `HostGuard::set`, which is created
|
||||||
|
// from a live `&mut dyn HostApi` and cleared (via `Drop`) before that
|
||||||
|
// borrow's scope ends. The interpreter run this pointer is valid for
|
||||||
|
// happens entirely on this thread, within that same scope.
|
||||||
|
Some(f(unsafe { &mut *ptr }))
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
//! Results of host-driven point/entity picks, retained across Python runs.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
|
use std::sync::Mutex;
|
||||||
|
|
||||||
|
use ocs_plugin_api::host::{CommandStep, Handle, InteractiveCommand};
|
||||||
|
|
||||||
|
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
|
||||||
|
static RESULTS: Mutex<Option<HashMap<u64, (u64, PickResult)>>> = Mutex::new(None);
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub(crate) enum PickResult {
|
||||||
|
Pending,
|
||||||
|
Point([f64; 3]),
|
||||||
|
Entity { handle: u64, point: [f64; 3] },
|
||||||
|
Cancelled,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct PickCommand {
|
||||||
|
id: u64,
|
||||||
|
tab_id: u64,
|
||||||
|
prompt: String,
|
||||||
|
entity: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn begin(tab_id: u64, prompt: String, entity: bool) -> (u64, PickCommand) {
|
||||||
|
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
|
||||||
|
if let Ok(mut lock) = RESULTS.lock() {
|
||||||
|
let results = lock.get_or_insert_with(HashMap::new);
|
||||||
|
if results.len() >= 1024 {
|
||||||
|
if let Some(oldest) = results.keys().min().copied() {
|
||||||
|
results.remove(&oldest);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
results.insert(id, (tab_id, PickResult::Pending));
|
||||||
|
}
|
||||||
|
(
|
||||||
|
id,
|
||||||
|
PickCommand {
|
||||||
|
id,
|
||||||
|
tab_id,
|
||||||
|
prompt,
|
||||||
|
entity,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn take(tab_id: u64, id: u64) -> Option<PickResult> {
|
||||||
|
let mut lock = RESULTS.lock().ok()?;
|
||||||
|
let results = lock.as_mut()?;
|
||||||
|
let (owner, result) = results.get(&id)?;
|
||||||
|
if *owner != tab_id {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if matches!(result, PickResult::Pending) {
|
||||||
|
return Some(PickResult::Pending);
|
||||||
|
}
|
||||||
|
results.remove(&id).map(|(_, result)| result)
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PickCommand {
|
||||||
|
fn finish(&self, result: PickResult) {
|
||||||
|
if let Ok(mut lock) = RESULTS.lock() {
|
||||||
|
lock.get_or_insert_with(HashMap::new)
|
||||||
|
.insert(self.id, (self.tab_id, result));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for PickCommand {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if let Ok(mut lock) = RESULTS.lock() {
|
||||||
|
if let Some((owner, PickResult::Pending)) = lock.as_mut().and_then(|r| r.get(&self.id))
|
||||||
|
{
|
||||||
|
if *owner == self.tab_id {
|
||||||
|
lock.as_mut()
|
||||||
|
.unwrap()
|
||||||
|
.insert(self.id, (self.tab_id, PickResult::Cancelled));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl InteractiveCommand for PickCommand {
|
||||||
|
fn prompt(&self) -> String {
|
||||||
|
self.prompt.clone()
|
||||||
|
}
|
||||||
|
fn needs_object_pick(&self) -> bool {
|
||||||
|
self.entity
|
||||||
|
}
|
||||||
|
fn on_point(&mut self, point: [f64; 3]) -> CommandStep {
|
||||||
|
if self.entity {
|
||||||
|
return CommandStep::NeedPoint;
|
||||||
|
}
|
||||||
|
self.finish(PickResult::Point(point));
|
||||||
|
CommandStep::Done
|
||||||
|
}
|
||||||
|
fn on_object_pick(&mut self, handle: Handle, point: [f64; 3]) -> CommandStep {
|
||||||
|
if !self.entity {
|
||||||
|
return CommandStep::NeedPoint;
|
||||||
|
}
|
||||||
|
self.finish(PickResult::Entity {
|
||||||
|
handle: handle.value(),
|
||||||
|
point,
|
||||||
|
});
|
||||||
|
CommandStep::Done
|
||||||
|
}
|
||||||
|
fn on_enter(&mut self) -> CommandStep {
|
||||||
|
self.finish(PickResult::Cancelled);
|
||||||
|
CommandStep::Cancel
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn point_and_entity_picks_complete_tokens() {
|
||||||
|
let (point_token, mut point) = begin(7, "Point".into(), false);
|
||||||
|
assert!(matches!(take(7, point_token), Some(PickResult::Pending)));
|
||||||
|
assert!(take(8, point_token).is_none());
|
||||||
|
assert!(matches!(point.on_point([1.0, 2.0, 3.0]), CommandStep::Done));
|
||||||
|
assert!(take(8, point_token).is_none());
|
||||||
|
assert!(matches!(
|
||||||
|
take(7, point_token),
|
||||||
|
Some(PickResult::Point([1.0, 2.0, 3.0]))
|
||||||
|
));
|
||||||
|
let (entity_token, mut entity) = begin(8, "Entity".into(), true);
|
||||||
|
assert!(entity.needs_object_pick());
|
||||||
|
assert!(matches!(
|
||||||
|
entity.on_object_pick(Handle::new(17), [2.0, 0.0, 0.0]),
|
||||||
|
CommandStep::Done
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
take(8, entity_token),
|
||||||
|
Some(PickResult::Entity { handle: 17, .. })
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn abandoned_pick_reports_cancellation() {
|
||||||
|
let (token, command) = begin(7, "Point".into(), false);
|
||||||
|
drop(command);
|
||||||
|
assert!(take(8, token).is_none());
|
||||||
|
assert!(matches!(take(7, token), Some(PickResult::Cancelled)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn enter_cancels_pick_without_returning_a_point() {
|
||||||
|
let (token, mut command) = begin(9, "Pick".into(), false);
|
||||||
|
assert!(matches!(command.on_enter(), CommandStep::Cancel));
|
||||||
|
assert!(matches!(take(9, token), Some(PickResult::Cancelled)));
|
||||||
|
drop(command);
|
||||||
|
assert!(take(9, token).is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,321 @@
|
|||||||
|
//! Python scripting plugin for Open CAD Studio.
|
||||||
|
//!
|
||||||
|
//! Phase 1.2 of `ROADMAP.md`: a read-only `ocs` module (`ocs.selection()`,
|
||||||
|
//! `ocs.get(handle)`) plus `PY_EVAL <expr>` to evaluate one inline Python
|
||||||
|
//! expression. Phase 1.3: 2D write access (`ocs.add_line`/`ocs.add_circle`)
|
||||||
|
//! plus `PY_RUN <path.py>` to run a script file. The experimental
|
||||||
|
//! `ocs.command("...")` / `ocs.select(handles)` functions remain disabled in
|
||||||
|
//! the bundled build because nested command replay can hang.
|
||||||
|
|
||||||
|
#[cfg(feature = "experimental-host-model")]
|
||||||
|
mod event_cache;
|
||||||
|
mod host_ctx;
|
||||||
|
#[cfg(feature = "experimental-host-model")]
|
||||||
|
mod input_cache;
|
||||||
|
mod ocs_module;
|
||||||
|
mod selection_cache;
|
||||||
|
|
||||||
|
use ocs_plugin_api::host::{BuiltinPlugin, HostApi, HostNotification};
|
||||||
|
use ocs_plugin_api::manifest::{ApiVersion, PluginManifest};
|
||||||
|
use ocs_plugin_api::ribbon::{CadModule, IconKind, ModuleEvent, RibbonGroup, RibbonItem, ToolDef};
|
||||||
|
|
||||||
|
pub(crate) const PLUGIN_ID: &str = "opencad.python";
|
||||||
|
|
||||||
|
// Keep these fields in sync with `plugin.toml`.
|
||||||
|
static MANIFEST: PluginManifest = PluginManifest {
|
||||||
|
id: PLUGIN_ID,
|
||||||
|
name: "Python Scripting",
|
||||||
|
version: env!("CARGO_PKG_VERSION"),
|
||||||
|
description: "Embedded Python scripting (RustPython) for Open CAD Studio.",
|
||||||
|
api_version: ApiVersion::CURRENT,
|
||||||
|
ribbon_order: 60,
|
||||||
|
xdata_apps: &[],
|
||||||
|
command_prefixes: &["PY_"],
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The ribbon tab.
|
||||||
|
struct PythonModule;
|
||||||
|
|
||||||
|
impl CadModule for PythonModule {
|
||||||
|
fn id(&self) -> &'static str {
|
||||||
|
"opencad_python"
|
||||||
|
}
|
||||||
|
fn title(&self) -> &'static str {
|
||||||
|
"Python Scripting"
|
||||||
|
}
|
||||||
|
fn ribbon_groups(&self) -> &[RibbonGroup] {
|
||||||
|
static GROUPS: std::sync::OnceLock<Vec<RibbonGroup>> = std::sync::OnceLock::new();
|
||||||
|
GROUPS.get_or_init(|| {
|
||||||
|
vec![RibbonGroup {
|
||||||
|
title: "Tools",
|
||||||
|
tools: vec![
|
||||||
|
RibbonItem::LargeTool(ToolDef {
|
||||||
|
id: "PY_EVAL",
|
||||||
|
label: "Eval 1+1",
|
||||||
|
icon: IconKind::Glyph("★"),
|
||||||
|
event: ModuleEvent::Command("PY_EVAL 1 + 1".to_string()),
|
||||||
|
}),
|
||||||
|
RibbonItem::LargeTool(ToolDef {
|
||||||
|
id: "PY_RUN",
|
||||||
|
label: "Run Script…",
|
||||||
|
icon: IconKind::Glyph("▶"),
|
||||||
|
event: ModuleEvent::PluginFileDialog {
|
||||||
|
command: "PY_RUN".to_string(),
|
||||||
|
title: "Run Python Script".to_string(),
|
||||||
|
filter_name: "Python Scripts".to_string(),
|
||||||
|
extensions: vec!["py".to_string()],
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
}]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The plugin entry point.
|
||||||
|
struct PythonPlugin;
|
||||||
|
|
||||||
|
impl BuiltinPlugin for PythonPlugin {
|
||||||
|
fn manifest(&self) -> &'static PluginManifest {
|
||||||
|
&MANIFEST
|
||||||
|
}
|
||||||
|
fn ribbon(&self) -> Box<dyn CadModule> {
|
||||||
|
Box::new(PythonModule)
|
||||||
|
}
|
||||||
|
fn dispatch(&self, host: &mut dyn HostApi, cmd: &str) -> bool {
|
||||||
|
if let Some(rest) = cmd.strip_prefix("PY_EVAL") {
|
||||||
|
let source = rest.trim();
|
||||||
|
if source.is_empty() {
|
||||||
|
host.push_error("PY_EVAL: expected a Python expression, e.g. PY_EVAL 1 + 1");
|
||||||
|
} else {
|
||||||
|
run_eval(host, source);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if let Some(rest) = cmd.strip_prefix("PY_RUN") {
|
||||||
|
let path = rest.trim();
|
||||||
|
if path.is_empty() {
|
||||||
|
host.push_error("PY_RUN: expected a file path, e.g. PY_RUN script.py");
|
||||||
|
} else {
|
||||||
|
run_file(host, path);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The runner's own event loop drains `HostApi::try_recv_notification()`
|
||||||
|
/// *before* any `Dispatch` request reaches `dispatch()` — calling it from
|
||||||
|
/// there always sees an empty queue. This callback is the only place a
|
||||||
|
/// V4+ plugin actually observes notifications; see `selection_cache.rs`.
|
||||||
|
fn on_notification(&mut self, _command_id: Option<u64>, notification: HostNotification) {
|
||||||
|
#[cfg(feature = "experimental-host-model")]
|
||||||
|
event_cache::observe(¬ification);
|
||||||
|
match notification {
|
||||||
|
HostNotification::SelectionChanged { handles } => selection_cache::set(handles),
|
||||||
|
HostNotification::SelectionChangedV4 { handles, .. } => selection_cache::set(handles),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Evaluate one Python expression against a fresh interpreter (no session
|
||||||
|
/// persistence yet — that's a Phase 3 open question) and report the result or
|
||||||
|
/// error via the command line. A script bug must never look like a silent
|
||||||
|
/// no-op, so both paths always push something.
|
||||||
|
fn run_eval(host: &mut dyn HostApi, source: &str) {
|
||||||
|
let guard = host_ctx::HostGuard::set(host, "PY_EVAL");
|
||||||
|
|
||||||
|
let builder = rustpython_vm::Interpreter::builder(Default::default());
|
||||||
|
let ocs_def = ocs_module::module_def(&builder.ctx);
|
||||||
|
let interp = builder.add_native_module(ocs_def).build();
|
||||||
|
|
||||||
|
let outcome = interp.enter(|vm| -> Result<(String, String), String> {
|
||||||
|
let output = install_output_capture(vm)?;
|
||||||
|
let scope = vm.new_scope_with_builtins();
|
||||||
|
// Pre-bind `ocs` in scope so a one-expression `PY_EVAL` can call
|
||||||
|
// `ocs.selection()` directly — `Mode::Eval` only accepts a single
|
||||||
|
// expression, so a script has no way to run an `import` statement
|
||||||
|
// itself.
|
||||||
|
let ocs = vm
|
||||||
|
.import("ocs", 0)
|
||||||
|
.map_err(|exc| exception_to_string(vm, &exc))?;
|
||||||
|
scope
|
||||||
|
.globals
|
||||||
|
.set_item("ocs", ocs, vm)
|
||||||
|
.map_err(|exc| exception_to_string(vm, &exc))?;
|
||||||
|
#[cfg(feature = "experimental-host-model")]
|
||||||
|
install_document_model(vm, &scope)?;
|
||||||
|
let code_obj = vm
|
||||||
|
.compile(
|
||||||
|
source,
|
||||||
|
rustpython_vm::compiler::Mode::Eval,
|
||||||
|
"<py_eval>".to_string(),
|
||||||
|
)
|
||||||
|
.map_err(|err| err.to_string())?;
|
||||||
|
let result = match vm.run_code_obj(code_obj, scope) {
|
||||||
|
Ok(result) => result
|
||||||
|
.str(vm)
|
||||||
|
.map(|s| s.to_string())
|
||||||
|
.map_err(|exc| exception_to_string(vm, &exc)),
|
||||||
|
Err(exc) => Err(exception_to_string(vm, &exc)),
|
||||||
|
}?;
|
||||||
|
Ok((result, captured_output(vm, &output)?))
|
||||||
|
});
|
||||||
|
|
||||||
|
drop(guard);
|
||||||
|
|
||||||
|
match outcome {
|
||||||
|
Ok((text, printed)) => {
|
||||||
|
if !printed.is_empty() {
|
||||||
|
host.push_output(&printed);
|
||||||
|
}
|
||||||
|
host.push_output(&text);
|
||||||
|
}
|
||||||
|
Err(err) => host.push_error(&err),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run a `.py` file (`PY_RUN <path>`) — same interpreter setup as `PY_EVAL`,
|
||||||
|
/// but `Mode::Exec` (statements, not a single expression) since a file can
|
||||||
|
/// hold a whole script. Reports errors the same way as `PY_EVAL`; on success
|
||||||
|
/// reports that the script ran rather than a value (`Mode::Exec` doesn't
|
||||||
|
/// produce one).
|
||||||
|
fn run_file(host: &mut dyn HostApi, path: &str) {
|
||||||
|
let source = match std::fs::read_to_string(path) {
|
||||||
|
Ok(text) => text,
|
||||||
|
Err(err) => {
|
||||||
|
host.push_error(&format!("PY_RUN: cannot read {path}: {err}"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let guard = host_ctx::HostGuard::set(host, "PY_RUN");
|
||||||
|
|
||||||
|
let builder = rustpython_vm::Interpreter::builder(Default::default());
|
||||||
|
let ocs_def = ocs_module::module_def(&builder.ctx);
|
||||||
|
let interp = builder.add_native_module(ocs_def).build();
|
||||||
|
|
||||||
|
let outcome = interp.enter(|vm| -> Result<String, String> {
|
||||||
|
let output = install_output_capture(vm)?;
|
||||||
|
let scope = vm.new_scope_with_builtins();
|
||||||
|
let ocs = vm
|
||||||
|
.import("ocs", 0)
|
||||||
|
.map_err(|exc| exception_to_string(vm, &exc))?;
|
||||||
|
scope
|
||||||
|
.globals
|
||||||
|
.set_item("ocs", ocs, vm)
|
||||||
|
.map_err(|exc| exception_to_string(vm, &exc))?;
|
||||||
|
#[cfg(feature = "experimental-host-model")]
|
||||||
|
install_document_model(vm, &scope)?;
|
||||||
|
let code_obj = vm
|
||||||
|
.compile(
|
||||||
|
&source,
|
||||||
|
rustpython_vm::compiler::Mode::Exec,
|
||||||
|
path.to_string(),
|
||||||
|
)
|
||||||
|
.map_err(|err| err.to_string())?;
|
||||||
|
vm.run_code_obj(code_obj, scope)
|
||||||
|
.map_err(|exc| exception_to_string(vm, &exc))?;
|
||||||
|
captured_output(vm, &output)
|
||||||
|
});
|
||||||
|
|
||||||
|
drop(guard);
|
||||||
|
|
||||||
|
match outcome {
|
||||||
|
Ok(printed) => {
|
||||||
|
if !printed.is_empty() {
|
||||||
|
host.push_output(&printed);
|
||||||
|
}
|
||||||
|
host.push_output(&format!("PY_RUN: {path} completed"));
|
||||||
|
}
|
||||||
|
Err(err) => host.push_error(&err),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "experimental-host-model")]
|
||||||
|
fn install_document_model(
|
||||||
|
vm: &rustpython_vm::VirtualMachine,
|
||||||
|
scope: &rustpython_vm::scope::Scope,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let code = vm
|
||||||
|
.compile(
|
||||||
|
include_str!("document_model.py"),
|
||||||
|
rustpython_vm::compiler::Mode::Exec,
|
||||||
|
"<ocs_document_model>".to_owned(),
|
||||||
|
)
|
||||||
|
.map_err(|error| error.to_string())?;
|
||||||
|
vm.run_code_obj(code, scope.clone())
|
||||||
|
.map_err(|exc| exception_to_string(vm, &exc))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(all(test, feature = "experimental-host-model"))]
|
||||||
|
#[test]
|
||||||
|
fn document_model_bootstraps_in_rustpython() {
|
||||||
|
let builder = rustpython_vm::Interpreter::builder(Default::default());
|
||||||
|
let ocs_def = ocs_module::module_def(&builder.ctx);
|
||||||
|
let interp = builder.add_native_module(ocs_def).build();
|
||||||
|
interp.enter(|vm| {
|
||||||
|
let scope = vm.new_scope_with_builtins();
|
||||||
|
let ocs = vm.import("ocs", 0).unwrap();
|
||||||
|
scope.globals.set_item("ocs", ocs, vm).unwrap();
|
||||||
|
install_document_model(vm, &scope).unwrap();
|
||||||
|
let code = vm
|
||||||
|
.compile(
|
||||||
|
"ocs.active_document.transaction('Move line').label",
|
||||||
|
rustpython_vm::compiler::Mode::Eval,
|
||||||
|
"<model_test>".to_owned(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let label = vm.run_code_obj(code, scope).unwrap();
|
||||||
|
assert_eq!(label.str(vm).unwrap().to_string(), "Move line");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// RustPython is built without its stdio feature, so sys.stdout/stderr are
|
||||||
|
/// None by default. Give each fresh interpreter a memory stream for print().
|
||||||
|
fn install_output_capture(
|
||||||
|
vm: &rustpython_vm::VirtualMachine,
|
||||||
|
) -> Result<rustpython_vm::PyObjectRef, String> {
|
||||||
|
let sys = vm
|
||||||
|
.import("sys", 0)
|
||||||
|
.map_err(|exc| exception_to_string(vm, &exc))?;
|
||||||
|
let io = vm
|
||||||
|
.import("_io", 0)
|
||||||
|
.map_err(|exc| exception_to_string(vm, &exc))?;
|
||||||
|
let output = vm
|
||||||
|
.call_method(&io, "StringIO", ())
|
||||||
|
.map_err(|exc| exception_to_string(vm, &exc))?;
|
||||||
|
sys.set_attr("stdout", output.clone(), vm)
|
||||||
|
.map_err(|exc| exception_to_string(vm, &exc))?;
|
||||||
|
sys.set_attr("stderr", output.clone(), vm)
|
||||||
|
.map_err(|exc| exception_to_string(vm, &exc))?;
|
||||||
|
Ok(output)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn captured_output(
|
||||||
|
vm: &rustpython_vm::VirtualMachine,
|
||||||
|
output: &rustpython_vm::PyObjectRef,
|
||||||
|
) -> Result<String, String> {
|
||||||
|
vm.call_method(output, "getvalue", ())
|
||||||
|
.and_then(|value| value.str(vm))
|
||||||
|
.map(|value| value.to_string().trim_end_matches('\n').to_owned())
|
||||||
|
.map_err(|exc| exception_to_string(vm, &exc))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `"<TypeName>: <message>"`, the same shape `str(exception)` plus its type
|
||||||
|
/// name produces in CPython — no full traceback yet (Phase 1.2 is minimal;
|
||||||
|
/// see the roadmap's error-handling note).
|
||||||
|
fn exception_to_string(
|
||||||
|
vm: &rustpython_vm::VirtualMachine,
|
||||||
|
exc: &rustpython_vm::builtins::PyBaseExceptionRef,
|
||||||
|
) -> String {
|
||||||
|
let exc_obj: rustpython_vm::PyObjectRef = exc.clone().into();
|
||||||
|
let type_name = exc_obj.class().name().to_string();
|
||||||
|
let message = exc_obj.str(vm).map(|s| s.to_string()).unwrap_or_default();
|
||||||
|
format!("{type_name}: {message}")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Emit the C-ABI symbols the host loader looks for.
|
||||||
|
ocs_plugin_api::export_plugin!(PythonPlugin);
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,23 @@
|
|||||||
|
// Merge helpers for nested structs that scripts edit as a partial patch.
|
||||||
|
|
||||||
|
/// Apply `patch` (a dict of context fields) onto `existing`, so a script can
|
||||||
|
/// change one context field without resetting the rest. Unknown keys error.
|
||||||
|
fn merge_multileader_context(
|
||||||
|
existing: &acadrust::entities::MultiLeaderAnnotContext,
|
||||||
|
patch: PyObjectRef,
|
||||||
|
vm: &VirtualMachine,
|
||||||
|
) -> PyResult<acadrust::entities::MultiLeaderAnnotContext> {
|
||||||
|
let patch = patch.try_into_value::<rustpython_vm::builtins::PyDictRef>(vm)?;
|
||||||
|
let merged = multi_leader_annot_context_to_dict(vm, existing)?
|
||||||
|
.try_into_value::<rustpython_vm::builtins::PyDictRef>(vm)?;
|
||||||
|
for key in patch.keys_vec() {
|
||||||
|
let name = key.clone().try_into_value::<String>(vm)?;
|
||||||
|
if merged.get_item_opt(name.as_str(), vm)?.is_none() {
|
||||||
|
return Err(vm.new_value_error(format!(
|
||||||
|
"ocs: MultiLeader.context property {name:?} is outside the editable schema"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
merged.set_item(name.as_str(), patch.get_item(name.as_str(), vm)?, vm)?;
|
||||||
|
}
|
||||||
|
dict_to_multi_leader_annot_context(merged.into(), vm)
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
//! Process-wide cache of the most recently observed selection.
|
||||||
|
//!
|
||||||
|
//! `HostApi` has no synchronous "give me the current selection" call — only
|
||||||
|
//! the best-effort `SelectionChanged` / `SelectionChangedV4` notification.
|
||||||
|
//! Naively calling `HostApi::try_recv_notification()` from inside `dispatch`
|
||||||
|
//! doesn't work: `ocs_plugin_api::runner`'s own V4 event loop
|
||||||
|
//! (`run_v4` in `runner.rs`) drains that queue itself on every iteration,
|
||||||
|
//! forwarding each notification to `BuiltinPlugin::on_notification` *before*
|
||||||
|
//! a `Dispatch` request ever reaches `dispatch()` — so by the time `dispatch`
|
||||||
|
//! runs, the queue is always empty. The only way to observe notifications is
|
||||||
|
//! to override `on_notification` and stash what's needed here; `dispatch`
|
||||||
|
//! (and the `ocs.selection()` pyfunction) then just reads this cache.
|
||||||
|
//!
|
||||||
|
//! A plain process-wide static is fine here: one plugin process hosts exactly
|
||||||
|
//! one `PythonPlugin`, so this is equivalent to an instance field, but a
|
||||||
|
//! static is far simpler to reach from the `#[pymodule]` native functions in
|
||||||
|
//! `ocs_module.rs`, which have no path back to the `BuiltinPlugin` instance.
|
||||||
|
|
||||||
|
use std::sync::Mutex;
|
||||||
|
|
||||||
|
use ocs_plugin_api::host::Handle;
|
||||||
|
|
||||||
|
static CACHE: Mutex<Vec<Handle>> = Mutex::new(Vec::new());
|
||||||
|
|
||||||
|
pub(crate) fn set(handles: Vec<Handle>) {
|
||||||
|
if let Ok(mut cache) = CACHE.lock() {
|
||||||
|
*cache = handles;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn get() -> Vec<Handle> {
|
||||||
|
CACHE.lock().map(|cache| cache.clone()).unwrap_or_default()
|
||||||
|
}
|
||||||
@@ -0,0 +1,310 @@
|
|||||||
|
import pathlib
|
||||||
|
import types
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
|
||||||
|
MODEL = pathlib.Path(__file__).resolve().parents[1] / "src" / "document_model.py"
|
||||||
|
|
||||||
|
|
||||||
|
class DocumentModelTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.records = {
|
||||||
|
1: {"handle": 1, "kind": "Line", "layer": "0", "start": {"x": 1, "y": 2, "z": 3},
|
||||||
|
"end": {"x": 4, "y": 5, "z": 6}, "_editable": True},
|
||||||
|
2: {"handle": 2, "kind": "Hatch", "layer": "0", "_editable": False},
|
||||||
|
}
|
||||||
|
self.calls = []
|
||||||
|
self.ocs = types.SimpleNamespace(
|
||||||
|
entity_descriptor=lambda handle: self.records.get(handle),
|
||||||
|
entity_coverage=lambda kind: {"kind": kind, "scope": "canvas",
|
||||||
|
"editable": ["start", "end", "layer"] if kind == "Line" else ["layer"],
|
||||||
|
"readable": ["handle", "kind", "layer"], "unmapped": []},
|
||||||
|
entity_kinds=lambda: ["Line", "Hatch"],
|
||||||
|
entity_snapshot=lambda handle: {self.records[handle]["kind"]: {
|
||||||
|
"common": {"layer": self.records[handle]["layer"]},
|
||||||
|
"pattern_name": "SOLID" if handle == 2 else None,
|
||||||
|
}} if handle in self.records else None,
|
||||||
|
entity_handles=lambda: list(self.records),
|
||||||
|
update_many=lambda label, updates: self.calls.append((label, updates)),
|
||||||
|
add=lambda entity: self.calls.append(("add", entity)) or 1,
|
||||||
|
remove_entity=lambda handle: self.calls.append(("remove", handle)),
|
||||||
|
selection=lambda: [1],
|
||||||
|
select=lambda handles: self.calls.append(("selection", handles)),
|
||||||
|
poll_events=lambda tab: [{"type": "drawing", "tab_id": tab}],
|
||||||
|
tab_id=lambda: 7,
|
||||||
|
request_input=lambda prompt, entity: (prompt, entity),
|
||||||
|
poll_input=lambda token: {"status": "point", "point": [1, 2, 3]},
|
||||||
|
layer_records=lambda: [{"name": "0", "current": True}, {"name": "Walls", "current": False}],
|
||||||
|
layer_operation=lambda op, name, options: self.calls.append((op, name, options)) or 9,
|
||||||
|
text_style_records=lambda: [{"name": n, "current": n == "Standard"} for n in ("Standard", "Title", "Notes")],
|
||||||
|
dim_style_records=lambda: [{"name": n, "current": n == "Standard"} for n in ("Standard", "Metric")],
|
||||||
|
style_operation=lambda kind, op, name, options: self.calls.append((kind, op, name, options)) or 9,
|
||||||
|
block_records=lambda: [{"name": n, "entities": []} for n in ("Widget", "Gadget")],
|
||||||
|
block_operation=lambda op, name, options: self.calls.append(("block", op, name, options)) or 9,
|
||||||
|
add_to_block=lambda block, entity: self.calls.append(("add_to_block", block, entity)) or 1,
|
||||||
|
linetype_records=lambda: [{"name": n} for n in ("Continuous", "Bracket")],
|
||||||
|
linetype_operation=lambda op, name, options: self.calls.append(("linetype", op, name, options)) or 9,
|
||||||
|
layout_records=lambda: [{"name": n, "current": n == "Model"} for n in ("Model", "Sheet1")],
|
||||||
|
layout_operation=lambda op, name, options: self.calls.append(("layout", op, name, options)) or 9,
|
||||||
|
command_step=self._command_step,
|
||||||
|
curve_samples=lambda handle, n: {"vertices": [[0, 0], [1, 0], [2, 0]], "elevation": 5.0, "closed": False},
|
||||||
|
)
|
||||||
|
namespace = {"ocs": self.ocs}
|
||||||
|
exec(MODEL.read_text(), namespace)
|
||||||
|
self.doc = self.ocs.active_document
|
||||||
|
|
||||||
|
def _command_step(self, kind, options):
|
||||||
|
self.calls.append(("step", kind, options))
|
||||||
|
outcome = {"status": "completed", "blocked_by": None, "command": "", "prompt": "", "accepts": [],
|
||||||
|
"options": [], "entities": 0, "added": 0, "unconsumed": [], "error": None}
|
||||||
|
outcome.update(self.step_outcome.get(kind, {}))
|
||||||
|
if kind == "token" and options.get("text") == "X":
|
||||||
|
outcome["status"] = "completed"
|
||||||
|
if kind in ("enter", "entity"):
|
||||||
|
new = max(self.records) + 1
|
||||||
|
self.records[new] = {"handle": new, "kind": "Line", "layer": "0", "_editable": True}
|
||||||
|
return outcome
|
||||||
|
|
||||||
|
def test_command_runner(self):
|
||||||
|
self.step_outcome = {}
|
||||||
|
out = self.doc.command("CIRCLE 0,0 5")
|
||||||
|
self.assertEqual(self.calls[-1], ("step", "run", {"line": "CIRCLE 0,0 5"}))
|
||||||
|
self.assertEqual(out["status"], "completed")
|
||||||
|
self.step_outcome = {"run": {"status": "waiting_input", "prompt": "Select object"}}
|
||||||
|
with self.assertRaises(RuntimeError):
|
||||||
|
self.doc.command("OFFSET")
|
||||||
|
self.assertEqual(self.calls[-1], ("step", "cancel", None))
|
||||||
|
self.step_outcome = {"run": {"error": "bad"}}
|
||||||
|
with self.assertRaises(RuntimeError):
|
||||||
|
self.doc.command("X")
|
||||||
|
waiting = {"status": "waiting_input"}
|
||||||
|
self.step_outcome = {"start": waiting, "point": waiting, "entity": waiting}
|
||||||
|
with self.doc.start_command("OFFSET") as command:
|
||||||
|
command.point((1, 2))
|
||||||
|
self.assertEqual(self.calls[-1], ("step", "point", {"point": [1.0, 2.0, 0.0]}))
|
||||||
|
command.entity(self.doc.entities[1], at=(0, 0, 0))
|
||||||
|
self.assertEqual(self.calls[-1][2]["handle"], 1)
|
||||||
|
self.assertEqual(self.calls[-1], ("step", "cancel", None))
|
||||||
|
|
||||||
|
def test_modify_wrappers(self):
|
||||||
|
self.step_outcome = {}
|
||||||
|
self.doc.modify.trim(1, (3, 0, 0))
|
||||||
|
steps = [c for c in self.calls if c[0] == "step"]
|
||||||
|
self.assertEqual([c[1] for c in steps], ["start", "entity", "enter"])
|
||||||
|
self.calls.clear()
|
||||||
|
self.doc.modify.move([1, 2], (0, 0, 0), (5, 5, 0))
|
||||||
|
self.assertEqual(self.calls[0], ("selection", [1, 2]))
|
||||||
|
self.assertEqual([c[1] for c in self.calls if c[0] == "step"], ["start", "point", "point"])
|
||||||
|
self.calls.clear()
|
||||||
|
self.doc.modify.offset(1, 2, (0, 5))
|
||||||
|
entity_step = [c for c in self.calls if c[0] == "step" and c[1] == "entity"][0]
|
||||||
|
self.assertEqual(entity_step[2]["point"], [1, 0, 5.0])
|
||||||
|
|
||||||
|
def test_more_modify_wrappers(self):
|
||||||
|
self.step_outcome = {}
|
||||||
|
self.doc.modify.chamfer(1, 2, 2, 3, at1=(0, 0, 0), at2=(1, 1, 0))
|
||||||
|
texts = [c[2]["text"] for c in self.calls if c[0] == "step" and c[1] == "text"]
|
||||||
|
self.assertEqual(texts, ["2", "3"])
|
||||||
|
self.calls.clear()
|
||||||
|
self.doc.modify.chamfer(1, 2, 4, at1=(0, 0, 0), at2=(1, 1, 0))
|
||||||
|
texts = [c[2]["text"] for c in self.calls if c[0] == "step" and c[1] == "text"]
|
||||||
|
self.assertEqual(texts, ["4", "4"])
|
||||||
|
self.calls.clear()
|
||||||
|
self.doc.modify.array_rect([1], 2, 3, 10, 20)
|
||||||
|
self.assertEqual([c[2]["text"] for c in self.calls if c[0] == "step" and c[1] == "text"], ["2", "3", "10", "20"])
|
||||||
|
self.calls.clear()
|
||||||
|
self.doc.modify.stretch((0, 0), (1, 1), (0, 0), (5, 0))
|
||||||
|
self.assertEqual([c[1] for c in self.calls if c[0] == "step"], ["start", "point", "point", "enter", "point", "point"])
|
||||||
|
|
||||||
|
def test_pedit_and_array_wrappers(self):
|
||||||
|
self.step_outcome = {"start": {"status": "waiting_input"}, "entity": {"status": "waiting_input", "prompt": "Turn it into one? [Yes/No]"},
|
||||||
|
"token": {"status": "waiting_input"}}
|
||||||
|
self.doc.modify.polyline_close(1)
|
||||||
|
tokens = [c[2]["text"] for c in self.calls if c[0] == "step" and c[1] == "token"]
|
||||||
|
self.assertEqual(tokens, ["Y", "C", "X"])
|
||||||
|
self.calls.clear()
|
||||||
|
self.step_outcome = {}
|
||||||
|
self.doc.modify.array_3d([1], 2, 2, 2, 10, 20, 30)
|
||||||
|
self.assertEqual([c[2]["text"] for c in self.calls if c[0] == "step" and c[1] == "text"], ["2", "2", "2", "10", "20", "30"])
|
||||||
|
self.calls.clear()
|
||||||
|
self.doc.modify.array_path([1], 2, 5, at=(0, 0, 0))
|
||||||
|
self.assertEqual([c[1] for c in self.calls if c[0] == "step"], ["start", "entity", "text"])
|
||||||
|
|
||||||
|
def test_batch_edit_and_rollback(self):
|
||||||
|
line = self.doc.entities[1]
|
||||||
|
self.assertEqual(line.start, (1, 2, 3))
|
||||||
|
with self.doc.transaction("Move line"):
|
||||||
|
line.start = (0, 0, 0)
|
||||||
|
line.end = (10, 0, 0)
|
||||||
|
self.assertEqual(line.end, (10, 0, 0))
|
||||||
|
self.assertEqual(self.calls, [("Move line", [{"handle": 1,
|
||||||
|
"start": {"x": 0, "y": 0, "z": 0}, "end": {"x": 10, "y": 0, "z": 0}}])])
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
with self.doc.transaction("Abort"):
|
||||||
|
line.layer = "A"
|
||||||
|
raise ValueError()
|
||||||
|
self.assertEqual(len(self.calls), 1)
|
||||||
|
|
||||||
|
def test_layers_lookup_and_options(self):
|
||||||
|
layers = self.doc.layers
|
||||||
|
self.assertIn("WALLS", layers)
|
||||||
|
self.assertEqual(layers["walls"]["name"], "Walls")
|
||||||
|
self.assertEqual(layers.current["name"], "0")
|
||||||
|
self.assertEqual(layers.names(), ["0", "Walls"])
|
||||||
|
with self.assertRaises(KeyError):
|
||||||
|
layers["Nope"]
|
||||||
|
layers.modify("Walls", color=3, linetype=None, off=False)
|
||||||
|
self.assertEqual(self.calls[-1], ("modify", "Walls", {"color": 3, "off": False}))
|
||||||
|
layers.delete("Walls", erase_objects=1)
|
||||||
|
self.assertEqual(self.calls[-1], ("delete", "Walls", {"erase_objects": True}))
|
||||||
|
with self.assertRaises(TypeError):
|
||||||
|
layers.create("New", colour=1)
|
||||||
|
self.assertEqual(len(self.calls), 2)
|
||||||
|
|
||||||
|
def test_text_and_dim_styles(self):
|
||||||
|
text, dim = self.doc.text_styles, self.doc.dim_styles
|
||||||
|
self.assertEqual(text.current["name"], "Standard")
|
||||||
|
self.assertEqual(text["TITLE"]["name"], "Title")
|
||||||
|
text.create("Notes", height=2.5, font=None, oblique=10)
|
||||||
|
self.assertEqual(self.calls[-1], ("text", "create", "Notes", {"height": 2.5, "oblique": 10}))
|
||||||
|
with self.assertRaises(TypeError):
|
||||||
|
text.create("Bad", true_type_font="Arial")
|
||||||
|
with self.assertRaises(TypeError):
|
||||||
|
text.modify("Title", fnt="x")
|
||||||
|
dim.create("Metric", copy_from="Standard", dimscale=2)
|
||||||
|
self.assertEqual(self.calls[-1], ("dim", "create", "Metric", {"dimscale": 2, "copy_from": "Standard"}))
|
||||||
|
dim.modify("Standard", dimtxt=3)
|
||||||
|
self.assertEqual(self.calls[-1], ("dim", "modify", "Standard", {"dimtxt": 3}))
|
||||||
|
dim.delete("Metric")
|
||||||
|
self.assertEqual(self.calls[-1], ("dim", "delete", "Metric", None))
|
||||||
|
dim.set_current("Standard")
|
||||||
|
self.assertEqual(self.calls[-1], ("dim", "set_current", "Standard", None))
|
||||||
|
|
||||||
|
def test_create_entity_in_block(self):
|
||||||
|
self.doc.create_entity("Line", block="Widget", start={"x": 0, "y": 0, "z": 0}, end={"x": 1, "y": 0, "z": 0})
|
||||||
|
self.assertEqual(self.calls[-1][:2], ("add_to_block", "Widget"))
|
||||||
|
self.assertEqual(self.calls[-1][2]["kind"], "Line")
|
||||||
|
self.assertNotIn("block", self.calls[-1][2])
|
||||||
|
self.doc.create_entity("Line", start={"x": 0, "y": 0, "z": 0}, end={"x": 1, "y": 0, "z": 0})
|
||||||
|
self.assertEqual(self.calls[-1][0], "add")
|
||||||
|
|
||||||
|
def test_linetypes_and_layouts(self):
|
||||||
|
lt, ly = self.doc.linetypes, self.doc.layouts
|
||||||
|
self.assertIn("bracket", lt)
|
||||||
|
lt.create("Bracket", [12, -3], "test")
|
||||||
|
self.assertEqual(self.calls[-1], ("linetype", "create", "Bracket", {"pattern": [12.0, -3.0], "description": "test"}))
|
||||||
|
lt.modify("Bracket", pattern=[1, -1])
|
||||||
|
self.assertEqual(self.calls[-1], ("linetype", "modify", "Bracket", {"pattern": [1.0, -1.0]}))
|
||||||
|
lt.rename("Bracket", "Bracket")
|
||||||
|
lt.delete("Bracket")
|
||||||
|
self.assertEqual(self.calls[-1], ("linetype", "delete", "Bracket", None))
|
||||||
|
self.assertEqual(ly.current["name"], "Model")
|
||||||
|
ly.create("Sheet1")
|
||||||
|
ly.set_page("Sheet1", paper_size=(420, 297), rotation=0, scale=(1, 50))
|
||||||
|
self.assertEqual(self.calls[-1], ("layout", "set_page", "Sheet1",
|
||||||
|
{"paper_size": [420.0, 297.0], "rotation": 0, "scale": [1.0, 50.0]}))
|
||||||
|
ly.current = "Sheet1"
|
||||||
|
self.assertEqual(self.calls[-1], ("layout", "set_current", "Sheet1", None))
|
||||||
|
ly.delete("Sheet1")
|
||||||
|
self.assertEqual(self.calls[-1], ("layout", "delete", "Sheet1", None))
|
||||||
|
with self.assertRaises(KeyError):
|
||||||
|
ly["Nope"]
|
||||||
|
|
||||||
|
def test_blocks(self):
|
||||||
|
blocks = self.doc.blocks
|
||||||
|
self.assertIn("WIDGET", blocks)
|
||||||
|
self.assertEqual(blocks.names(), ["Widget", "Gadget"])
|
||||||
|
blocks.create("Gadget", [self.doc.entities[1], 2], base_point=(1, 2, 3), erase_originals=True)
|
||||||
|
self.assertEqual(self.calls[-1], ("block", "create", "Gadget",
|
||||||
|
{"entities": [1, 2], "base_point": [1.0, 2.0, 3.0], "erase_originals": True}))
|
||||||
|
blocks.modify("Widget", explodable=False)
|
||||||
|
self.assertEqual(self.calls[-1], ("block", "modify", "Widget", {"explodable": False}))
|
||||||
|
blocks.rename("Widget", "Gadget")
|
||||||
|
self.assertEqual(self.calls[-1], ("block", "rename", "Widget", {"to": "Gadget"}))
|
||||||
|
blocks.delete("Widget")
|
||||||
|
self.assertEqual(self.calls[-1], ("block", "delete", "Widget", None))
|
||||||
|
with self.assertRaises(KeyError):
|
||||||
|
blocks["Nope"]
|
||||||
|
|
||||||
|
def test_create_and_delete_use_document_model(self):
|
||||||
|
line = self.doc.create_entity("Line", start={"x": 0, "y": 0, "z": 0},
|
||||||
|
end={"x": 10, "y": 0, "z": 0})
|
||||||
|
self.assertEqual(line.handle, 1)
|
||||||
|
self.assertEqual(self.calls[-1], ("add", {"kind": "Line",
|
||||||
|
"start": {"x": 0, "y": 0, "z": 0}, "end": {"x": 10, "y": 0, "z": 0}}))
|
||||||
|
self.doc.delete_entity(line)
|
||||||
|
self.assertEqual(self.calls[-1], ("remove", 1))
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
self.doc.create_entity("Line", handle=4)
|
||||||
|
|
||||||
|
def test_create_entity_accepts_coordinate_tuples_for_point_properties(self):
|
||||||
|
self.ocs.entity_coverage = lambda kind: {"kind": kind, "scope": "canvas",
|
||||||
|
"editable": [], "readable": [], "unmapped": [], "properties": [
|
||||||
|
{"name": "start", "type": "Vector3", "sequence": False},
|
||||||
|
{"name": "end", "type": "Vector3", "sequence": False},
|
||||||
|
{"name": "corners", "type": "Vector2", "sequence": True},
|
||||||
|
{"name": "knots", "type": "f64", "sequence": True}]}
|
||||||
|
self.doc.create_entity("Line", start=(0, 0, 0), end=(10, 5, 0),
|
||||||
|
corners=[(1, 2), (3, 4)], knots=[0, 0, 1])
|
||||||
|
self.assertEqual(self.calls[-1], ("add", {"kind": "Line",
|
||||||
|
"start": {"x": 0.0, "y": 0.0, "z": 0.0}, "end": {"x": 10.0, "y": 5.0, "z": 0.0},
|
||||||
|
"corners": [{"x": 1.0, "y": 2.0}, {"x": 3.0, "y": 4.0}],
|
||||||
|
"knots": [0, 0, 1]}))
|
||||||
|
|
||||||
|
def test_coverage_and_read_only_entity(self):
|
||||||
|
self.assertEqual(len(self.doc.entities), 2)
|
||||||
|
self.assertEqual([entity.handle for entity in self.doc.entities], [1, 2])
|
||||||
|
self.assertIn("start", self.doc.entities[1].coverage["editable"])
|
||||||
|
self.assertEqual(self.doc.entities[2].coverage["editable"], ["layer"])
|
||||||
|
self.assertEqual(set(self.doc.coverage()), {"Line", "Hatch"})
|
||||||
|
self.assertEqual(self.doc.coverage("Hatch")["editable"], ["layer"])
|
||||||
|
snapshot = self.doc.entities[2].snapshot
|
||||||
|
self.assertEqual(snapshot["pattern_name"], "SOLID")
|
||||||
|
snapshot["pattern_name"] = "OTHER"
|
||||||
|
self.assertEqual(self.doc.entities[2].snapshot["pattern_name"], "SOLID")
|
||||||
|
with self.doc.transaction("Move hatch"):
|
||||||
|
self.doc.entities[2].layer = "HATCHES"
|
||||||
|
self.assertEqual(self.calls[-1], ("Move hatch", [{"handle": 2, "layer": "HATCHES"}]))
|
||||||
|
with self.doc.transaction("Unsupported geometry"):
|
||||||
|
with self.assertRaises(AttributeError):
|
||||||
|
self.doc.entities[2].pattern_name = "OTHER"
|
||||||
|
|
||||||
|
def test_rejected_host_transaction_leaves_python_model_ready(self):
|
||||||
|
def reject(label, updates):
|
||||||
|
raise ValueError("Line.start must contain finite coordinates")
|
||||||
|
self.ocs.update_many = reject
|
||||||
|
with self.assertRaisesRegex(ValueError, "finite coordinates"):
|
||||||
|
with self.doc.transaction("Invalid"):
|
||||||
|
self.doc.entities[1].start = (float("nan"), 0, 0)
|
||||||
|
self.assertIsNone(self.doc._pending)
|
||||||
|
self.assertEqual(self.doc.entities[1].start, (1, 2, 3))
|
||||||
|
|
||||||
|
def test_readable_insert_identity_cannot_be_patched(self):
|
||||||
|
self.records[3] = {"handle": 3, "kind": "Insert", "layer": "0",
|
||||||
|
"block_name": "DOOR", "insert_point": {"x": 1, "y": 2, "z": 0},
|
||||||
|
"_editable": True}
|
||||||
|
old_coverage = self.ocs.entity_coverage
|
||||||
|
self.ocs.entity_coverage = lambda kind: (
|
||||||
|
{"kind": "Insert", "scope": "canvas", "editable": ["layer", "insert_point"],
|
||||||
|
"readable": ["kind", "handle", "layer", "block_name", "insert_point"],
|
||||||
|
"unmapped": []} if kind == "Insert" else old_coverage(kind))
|
||||||
|
insert = self.doc.entities[3]
|
||||||
|
self.assertEqual(insert.block_name, "DOOR")
|
||||||
|
with self.doc.transaction("Move block"):
|
||||||
|
with self.assertRaises(AttributeError):
|
||||||
|
insert.block_name = "WINDOW"
|
||||||
|
insert.insert_point = (4, 5, 0)
|
||||||
|
self.assertEqual(self.calls[-1], ("Move block", [{"handle": 3,
|
||||||
|
"insert_point": {"x": 4, "y": 5, "z": 0}}]))
|
||||||
|
|
||||||
|
def test_selection_events_and_input(self):
|
||||||
|
self.assertEqual([entity.handle for entity in self.doc.selection], [1])
|
||||||
|
self.doc.selection = [self.doc.entities[1]]
|
||||||
|
self.assertEqual(self.calls[-1], ("selection", [1]))
|
||||||
|
self.assertEqual(self.doc.poll_events(), [{"type": "drawing", "tab_id": 7}])
|
||||||
|
self.assertEqual(self.doc.request_entity("Pick"), ("Pick", True))
|
||||||
|
self.assertEqual(self.doc.poll_input(10)["status"], "point")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
+75
@@ -0,0 +1,75 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Build the in-tree API v7 Python plugin and stage a complete plugin package.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
if [[ $# -lt 1 ]]; then
|
||||||
|
echo "usage: $0 <stage directory> [--debug] [--target <triple>]" >&2
|
||||||
|
exit 2
|
||||||
|
fi
|
||||||
|
|
||||||
|
stage_dir=$(python3 -c 'import os,sys; print(os.path.abspath(sys.argv[1]))' "$1")
|
||||||
|
shift
|
||||||
|
profile=release
|
||||||
|
target=""
|
||||||
|
while [[ $# -gt 0 ]]; do
|
||||||
|
case "$1" in
|
||||||
|
--debug) profile=debug; shift ;;
|
||||||
|
--target)
|
||||||
|
[[ $# -ge 2 ]] || { echo "--target requires a triple" >&2; exit 2; }
|
||||||
|
target=$2
|
||||||
|
shift 2
|
||||||
|
;;
|
||||||
|
*) echo "unknown option: $1" >&2; exit 2 ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
plugin_dir=$(cd "$(dirname "$0")/.." && pwd)
|
||||||
|
ocs_repo=$(cd "$plugin_dir/../.." && pwd)
|
||||||
|
cd "$plugin_dir"
|
||||||
|
|
||||||
|
build_args=(build --locked --features experimental-host-model)
|
||||||
|
[[ $profile == release ]] && build_args+=(--release)
|
||||||
|
[[ -n $target ]] && build_args+=(--target "$target")
|
||||||
|
cargo "${build_args[@]}"
|
||||||
|
|
||||||
|
case "$(uname -s)" in
|
||||||
|
Darwin) library="libopencad_python.dylib" ;;
|
||||||
|
Linux) library="libopencad_python.so" ;;
|
||||||
|
MINGW*|MSYS*|CYGWIN*) library="opencad_python.dll" ;;
|
||||||
|
*) echo "unsupported platform" >&2; exit 2 ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
target_dir="$plugin_dir/target"
|
||||||
|
[[ -n $target ]] && target_dir="$target_dir/$target"
|
||||||
|
source_library="$target_dir/$profile/$library"
|
||||||
|
[[ -f $source_library ]] || { echo "build did not produce $source_library" >&2; exit 1; }
|
||||||
|
|
||||||
|
mkdir -p "$stage_dir"
|
||||||
|
cp "$source_library" "$stage_dir/$library"
|
||||||
|
python3 - "$stage_dir/plugin.toml" "$(rustc --version)" "$ocs_repo/Cargo.lock" <<'PY'
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
|
||||||
|
def acadrust_source(path):
|
||||||
|
packages = re.findall(r"(?ms)^\[\[package\]\]\n(.*?)(?=^\[\[package\]\]|\Z)", Path(path).read_text())
|
||||||
|
sources = []
|
||||||
|
for package in packages:
|
||||||
|
if re.search(r'^name = "acadrust"$', package, re.M):
|
||||||
|
match = re.search(r'^source = "([^"]+)"$', package, re.M)
|
||||||
|
if match:
|
||||||
|
sources.append(match.group(1))
|
||||||
|
if len(sources) != 1:
|
||||||
|
raise SystemExit(f"expected one acadrust source in {path}, found {len(sources)}")
|
||||||
|
return sources[0]
|
||||||
|
|
||||||
|
manifest = Path("plugin.toml").read_text()
|
||||||
|
if "api_version = 7" not in manifest:
|
||||||
|
raise SystemExit("bundled plugin.toml must target API v7")
|
||||||
|
manifest = manifest.replace("__RUSTC_VERSION__", sys.argv[2])
|
||||||
|
manifest = manifest.replace("__ACADRUST_SOURCE__", acadrust_source(sys.argv[3]))
|
||||||
|
if "__" in manifest:
|
||||||
|
raise SystemExit("unresolved manifest placeholder")
|
||||||
|
Path(sys.argv[1]).write_text(manifest)
|
||||||
|
PY
|
||||||
|
echo "Staged bundled API v7 plugin in $stage_dir"
|
||||||
@@ -283,6 +283,8 @@ impl OpenCADStudio {
|
|||||||
// selection check has to run on this path too.
|
// selection check has to run on this path too.
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
self.notify_plugins_selection_changed();
|
self.notify_plugins_selection_changed();
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
self.notify_plugins_document_changed();
|
||||||
res
|
res
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -767,6 +769,46 @@ impl OpenCADStudio {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
#[test]
|
||||||
|
fn clayer_command_sets_layer_used_by_new_geometry() {
|
||||||
|
let mut app = super::OpenCADStudio::new_for_test();
|
||||||
|
app.automation_op(r#"{"op":"new"}"#);
|
||||||
|
app.automation_op(r#"{"op":"run","cmd":"LAYER NEW Annotations"}"#);
|
||||||
|
app.automation_op(r#"{"op":"run","cmd":"CLAYER Annotations"}"#);
|
||||||
|
app.automation_op(r#"{"op":"run","cmd":"LINE 0,0 10,0"}"#);
|
||||||
|
let lines = app.automation_op(r#"{"op":"query","type":"Line"}"#);
|
||||||
|
assert_eq!(lines["entities"][0]["layer"], "Annotations");
|
||||||
|
}
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
#[test]
|
||||||
|
fn built_in_edits_advance_plugin_document_fingerprint_once() {
|
||||||
|
let mut app = super::OpenCADStudio::new_for_test();
|
||||||
|
app.automation_op(r#"{"op":"new"}"#);
|
||||||
|
let before = app.last_plugin_document.expect("new drawing published");
|
||||||
|
app.automation_op(r#"{"op":"run","cmd":"LINE 0,0 10,0"}"#);
|
||||||
|
let after = app.last_plugin_document.expect("line edit published");
|
||||||
|
assert_eq!(after.0, app.tabs[app.active_tab].id);
|
||||||
|
assert_ne!(after, before);
|
||||||
|
assert_eq!(after.1, app.tabs[app.active_tab].scene.geometry_epoch);
|
||||||
|
app.automation_op(r#"{"op":"query","type":"Line"}"#);
|
||||||
|
assert_eq!(app.last_plugin_document, Some(after));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
#[test]
|
||||||
|
fn plugin_edit_publication_is_not_repeated_at_message_boundary() {
|
||||||
|
use acadrust::entities::Point;
|
||||||
|
use acadrust::EntityType;
|
||||||
|
|
||||||
|
let mut app = super::OpenCADStudio::new_for_test();
|
||||||
|
app.automation_op(r#"{"op":"new"}"#);
|
||||||
|
let tab = app.active_tab;
|
||||||
|
let mut host = super::super::plugin_host::HostSession::new(&mut app, tab);
|
||||||
|
host.add_entity(EntityType::Point(Point::new()));
|
||||||
|
let published = app.last_plugin_document.expect("plugin write published");
|
||||||
|
app.notify_plugins_document_changed();
|
||||||
|
assert_eq!(app.last_plugin_document, Some(published));
|
||||||
|
}
|
||||||
use crate::app::OpenCADStudio;
|
use crate::app::OpenCADStudio;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -2745,21 +2745,7 @@ impl OpenCADStudio {
|
|||||||
self.command_line
|
self.command_line
|
||||||
.push_output(crate::tf!("CLAYER = \"{cur}\"").as_ref());
|
.push_output(crate::tf!("CLAYER = \"{cur}\"").as_ref());
|
||||||
} else {
|
} else {
|
||||||
if self.tabs[i].scene.document.layers.contains(name_arg) {
|
if self.set_current_layer_name(i, name_arg).is_ok() {
|
||||||
let handle = self.tabs[i]
|
|
||||||
.scene
|
|
||||||
.document
|
|
||||||
.layers
|
|
||||||
.get(name_arg)
|
|
||||||
.map(|l| l.handle)
|
|
||||||
.unwrap_or(acadrust::types::Handle::NULL);
|
|
||||||
self.tabs[i].scene.document.header.current_layer_name =
|
|
||||||
name_arg.to_string();
|
|
||||||
self.tabs[i].scene.document.header.current_layer_handle = handle;
|
|
||||||
self.tabs[i].active_layer = name_arg.to_string();
|
|
||||||
self.tabs[i].layers.current_layer = name_arg.to_string();
|
|
||||||
self.ribbon.active_layer = name_arg.to_string();
|
|
||||||
self.tabs[i].dirty = true;
|
|
||||||
self.command_line
|
self.command_line
|
||||||
.push_output(crate::tf!("CLAYER set to \"{name_arg}\"").as_ref());
|
.push_output(crate::tf!("CLAYER set to \"{name_arg}\"").as_ref());
|
||||||
} else {
|
} else {
|
||||||
@@ -2944,6 +2930,29 @@ impl OpenCADStudio {
|
|||||||
_ => self.command_line.push_error(crate::t!("Requires 0 or 1").as_ref()),
|
_ => self.command_line.push_error(crate::t!("Requires 0 or 1").as_ref()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
cmd if cmd == "SCRIPTCOMMANDS" || cmd.starts_with("SCRIPTCOMMANDS ") => {
|
||||||
|
// A user setting, deliberately outside the script's reach: it is refused by
|
||||||
|
// the script command runner, so only the command line can change it.
|
||||||
|
let arg = cmd.trim_start_matches("SCRIPTCOMMANDS").trim();
|
||||||
|
match arg {
|
||||||
|
"" => {}
|
||||||
|
"1" | "ON" | "YES" => self.script_commands = true,
|
||||||
|
"0" | "OFF" | "NO" => self.script_commands = false,
|
||||||
|
_ => {
|
||||||
|
self.command_line.push_error(
|
||||||
|
crate::t!("SCRIPTCOMMANDS takes 1 (scripts may run commands) or 0 (they may not)")
|
||||||
|
.as_ref(),
|
||||||
|
);
|
||||||
|
return Some(Task::none());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !arg.is_empty() {
|
||||||
|
self.persist_settings_if_changed();
|
||||||
|
}
|
||||||
|
let state = if self.script_commands { 1 } else { 0 };
|
||||||
|
self.command_line
|
||||||
|
.push_output(crate::tf!("SCRIPTCOMMANDS = {state}").as_ref());
|
||||||
|
}
|
||||||
"SAVETIME" => {
|
"SAVETIME" => {
|
||||||
use crate::command::ValuePromptCommand;
|
use crate::command::ValuePromptCommand;
|
||||||
let c = ValuePromptCommand::new(
|
let c = ValuePromptCommand::new(
|
||||||
|
|||||||
@@ -314,7 +314,7 @@ fn command_selection_policy(name: &str) -> &'static str {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn active_command_metadata(command: &dyn crate::command::CadCommand) -> Value {
|
pub(super) fn active_command_metadata(command: &dyn crate::command::CadCommand) -> Value {
|
||||||
let options = command.options();
|
let options = command.options();
|
||||||
let mut accepts = Vec::new();
|
let mut accepts = Vec::new();
|
||||||
if command.is_selection_gathering() {
|
if command.is_selection_gathering() {
|
||||||
|
|||||||
@@ -2,6 +2,27 @@ use super::OpenCADStudio;
|
|||||||
use crate::ui;
|
use crate::ui;
|
||||||
|
|
||||||
impl OpenCADStudio {
|
impl OpenCADStudio {
|
||||||
|
/// Apply the current layer to the document header and all per-tab/UI
|
||||||
|
/// creation state. Both built-in commands and plugin settings use this.
|
||||||
|
pub(super) fn set_current_layer_name(&mut self, tab: usize, layer: &str) -> Result<(), String> {
|
||||||
|
let handle = self.tabs[tab]
|
||||||
|
.scene
|
||||||
|
.document
|
||||||
|
.layers
|
||||||
|
.get(layer)
|
||||||
|
.map(|entry| entry.handle)
|
||||||
|
.ok_or_else(|| format!("layer {layer:?} does not exist"))?;
|
||||||
|
self.tabs[tab].scene.document.header.current_layer_name = layer.to_owned();
|
||||||
|
self.tabs[tab].scene.document.header.current_layer_handle = handle;
|
||||||
|
self.tabs[tab].active_layer = layer.to_owned();
|
||||||
|
self.tabs[tab].layers.current_layer = layer.to_owned();
|
||||||
|
self.tabs[tab].dirty = true;
|
||||||
|
if tab == self.active_tab {
|
||||||
|
self.ribbon.active_layer = layer.to_owned();
|
||||||
|
self.refresh_layer_panel();
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
pub(super) fn load_layer_state_editor(&mut self, selected: Option<String>) {
|
pub(super) fn load_layer_state_editor(&mut self, selected: Option<String>) {
|
||||||
let i = self.active_tab;
|
let i = self.active_tab;
|
||||||
if let Some(name) = selected {
|
if let Some(name) = selected {
|
||||||
|
|||||||
+11
-1
@@ -35,7 +35,7 @@ mod record_api;
|
|||||||
pub(crate) mod settings;
|
pub(crate) mod settings;
|
||||||
mod shortcuts;
|
mod shortcuts;
|
||||||
mod startup;
|
mod startup;
|
||||||
mod style_ops;
|
pub(crate) mod style_ops;
|
||||||
mod text_inline;
|
mod text_inline;
|
||||||
mod tolerance_dialog;
|
mod tolerance_dialog;
|
||||||
mod update;
|
mod update;
|
||||||
@@ -634,6 +634,8 @@ pub(super) struct OpenCADStudio {
|
|||||||
/// Minutes between autosaves to a `.sv$` recovery file (SAVETIME command);
|
/// Minutes between autosaves to a `.sv$` recovery file (SAVETIME command);
|
||||||
/// 0 disables autosave.
|
/// 0 disables autosave.
|
||||||
pub savetime_min: i32,
|
pub savetime_min: i32,
|
||||||
|
/// SCRIPTCOMMANDS: scripts may run OCS commands (see `UserSettings`).
|
||||||
|
pub script_commands: bool,
|
||||||
/// Persisted default viewport background, restored from settings and applied
|
/// Persisted default viewport background, restored from settings and applied
|
||||||
/// to every drawing tab (new and opened) so a chosen background survives
|
/// to every drawing tab (new and opened) so a chosen background survives
|
||||||
/// restarts (#188). `None` = the built-in dark-grey / off-white defaults.
|
/// restarts (#188). `None` = the built-in dark-grey / off-white defaults.
|
||||||
@@ -904,6 +906,11 @@ pub(super) struct OpenCADStudio {
|
|||||||
/// `SelectionChangedV4` fires once per real change rather than per message.
|
/// `SelectionChangedV4` fires once per real change rather than per message.
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
last_plugin_selection: Option<(u64, u64)>,
|
last_plugin_selection: Option<(u64, u64)>,
|
||||||
|
/// `(tab id, geometry epoch)` last published to the V4 document view.
|
||||||
|
/// Built-in edits bypass HostSession, so this is checked at message
|
||||||
|
/// boundaries as well as after plugin-initiated writes.
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
last_plugin_document: Option<(u64, u64)>,
|
||||||
/// External add-on packages found in the plugins folder, refreshed when the
|
/// External add-on packages found in the plugins folder, refreshed when the
|
||||||
/// Plugin Manager opens.
|
/// Plugin Manager opens.
|
||||||
external_plugins: Vec<crate::plugin::external::ExternalPlugin>,
|
external_plugins: Vec<crate::plugin::external::ExternalPlugin>,
|
||||||
@@ -4000,6 +4007,7 @@ impl OpenCADStudio {
|
|||||||
suppress_plugin_dispatch: false,
|
suppress_plugin_dispatch: false,
|
||||||
constraint_bar_mode: 4095,
|
constraint_bar_mode: 4095,
|
||||||
savetime_min: 10,
|
savetime_min: 10,
|
||||||
|
script_commands: true,
|
||||||
default_bg_color: None,
|
default_bg_color: None,
|
||||||
default_paper_bg_color: None,
|
default_paper_bg_color: None,
|
||||||
cliprompt_lines: 3,
|
cliprompt_lines: 3,
|
||||||
@@ -4101,6 +4109,8 @@ impl OpenCADStudio {
|
|||||||
disabled_plugins: rustc_hash::FxHashSet::default(),
|
disabled_plugins: rustc_hash::FxHashSet::default(),
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
last_plugin_selection: None,
|
last_plugin_selection: None,
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
last_plugin_document: None,
|
||||||
external_plugins: Vec::new(),
|
external_plugins: Vec::new(),
|
||||||
loaded_plugin_ids: rustc_hash::FxHashSet::default(),
|
loaded_plugin_ids: rustc_hash::FxHashSet::default(),
|
||||||
plugin_load_errors: rustc_hash::FxHashMap::default(),
|
plugin_load_errors: rustc_hash::FxHashMap::default(),
|
||||||
|
|||||||
+8336
-22
File diff suppressed because it is too large.
Load diff
@@ -485,6 +485,10 @@ pub struct UserSettings {
|
|||||||
/// Minutes between autosaves to a `.sv$` recovery file (SAVETIME command).
|
/// Minutes between autosaves to a `.sv$` recovery file (SAVETIME command).
|
||||||
/// 0 disables autosave.
|
/// 0 disables autosave.
|
||||||
pub savetime_min: i32,
|
pub savetime_min: i32,
|
||||||
|
/// SCRIPTCOMMANDS: whether a script (the Python plugin) may run OCS commands
|
||||||
|
/// through the host. On by default; a user turns it off with the
|
||||||
|
/// `SCRIPTCOMMANDS 0` command, and a script cannot change it.
|
||||||
|
pub script_commands: bool,
|
||||||
/// File type and version used when a new/unsaved drawing is first saved.
|
/// File type and version used when a new/unsaved drawing is first saved.
|
||||||
/// Existing drawings keep their own type and version.
|
/// Existing drawings keep their own type and version.
|
||||||
pub default_save_format: String,
|
pub default_save_format: String,
|
||||||
@@ -685,6 +689,7 @@ impl Default for UserSettings {
|
|||||||
constraint_bar_display: 3,
|
constraint_bar_display: 3,
|
||||||
constraint_bar_mode: 4095,
|
constraint_bar_mode: 4095,
|
||||||
savetime_min: 10,
|
savetime_min: 10,
|
||||||
|
script_commands: true,
|
||||||
default_save_format: crate::io::DEFAULT_SAVE_FORMAT.to_string(),
|
default_save_format: crate::io::DEFAULT_SAVE_FORMAT.to_string(),
|
||||||
pick_add: true,
|
pick_add: true,
|
||||||
pick_drag_rect: false,
|
pick_drag_rect: false,
|
||||||
@@ -798,6 +803,19 @@ mod tests {
|
|||||||
assert_eq!(cfg.settings.savetime_min, 42);
|
assert_eq!(cfg.settings.savetime_min, 42);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn script_commands_default_on_and_survive_a_round_trip() {
|
||||||
|
let missing: crate::app::config::AppConfig =
|
||||||
|
serde_json::from_str(r#"{"settings": {"pick_add": false}}"#).unwrap();
|
||||||
|
assert!(missing.settings.script_commands, "an old config keeps scripts allowed");
|
||||||
|
let off: crate::app::config::AppConfig =
|
||||||
|
serde_json::from_str(r#"{"settings": {"script_commands": false}}"#).unwrap();
|
||||||
|
assert!(!off.settings.script_commands);
|
||||||
|
let text = serde_json::to_string(&off).unwrap();
|
||||||
|
let back: crate::app::config::AppConfig = serde_json::from_str(&text).unwrap();
|
||||||
|
assert!(!back.settings.script_commands);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn isometric_drafting_never_persists_or_loads() {
|
fn isometric_drafting_never_persists_or_loads() {
|
||||||
// A persisted On used to bring the isoplane crosshair (vertical +
|
// A persisted On used to bring the isoplane crosshair (vertical +
|
||||||
|
|||||||
@@ -271,7 +271,7 @@ impl OpenCADStudio {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn style_exists(&self, kind: StyleKind, name: &str) -> bool {
|
pub(super) fn style_exists(&self, kind: StyleKind, name: &str) -> bool {
|
||||||
self.style_names(kind)
|
self.style_names(kind)
|
||||||
.iter()
|
.iter()
|
||||||
.any(|n| n.eq_ignore_ascii_case(name))
|
.any(|n| n.eq_ignore_ascii_case(name))
|
||||||
@@ -308,7 +308,7 @@ impl OpenCADStudio {
|
|||||||
|
|
||||||
/// Refresh anything that mirrors the style list / current style after a
|
/// Refresh anything that mirrors the style list / current style after a
|
||||||
/// mutation (ribbon dropdowns, geometry that depends on the style).
|
/// mutation (ribbon dropdowns, geometry that depends on the style).
|
||||||
fn after_style_change(&mut self, kind: StyleKind) {
|
pub(super) fn after_style_change(&mut self, kind: StyleKind) {
|
||||||
if kind.in_ribbon() {
|
if kind.in_ribbon() {
|
||||||
self.sync_ribbon_styles();
|
self.sync_ribbon_styles();
|
||||||
}
|
}
|
||||||
@@ -405,7 +405,7 @@ impl OpenCADStudio {
|
|||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
|
||||||
fn remove_style_storage(&mut self, kind: StyleKind, name: &str) -> bool {
|
pub(super) fn remove_style_storage(&mut self, kind: StyleKind, name: &str) -> bool {
|
||||||
let doc = &mut self.tabs[self.active_tab].scene.document;
|
let doc = &mut self.tabs[self.active_tab].scene.document;
|
||||||
match kind {
|
match kind {
|
||||||
StyleKind::Text => doc.text_styles.remove(name).is_some(),
|
StyleKind::Text => doc.text_styles.remove(name).is_some(),
|
||||||
@@ -541,7 +541,7 @@ impl OpenCADStudio {
|
|||||||
|
|
||||||
/// Rename `old`→`new` in the backing store, re-keying table entries and
|
/// Rename `old`→`new` in the backing store, re-keying table entries and
|
||||||
/// rewriting name-based references + current-style pointers.
|
/// rewriting name-based references + current-style pointers.
|
||||||
fn rename_style_storage(&mut self, kind: StyleKind, old: &str, new: &str) {
|
pub(super) fn rename_style_storage(&mut self, kind: StyleKind, old: &str, new: &str) {
|
||||||
let i = self.active_tab;
|
let i = self.active_tab;
|
||||||
match kind {
|
match kind {
|
||||||
StyleKind::Text => {
|
StyleKind::Text => {
|
||||||
|
|||||||
@@ -619,6 +619,7 @@ impl OpenCADStudio {
|
|||||||
constraint_bar_display: self.constraint_bar_display,
|
constraint_bar_display: self.constraint_bar_display,
|
||||||
constraint_bar_mode: self.constraint_bar_mode,
|
constraint_bar_mode: self.constraint_bar_mode,
|
||||||
savetime_min: self.savetime_min,
|
savetime_min: self.savetime_min,
|
||||||
|
script_commands: self.script_commands,
|
||||||
default_save_format: self.default_save_format.clone(),
|
default_save_format: self.default_save_format.clone(),
|
||||||
pick_add: self.pick_add,
|
pick_add: self.pick_add,
|
||||||
pick_drag_rect: self.pick_drag_rect,
|
pick_drag_rect: self.pick_drag_rect,
|
||||||
@@ -723,6 +724,7 @@ impl OpenCADStudio {
|
|||||||
self.constraint_bar_display = s.constraint_bar_display.clamp(0, 3);
|
self.constraint_bar_display = s.constraint_bar_display.clamp(0, 3);
|
||||||
self.constraint_bar_mode = s.constraint_bar_mode.clamp(0, 4095);
|
self.constraint_bar_mode = s.constraint_bar_mode.clamp(0, 4095);
|
||||||
self.savetime_min = s.savetime_min;
|
self.savetime_min = s.savetime_min;
|
||||||
|
self.script_commands = s.script_commands;
|
||||||
self.default_save_format =
|
self.default_save_format =
|
||||||
crate::io::canonical_save_format(&s.default_save_format).to_string();
|
crate::io::canonical_save_format(&s.default_save_format).to_string();
|
||||||
self.pick_add = s.pick_add;
|
self.pick_add = s.pick_add;
|
||||||
|
|||||||
@@ -284,6 +284,24 @@ impl OpenCADStudio {
|
|||||||
crate::plugin::v4_support::publish_selection_changed_v4(tab_id, handles);
|
crate::plugin::v4_support::publish_selection_changed_v4(tab_id, handles);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Refresh the shared V4 document after built-in geometry edits. Plugin
|
||||||
|
/// writes publish through HostSession immediately; the fingerprint avoids
|
||||||
|
/// sending a duplicate notification at this message boundary.
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
pub(super) fn notify_plugins_document_changed(&mut self) {
|
||||||
|
if self.active_tab >= self.tabs.len() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let tab = &self.tabs[self.active_tab];
|
||||||
|
let key = (tab.id, tab.scene.geometry_epoch);
|
||||||
|
if self.last_plugin_document == Some(key) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.last_plugin_document = Some(key);
|
||||||
|
crate::plugin::v4_support::publish_drawing_changed(tab.id, tab.scene.geometry_epoch);
|
||||||
|
crate::plugin::v4_support::publish_document_view_v4(tab.id, &tab.scene.document);
|
||||||
|
}
|
||||||
|
|
||||||
pub fn update(&mut self, msg: Message) -> Task<Message> {
|
pub fn update(&mut self, msg: Message) -> Task<Message> {
|
||||||
if let Some(tab) = self.tabs.get(self.active_tab) {
|
if let Some(tab) = self.tabs.get(self.active_tab) {
|
||||||
crate::entities::common::set_unit_context(
|
crate::entities::common::set_unit_context(
|
||||||
@@ -355,7 +373,29 @@ impl OpenCADStudio {
|
|||||||
return task;
|
return task;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// A command's name is `&'static str`, so this runs on every message —
|
||||||
|
// a mouse move included — without allocating.
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
let active_command = |app: &Self| -> Option<(u64, Option<&'static str>)> {
|
||||||
|
app.tabs
|
||||||
|
.get(app.active_tab)
|
||||||
|
.map(|tab| (tab.id, tab.active_cmd.as_ref().map(|command| command.name())))
|
||||||
|
};
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
let command_before = active_command(self);
|
||||||
let task = self.update_inner(msg);
|
let task = self.update_inner(msg);
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
{
|
||||||
|
let command_after = active_command(self);
|
||||||
|
if command_before != command_after {
|
||||||
|
if let Some((tab_id, command)) = command_after {
|
||||||
|
crate::plugin::v4_support::publish_command_state_changed(
|
||||||
|
tab_id,
|
||||||
|
command.map(str::to_owned),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
self.refresh_gpu_status();
|
self.refresh_gpu_status();
|
||||||
self.show_next_startup_modal();
|
self.show_next_startup_modal();
|
||||||
self.sync_open_command_history();
|
self.sync_open_command_history();
|
||||||
@@ -389,6 +429,8 @@ impl OpenCADStudio {
|
|||||||
// and plugin request draining).
|
// and plugin request draining).
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
self.notify_plugins_selection_changed();
|
self.notify_plugins_selection_changed();
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
self.notify_plugins_document_changed();
|
||||||
// OTRACK acquires tracking points only while a command or grip drag is
|
// OTRACK acquires tracking points only while a command or grip drag is
|
||||||
// running; drop them once neither is active so the temporary tracking
|
// running; drop them once neither is active so the temporary tracking
|
||||||
// points / vectors disappear when the command ends (issue #64).
|
// points / vectors disappear when the command ends (issue #64).
|
||||||
|
|||||||
@@ -25,6 +25,14 @@ pub(crate) fn set_dimension_text_override(base: &mut DimensionBase, text: Option
|
|||||||
base.user_text = text;
|
base.user_text = text;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Recompute the fields a script cannot set: the base definition point and
|
||||||
|
/// the stored measurement, exactly as grip edits do.
|
||||||
|
pub(crate) fn normalize_scripted_dimension(dim: &mut Dimension) {
|
||||||
|
let definition_point = dimension_definition_point(dim);
|
||||||
|
dim.base_mut().definition_point = definition_point;
|
||||||
|
dim.base_mut().actual_measurement = dim.measurement();
|
||||||
|
}
|
||||||
|
|
||||||
fn dimension_definition_point(dim: &Dimension) -> acadrust::types::Vector3 {
|
fn dimension_definition_point(dim: &Dimension) -> acadrust::types::Vector3 {
|
||||||
match dim {
|
match dim {
|
||||||
Dimension::Aligned(d) => d.definition_point,
|
Dimension::Aligned(d) => d.definition_point,
|
||||||
|
|||||||
@@ -602,3 +602,28 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Rebuild the derived spline after a scripted create or edit of the
|
||||||
|
/// generating parameters. `radius` is the top radius; the base radius is the
|
||||||
|
/// start point's distance from the axis.
|
||||||
|
pub(crate) fn normalize_scripted_helix(old: Option<&Helix>, new: &mut Helix) -> Result<(), String> {
|
||||||
|
let unchanged = old.is_some_and(|old| {
|
||||||
|
old.axis_base_point == new.axis_base_point
|
||||||
|
&& old.start_point == new.start_point
|
||||||
|
&& old.axis_vector == new.axis_vector
|
||||||
|
&& old.radius.to_bits() == new.radius.to_bits()
|
||||||
|
&& old.turns.to_bits() == new.turns.to_bits()
|
||||||
|
&& old.turn_height.to_bits() == new.turn_height.to_bits()
|
||||||
|
&& old.handedness == new.handedness
|
||||||
|
&& old.constraint == new.constraint
|
||||||
|
});
|
||||||
|
if unchanged {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let top = new.radius;
|
||||||
|
if rebuild(new, top) {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err("Helix parameters do not define a valid curve".into())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -418,6 +418,54 @@ fn restore_shifted_mline_segment(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Recompute the derived MLine state after a scripted create or edit:
|
||||||
|
/// vertex direction/miter, element segment layout and the per-element miter
|
||||||
|
/// offsets. Dash/cut parameters survive an edit unless a vertex moved.
|
||||||
|
pub(crate) fn normalize_scripted_mline(
|
||||||
|
old: Option<&MLine>,
|
||||||
|
new: &mut MLine,
|
||||||
|
document: &acadrust::CadDocument,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let style = resolved_mline_style(new, document)
|
||||||
|
.ok_or_else(|| format!("MLine style {:?} does not exist", new.style_name))?;
|
||||||
|
let unchanged = old.is_some_and(|old| {
|
||||||
|
old.vertices == new.vertices
|
||||||
|
&& old.normal == new.normal
|
||||||
|
&& old.flags == new.flags
|
||||||
|
&& old.justification == new.justification
|
||||||
|
&& old.scale_factor.to_bits() == new.scale_factor.to_bits()
|
||||||
|
&& old.style_name == new.style_name
|
||||||
|
&& old.style_handle == new.style_handle
|
||||||
|
});
|
||||||
|
if unchanged {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let moved = old.is_none_or(|old| {
|
||||||
|
old.vertices.len() != new.vertices.len()
|
||||||
|
|| old
|
||||||
|
.vertices
|
||||||
|
.iter()
|
||||||
|
.zip(&new.vertices)
|
||||||
|
.any(|(a, b)| a.position != b.position)
|
||||||
|
});
|
||||||
|
let elements = style.elements.len().max(1);
|
||||||
|
for vertex in &mut new.vertices {
|
||||||
|
if vertex.segments.is_empty() {
|
||||||
|
vertex.init_segments(elements);
|
||||||
|
} else if moved {
|
||||||
|
for segment in &mut vertex.segments {
|
||||||
|
segment.parameters.truncate(1);
|
||||||
|
segment.area_fill_parameters.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !rebuild_mline_geometry(new) {
|
||||||
|
return Err("MLine vertices are degenerate".into());
|
||||||
|
}
|
||||||
|
crate::modules::draw::draw::mline::sync_mline_element_parameters(new, style);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Resolve a multiline into styled parallel lines in WCS.
|
/// Resolve a multiline into styled parallel lines in WCS.
|
||||||
pub fn resolved_mline_style<'a>(
|
pub fn resolved_mline_style<'a>(
|
||||||
m: &MLine,
|
m: &MLine,
|
||||||
|
|||||||
@@ -3339,3 +3339,29 @@ impl Transformable for Table {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Keep the per-cell merge dimensions (what DXF stores) in step with
|
||||||
|
/// `merged_ranges` (what DWG stores) after a scripted create or edit. Cells a
|
||||||
|
/// script did not touch keep their merge state when the ranges are unchanged.
|
||||||
|
pub(crate) fn normalize_scripted_table(old: Option<&Table>, new: &mut Table) {
|
||||||
|
if old.is_some_and(|old| old.merged_ranges == new.merged_ranges) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for row in &mut new.rows {
|
||||||
|
for cell in &mut row.cells {
|
||||||
|
cell.merge_width = 1;
|
||||||
|
cell.merge_height = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let ranges = new.merged_ranges.clone();
|
||||||
|
for range in &ranges {
|
||||||
|
if let Some(cell) = new
|
||||||
|
.rows
|
||||||
|
.get_mut(range.top_row)
|
||||||
|
.and_then(|row| row.cells.get_mut(range.left_col))
|
||||||
|
{
|
||||||
|
cell.merge_width = range.col_count() as i32;
|
||||||
|
cell.merge_height = range.row_count() as i32;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+87
-12
@@ -15,7 +15,8 @@
|
|||||||
|
|
||||||
#![cfg_attr(target_arch = "wasm32", allow(dead_code))]
|
#![cfg_attr(target_arch = "wasm32", allow(dead_code))]
|
||||||
|
|
||||||
use std::path::PathBuf;
|
use std::collections::BTreeMap;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
/// One entry in the curated plugin registry (`plugins/registry.json`).
|
/// One entry in the curated plugin registry (`plugins/registry.json`).
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
@@ -68,6 +69,9 @@ pub struct ExternalPlugin {
|
|||||||
pub command_prefixes: Vec<String>,
|
pub command_prefixes: Vec<String>,
|
||||||
/// The package directory under the plugins folder.
|
/// The package directory under the plugins folder.
|
||||||
pub dir: PathBuf,
|
pub dir: PathBuf,
|
||||||
|
/// True when the package ships inside the application rather than the
|
||||||
|
/// per-user plugin directory.
|
||||||
|
pub bundled: bool,
|
||||||
/// Whether a native library for this platform sits beside `plugin.toml`.
|
/// Whether a native library for this platform sits beside `plugin.toml`.
|
||||||
pub lib_present: bool,
|
pub lib_present: bool,
|
||||||
}
|
}
|
||||||
@@ -155,6 +159,24 @@ pub fn plugins_dir() -> Option<PathBuf> {
|
|||||||
Some(p)
|
Some(p)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Read-only plugins shipped with the application. The environment override
|
||||||
|
/// makes development and packaging tests independent of a particular bundle
|
||||||
|
/// layout.
|
||||||
|
pub fn bundled_plugins_dir() -> Option<PathBuf> {
|
||||||
|
if let Ok(p) = std::env::var("OCS_BUNDLED_PLUGINS_DIR") {
|
||||||
|
return Some(PathBuf::from(p));
|
||||||
|
}
|
||||||
|
let exe = std::env::current_exe().ok()?;
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
{
|
||||||
|
return Some(exe.parent()?.parent()?.join("Resources").join("plugins"));
|
||||||
|
}
|
||||||
|
#[cfg(not(target_os = "macos"))]
|
||||||
|
{
|
||||||
|
Some(exe.parent()?.join("plugins"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Delete an installed package's folder. It stays loaded for the current
|
/// Delete an installed package's folder. It stays loaded for the current
|
||||||
/// session (the library is resident); the removal takes effect on next start.
|
/// session (the library is resident); the removal takes effect on next start.
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
@@ -179,16 +201,33 @@ fn lib_extension() -> &'static str {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Discover every package under the plugins directory, sorted by `ribbon_order`
|
/// Discover bundled and per-user packages, sorted by `ribbon_order` then id.
|
||||||
/// then id. Missing directory → empty list (not an error).
|
/// A per-user package with the same id explicitly overrides the bundled copy.
|
||||||
|
/// Missing directories are ignored.
|
||||||
pub fn discover() -> Vec<ExternalPlugin> {
|
pub fn discover() -> Vec<ExternalPlugin> {
|
||||||
let Some(root) = plugins_dir() else {
|
discover_from_roots(bundled_plugins_dir().as_deref(), plugins_dir().as_deref())
|
||||||
return Vec::new();
|
}
|
||||||
|
|
||||||
|
fn discover_from_roots(
|
||||||
|
bundled_root: Option<&Path>,
|
||||||
|
user_root: Option<&Path>,
|
||||||
|
) -> Vec<ExternalPlugin> {
|
||||||
|
let mut found = BTreeMap::new();
|
||||||
|
if let Some(root) = bundled_root {
|
||||||
|
discover_root(root, true, &mut found);
|
||||||
|
}
|
||||||
|
if let Some(root) = user_root {
|
||||||
|
discover_root(root, false, &mut found);
|
||||||
|
}
|
||||||
|
let mut found: Vec<_> = found.into_values().collect();
|
||||||
|
found.sort_by(|a, b| a.ribbon_order.cmp(&b.ribbon_order).then(a.id.cmp(&b.id)));
|
||||||
|
found
|
||||||
|
}
|
||||||
|
|
||||||
|
fn discover_root(root: &Path, bundled: bool, found: &mut BTreeMap<String, ExternalPlugin>) {
|
||||||
|
let Ok(entries) = std::fs::read_dir(root) else {
|
||||||
|
return;
|
||||||
};
|
};
|
||||||
let Ok(entries) = std::fs::read_dir(&root) else {
|
|
||||||
return Vec::new();
|
|
||||||
};
|
|
||||||
let mut found = Vec::new();
|
|
||||||
for entry in entries.flatten() {
|
for entry in entries.flatten() {
|
||||||
let dir = entry.path();
|
let dir = entry.path();
|
||||||
if !dir.is_dir() {
|
if !dir.is_dir() {
|
||||||
@@ -206,11 +245,10 @@ pub fn discover() -> Vec<ExternalPlugin> {
|
|||||||
}
|
}
|
||||||
p.lib_present = lib_present_in(&dir);
|
p.lib_present = lib_present_in(&dir);
|
||||||
p.dir = dir;
|
p.dir = dir;
|
||||||
found.push(p);
|
p.bundled = bundled;
|
||||||
|
found.insert(p.id.clone(), p);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
found.sort_by(|a, b| a.ribbon_order.cmp(&b.ribbon_order).then(a.id.cmp(&b.id)));
|
|
||||||
found
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// True when a file with this platform's dynamic-library extension exists in
|
/// True when a file with this platform's dynamic-library extension exists in
|
||||||
@@ -298,6 +336,7 @@ pub(crate) fn parse_plugin_toml(text: &str) -> Option<ExternalPlugin> {
|
|||||||
ribbon_order,
|
ribbon_order,
|
||||||
command_prefixes,
|
command_prefixes,
|
||||||
dir: PathBuf::new(),
|
dir: PathBuf::new(),
|
||||||
|
bundled: false,
|
||||||
lib_present: false,
|
lib_present: false,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -531,6 +570,42 @@ xdata_apps = ["MYPLUGIN_RECORD"]
|
|||||||
assert!(parse_plugin_toml("name = \"x\"").is_none());
|
assert!(parse_plugin_toml("name = \"x\"").is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn discovers_bundled_plugins_and_allows_a_user_override() {
|
||||||
|
let base = std::env::temp_dir().join(format!(
|
||||||
|
"ocs-bundled-plugin-discovery-{}",
|
||||||
|
std::process::id()
|
||||||
|
));
|
||||||
|
let bundled = base.join("bundled").join("opencad.python");
|
||||||
|
let user = base.join("user").join("opencad.python");
|
||||||
|
std::fs::create_dir_all(&bundled).unwrap();
|
||||||
|
std::fs::create_dir_all(&user).unwrap();
|
||||||
|
let manifest = |version: &str| {
|
||||||
|
format!(
|
||||||
|
"[plugin]\nid=\"opencad.python\"\nversion=\"{version}\"\n[opencad]\napi_version=7\n"
|
||||||
|
)
|
||||||
|
};
|
||||||
|
std::fs::write(bundled.join("plugin.toml"), manifest("bundled")).unwrap();
|
||||||
|
std::fs::write(user.join("plugin.toml"), manifest("user")).unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
bundled.join(format!("plugin.{}", lib_extension())),
|
||||||
|
b"fixture",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
std::fs::write(user.join(format!("plugin.{}", lib_extension())), b"fixture").unwrap();
|
||||||
|
|
||||||
|
let bundled_only = discover_from_roots(Some(&base.join("bundled")), None);
|
||||||
|
assert_eq!(bundled_only.len(), 1);
|
||||||
|
assert!(bundled_only[0].bundled);
|
||||||
|
assert_eq!(bundled_only[0].version, "bundled");
|
||||||
|
|
||||||
|
let overridden = discover_from_roots(Some(&base.join("bundled")), Some(&base.join("user")));
|
||||||
|
assert_eq!(overridden.len(), 1);
|
||||||
|
assert!(!overridden[0].bundled);
|
||||||
|
assert_eq!(overridden[0].version, "user");
|
||||||
|
std::fs::remove_dir_all(base).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn incompatible_api_flagged() {
|
fn incompatible_api_flagged() {
|
||||||
let p = parse_plugin_toml("id=\"a\"\napi_version = 9999").unwrap();
|
let p = parse_plugin_toml("id=\"a\"\napi_version = 9999").unwrap();
|
||||||
|
|||||||
+4
-4
@@ -1,6 +1,6 @@
|
|||||||
// Open CAD Studio plugin runtime. Plugins are external cdylibs loaded from the
|
// Open CAD Studio plugin runtime. Plugins are out-of-process cdylibs loaded
|
||||||
// user plugins folder (see `external`) and installed via the marketplace; the
|
// from the application bundle or user plugins folder (see `external`).
|
||||||
// host ships no built-in add-ons. See `docs/plugin-architecture.md`.
|
// See `docs/plugin-architecture.md`.
|
||||||
|
|
||||||
pub mod external;
|
pub mod external;
|
||||||
pub mod host;
|
pub mod host;
|
||||||
@@ -81,4 +81,4 @@ mod tests {
|
|||||||
"expected an error queued for the command line, got: {queued:?}"
|
"expected an error queued for the command line, got: {queued:?}"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -51,6 +51,16 @@ pub fn publish_selection_changed_v4(tab_id: u64, handles: Vec<acadrust::Handle>)
|
|||||||
broadcast(HostNotification::SelectionChangedV4 { tab_id, handles });
|
broadcast(HostNotification::SelectionChangedV4 { tab_id, handles });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Broadcast a change in a tab's active interactive command.
|
||||||
|
pub fn publish_command_state_changed(tab_id: u64, command: Option<String>) {
|
||||||
|
broadcast(HostNotification::CommandStateChanged { tab_id, command });
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Broadcast drawing changes independently of shared-view subscriptions.
|
||||||
|
pub fn publish_drawing_changed(tab_id: u64, epoch: u64) {
|
||||||
|
broadcast(HostNotification::DrawingChanged { tab_id, epoch });
|
||||||
|
}
|
||||||
|
|
||||||
/// V4 notification handler installed on the plugin manager.
|
/// V4 notification handler installed on the plugin manager.
|
||||||
///
|
///
|
||||||
/// Forwards REPL status messages to the log; other notifications are handled
|
/// Forwards REPL status messages to the log; other notifications are handled
|
||||||
|
|||||||
@@ -543,6 +543,9 @@ impl Scene {
|
|||||||
let Some(existing) = self.document.get_entity(handle) else {
|
let Some(existing) = self.document.get_entity(handle) else {
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
|
// IPC snapshots omit storage-only payloads (notably Unknown/Extended
|
||||||
|
// entities). Preserve them when replacing a clone from a plugin.
|
||||||
|
entity.preserve_storage_data_from(existing);
|
||||||
// The caller edited a snapshot copy; keep the live entity in its block.
|
// The caller edited a snapshot copy; keep the live entity in its block.
|
||||||
entity.common_mut().owner_handle = existing.common().owner_handle;
|
entity.common_mut().owner_handle = existing.common().owner_handle;
|
||||||
|
|
||||||
|
|||||||
@@ -158,6 +158,16 @@ impl Scene {
|
|||||||
self.bump_selection_set();
|
self.bump_selection_set();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Script-facing replacement: preserve exactly the validated input order.
|
||||||
|
/// UI picks still use `select_entity` and its leader/annotation expansion.
|
||||||
|
pub(crate) fn replace_selection_exact(&mut self, handles: &[Handle]) {
|
||||||
|
if self.selected_handles_in_order() == handles { return; }
|
||||||
|
self.selected_constraint = None;
|
||||||
|
self.selected = handles.iter().copied().collect();
|
||||||
|
self.selected_order = handles.to_vec();
|
||||||
|
self.bump_selection_set();
|
||||||
|
}
|
||||||
|
|
||||||
pub fn select_all_visible(&mut self) -> usize {
|
pub fn select_all_visible(&mut self) -> usize {
|
||||||
let block = self.interaction_block_handle();
|
let block = self.interaction_block_handle();
|
||||||
let frozen: Option<HashSet<Handle>> = self
|
let frozen: Option<HashSet<Handle>> = self
|
||||||
|
|||||||
@@ -309,11 +309,19 @@ fn external_card<'a>(
|
|||||||
actions = actions.push(toggle_button(&p.id, disabled));
|
actions = actions.push(toggle_button(&p.id, disabled));
|
||||||
actions = actions.push(Space::new().width(6));
|
actions = actions.push(Space::new().width(6));
|
||||||
}
|
}
|
||||||
actions = actions.push(pill_button(
|
if p.bundled {
|
||||||
t!("Uninstall"),
|
actions = actions.push(
|
||||||
Message::PluginUninstall(p.id.clone()),
|
text(t!("Bundled with Open CAD Studio"))
|
||||||
button::danger,
|
.size(11)
|
||||||
));
|
.style(muted_style),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
actions = actions.push(pill_button(
|
||||||
|
t!("Uninstall"),
|
||||||
|
Message::PluginUninstall(p.id.clone()),
|
||||||
|
button::danger,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
container(column![info, actions].spacing(8).padding([10, 12]))
|
container(column![info, actions].spacing(8).padding([10, 12]))
|
||||||
.width(Fill)
|
.width(Fill)
|
||||||
|
|||||||
Reference in new issue
Block a user