feat: node graph overlay; move to opencadcodec/opencadkernel/opencadgraph

The codec and kernel repositories and crates are renamed opencadcodec and
opencadkernel. Inside OCS they are depended on under short keys, so code
reads `codec::`, `kernel::` and the new `graph::` (opencadgraph, the node
graph engine). File-format and protocol spellings stay as they were: the
ACIS product id `acadrust`, the ACADRUST_* switches and the plugin
version keys `acadrust_version` / `acadrust_source`.

A button left of MCP on the command line opens a translucent node graph
over the viewport, with a palette of object, input, math, logic, list,
text and geometry nodes added by click or drag. An object node owns
drawing entities and its rows are the Properties panel's own rows for
them: the single-object page is extracted from refresh_properties as
entity_property_sections, values use the control protocol's
property_json, and writes go through set_property_value with a property
target override, so the panel, MCP and the graph share one read/write
path. A list reaching an object row makes one entity per element. Each
graph action is one undo step; the canvas pans and zooms.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Hakan SevenandClaude Opus 5.5 committed 2026-09-25 07:34:23 +03:00
1 parent 56c04408d6
commit f537aff75c
430 files changed
+9925 -8540

No files matched your search

+4 -4
View File
@@ -6,7 +6,7 @@
use crate::app::Message;
use crate::ui::properties::acad_color_display;
use crate::ui::ROW_H;
use acadrust::types::Color as AcadColor;
use codec::types::Color as AcadColor;
use iced::widget::{button, column, container, row, text};
use iced::{Background, Border, Color, Element, Length, Theme};
use crate::t;
@@ -47,7 +47,7 @@ pub fn nearest_aci(r: u8, g: u8, b: u8) -> u8 {
let mut best_distance = u32::MAX;
for index in 1..=255 {
let Some((ar, ag, ab)) = acadrust::types::aci_table::aci_to_rgb(index) else {
let Some((ar, ag, ab)) = codec::types::aci_table::aci_to_rgb(index) else {
continue;
};
let dr = i32::from(r) - i32::from(ar);
@@ -83,7 +83,7 @@ pub fn color_display_name(c: AcadColor) -> String {
match c {
AcadColor::Index(i) => {
let (r, g, b) =
acadrust::types::aci_table::aci_to_rgb(i).unwrap_or((128, 128, 128));
codec::types::aci_table::aci_to_rgb(i).unwrap_or((128, 128, 128));
format!("{r},{g},{b}")
}
AcadColor::Rgb { r, g, b } => format!("{r},{g},{b}"),
@@ -462,7 +462,7 @@ pub fn index_color_page<'a>(
let selected_text = match current {
AcadColor::Index(i) => {
let (r, g, b) =
acadrust::types::aci_table::aci_to_rgb(i).unwrap_or((128, 128, 128));
codec::types::aci_table::aci_to_rgb(i).unwrap_or((128, 128, 128));
format!("ACI {i} RGB {r}, {g}, {b}")
}
AcadColor::Rgb { r, g, b } => {
+16 -1
View File
@@ -643,6 +643,7 @@ impl CommandLine {
control_enabled: bool,
control_busy: bool,
pick_pending: bool,
graph_open: bool,
) -> Element<'a, Message> {
// Only the most recent entries pushed within COMMANDLINEFADETIME
// show on the overlay (0 skips transient lines). The dropdown button
@@ -885,7 +886,21 @@ impl CommandLine {
bottom: 0.0,
left: 0.0,
});
let input_row = row![prompt, literal_btn, input_with_history, mcp_btn]
let graph_btn = button(crate::ui::icons::themed(crate::ui::icons::NODE_GRAPH, 13.0))
.on_press(Message::Graph(crate::ui::node_graph::GraphMsg::Toggle))
.style(move |theme: &Theme, status| {
if graph_open {
button::primary(theme, status)
} else {
button::subtle(theme, status)
}
})
.padding([2, 6]);
let graph_tip = container(text(t!("Node graph")).size(11))
.padding([3, 6])
.style(container::bordered_box);
let graph_btn = tooltip(graph_btn, graph_tip, tooltip::Position::Top).gap(4);
let input_row = row![prompt, literal_btn, input_with_history, graph_btn, mcp_btn]
.spacing(4)
.align_y(iced::Center);
+1
View File
@@ -61,6 +61,7 @@ pub static CLOSE: &[u8] = include_bytes!("../../assets/icons/ui/close.svg");
pub static PLUS: &[u8] = include_bytes!("../../assets/icons/ui/plus.svg");
pub static MINUS: &[u8] = include_bytes!("../../assets/icons/ui/minus.svg");
pub static TRASH: &[u8] = include_bytes!("../../assets/icons/ui/trash.svg");
pub static NODE_GRAPH: &[u8] = include_bytes!("../../assets/icons/ui/node_graph.svg");
pub static COPY: &[u8] = include_bytes!("../../assets/icons/ui/copy.svg");
pub static MENU: &[u8] = include_bytes!("../../assets/icons/ui/menu.svg");
pub static MOVE: &[u8] = include_bytes!("../../assets/icons/ui/move.svg");
+1
View File
@@ -7,6 +7,7 @@ pub mod command_line;
pub mod dock;
pub mod icons;
pub mod modal;
pub mod node_graph;
pub mod overlay;
pub mod popup;
pub mod properties;
+958
View File
@@ -0,0 +1,958 @@
//! Node graph overlay over the viewport.
//!
//! The graph itself — nodes, links, evaluation, the operation library — is the
//! `graph` crate. This module is its canvas: the palette, node cards, wires
//! and dragging. Object nodes own drawing entities, and their rows are the
//! Properties panel's own rows for that entity (built and written back in
//! `app::node_graph`); operation rows come from the node's spec.
use codec::{EntityType, Handle};
use graph::{Kind, NodeId, Port, Spec};
use iced::widget::{
button, canvas, checkbox, column, container, mouse_area, opaque, pin, row, scrollable, slider,
stack, text, text_input, Space,
};
use iced::advanced::layout::{self, Layout};
use iced::advanced::widget::{self, Widget};
use iced::advanced::{renderer, Renderer as _, Shell};
use iced::{
mouse, Background, Border, Element, Length, Point, Rectangle, Size, Theme, Transformation,
Vector,
};
use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
use serde_json::Value;
use crate::app::Message;
use crate::t;
pub const NODE_W: f32 = 280.0;
const HEADER_H: f32 = 26.0;
const SECTION_H: f32 = 22.0;
const ROW_H: f32 = 22.0;
const LABEL_W: f32 = 96.0;
const PORT_W: f32 = 14.0;
const PORT_HIT: f32 = 10.0;
pub const TREE_W: f32 = 190.0;
const ZOOM_STEP: f32 = 1.1;
const ZOOM_STEPS: std::ops::RangeInclusive<i32> = -15..=12;
/// Drawing objects a node can create.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ObjectKind {
Line,
Circle,
Arc,
Ellipse,
Point,
Polyline,
Ray,
XLine,
Text,
MText,
}
const OBJECTS: &[ObjectKind] = &[
ObjectKind::Line,
ObjectKind::Circle,
ObjectKind::Arc,
ObjectKind::Ellipse,
ObjectKind::Point,
ObjectKind::Polyline,
ObjectKind::Ray,
ObjectKind::XLine,
ObjectKind::Text,
ObjectKind::MText,
];
impl ObjectKind {
/// Display name, also the graph's object type name.
pub fn name(self) -> &'static str {
match self {
ObjectKind::Line => "Line",
ObjectKind::Circle => "Circle",
ObjectKind::Arc => "Arc",
ObjectKind::Ellipse => "Ellipse",
ObjectKind::Point => "Point",
ObjectKind::Polyline => "Polyline",
ObjectKind::Ray => "Ray",
ObjectKind::XLine => "Construction Line",
ObjectKind::Text => "Text",
ObjectKind::MText => "Multiline Text",
}
}
pub fn from_name(name: &str) -> Option<Self> {
OBJECTS.iter().copied().find(|kind| kind.name() == name)
}
fn command(self) -> &'static str {
match self {
ObjectKind::Line => "LINE",
ObjectKind::Circle => "CIRCLE",
ObjectKind::Arc => "ARC",
ObjectKind::Ellipse => "ELLIPSE",
ObjectKind::Point => "POINT",
ObjectKind::Polyline => "PLINE",
ObjectKind::Ray => "RAY",
ObjectKind::XLine => "XLINE",
ObjectKind::Text => "TEXT",
ObjectKind::MText => "MTEXT",
}
}
/// The entity a new node starts from.
pub fn entity(self) -> EntityType {
use codec::entities as e;
use codec::types::{Vector2, Vector3};
let origin = Vector3::new(0.0, 0.0, 0.0);
let x_axis = Vector3::new(1.0, 0.0, 0.0);
match self {
ObjectKind::Line => EntityType::Line(e::Line::from_coords(0.0, 0.0, 0.0, 10.0, 0.0, 0.0)),
ObjectKind::Circle => EntityType::Circle(e::Circle::from_coords(0.0, 0.0, 0.0, 5.0)),
ObjectKind::Arc => EntityType::Arc(e::Arc::from_coords(
0.0,
0.0,
0.0,
5.0,
0.0,
std::f64::consts::PI,
)),
ObjectKind::Ellipse => EntityType::Ellipse(e::Ellipse::from_center_axes(
origin,
Vector3::new(10.0, 0.0, 0.0),
0.5,
)),
ObjectKind::Point => EntityType::Point(e::Point::from_coords(0.0, 0.0, 0.0)),
ObjectKind::Polyline => EntityType::LwPolyline(e::LwPolyline::from_points(vec![
Vector2::new(0.0, 0.0),
Vector2::new(10.0, 0.0),
Vector2::new(10.0, 10.0),
])),
ObjectKind::Ray => EntityType::Ray(e::Ray::new(origin, x_axis)),
ObjectKind::XLine => EntityType::XLine(e::XLine::new(origin, x_axis)),
ObjectKind::Text => {
EntityType::Text(e::Text::with_value("Text", origin).with_height(2.5))
}
ObjectKind::MText => {
EntityType::MText(e::MText::with_value("MText", origin).with_height(2.5))
}
}
}
}
/// What a palette entry adds.
#[derive(Clone, Copy, Debug)]
pub enum PaletteItem {
Object(ObjectKind),
Op(&'static Spec),
}
impl PaletteItem {
fn label(self) -> &'static str {
match self {
PaletteItem::Object(kind) => kind.name(),
PaletteItem::Op(spec) => spec.name,
}
}
}
/// Canvas state of one node.
pub struct NodeUi {
pub pos: Point,
/// Expanded section titles; a new object node opens only Geometry.
pub open: HashSet<String>,
/// Entities an object node owns, one per list element.
pub handles: Vec<Handle>,
}
pub enum RowWidget {
Field,
Slider { min: f64, max: f64, step: f64 },
Toggle,
}
/// A group of rows; an empty title has no header and is always open.
pub struct NodeSection {
pub title: String,
pub rows: Vec<NodeRow>,
}
pub struct NodeRow {
pub field: String,
pub label: String,
pub value: Value,
pub input: bool,
pub output: bool,
pub widget: RowWidget,
}
pub enum Drag {
Palette(PaletteItem),
Node(NodeId, Vector),
Link(Port),
Pan(Point, Vector),
}
#[derive(Default)]
pub struct Graph {
pub engine: graph::Graph,
pub ui: HashMap<NodeId, NodeUi>,
pub pan: Vector,
/// Wheel steps; the scale is `ZOOM_STEP ^ zoom_steps`.
zoom_steps: i32,
pub cursor: Point,
pub drag: Option<Drag>,
pub drafts: HashMap<Port, String>,
closed_categories: HashSet<&'static str>,
}
#[derive(Debug, Clone)]
pub enum GraphMsg {
Toggle,
Category(&'static str),
PalettePress(PaletteItem),
Moved(Point),
Pressed,
Released,
NodePress(NodeId),
NodeDelete(NodeId),
Section(NodeId, String),
OutPress(Port),
InPress(Port),
Input(Port, String),
Commit(Port),
/// A slider or toggle set an operation input.
Set(Port, Value),
Zoom(mouse::ScrollDelta),
}
fn msg(m: GraphMsg) -> Message {
Message::Graph(m)
}
/// Compact display of a port value.
pub fn display(value: &Value) -> String {
let number = |x: f64| {
let s = format!("{:.4}", x);
s.trim_end_matches('0').trim_end_matches('.').to_owned()
};
match value {
Value::Number(n) => n.as_f64().map_or_else(|| n.to_string(), number),
Value::Array(items) => {
let shown: Vec<String> = items.iter().take(4).map(display).collect();
let more = if items.len() > 4 { ", …" } else { "" };
format!("[{}] {}{more}", items.len(), shown.join(", "))
}
Value::Object(_) => match graph::value::point(value) {
Some(p) => format!("({}, {}, {})", number(p[0]), number(p[1]), number(p[2])),
None => value.to_string(),
},
other => graph::value::text(other),
}
}
impl Graph {
fn zoom(&self) -> f32 {
ZOOM_STEP.powi(self.zoom_steps)
}
/// Screen point → graph coordinates.
fn to_graph(&self, screen: Point) -> Point {
let zoom = self.zoom();
Point::new((screen.x - self.pan.x) / zoom, (screen.y - self.pan.y) / zoom)
}
/// Graph coordinates → screen point.
fn to_screen(&self, graph: Point) -> Point {
let zoom = self.zoom();
Point::new(self.pan.x + graph.x * zoom, self.pan.y + graph.y * zoom)
}
pub fn add_node(&mut self, item: PaletteItem, handles: Vec<Handle>, pos: Point) -> NodeId {
let kind = match item {
PaletteItem::Object(kind) => Kind::Object(kind.name().to_owned()),
PaletteItem::Op(spec) => Kind::Op(spec),
};
let id = self.engine.add(kind);
let mut open = HashSet::default();
open.insert(t!("Geometry").into_owned());
self.ui.insert(id, NodeUi { pos, open, handles });
id
}
/// Where a palette entry lands: under the cursor when dropped on the
/// canvas, staggered beside the palette when clicked.
pub fn drop_position(&self) -> Point {
if self.cursor.x > TREE_W {
return self.to_graph(self.cursor);
}
let step = (self.engine.nodes.len() % 6) as f32 * 30.0;
self.to_graph(Point::new(TREE_W + 40.0 + step, 40.0 + step))
}
/// Rows of an operation node, read from its spec. An input sharing its
/// name with an output is one row with both ports.
fn op_sections(&self, id: NodeId, spec: &'static Spec) -> Vec<NodeSection> {
let Some(node) = self.engine.node(id) else {
return Vec::new();
};
let param = |name: &str| node.params.get(name).and_then(graph::value::num);
let mut rows: Vec<NodeRow> = spec
.inputs
.iter()
.map(|input| {
let port = Port { node: id, field: input.name.to_owned() };
let widget = match (spec.name, input.name) {
("Number Slider" | "Integer Slider", "value") => RowWidget::Slider {
min: param("min").unwrap_or(0.0),
max: param("max").unwrap_or(1.0),
step: param("step").unwrap_or(0.0),
},
("Boolean", "value") => RowWidget::Toggle,
_ => RowWidget::Field,
};
let output = spec.outputs.contains(&input.name);
NodeRow {
field: input.name.to_owned(),
label: input.name.to_owned(),
value: if output {
node.outputs.get(input.name).cloned().unwrap_or(Value::Null)
} else {
self.engine.input(&port)
},
input: true,
output,
widget,
}
})
.collect();
rows.extend(
spec.outputs
.iter()
.filter(|name| !spec.inputs.iter().any(|input| input.name == **name))
.map(|name| NodeRow {
field: (*name).to_owned(),
label: (*name).to_owned(),
value: node.outputs.get(*name).cloned().unwrap_or(Value::Null),
input: false,
output: true,
widget: RowWidget::Field,
}),
);
vec![NodeSection { title: String::new(), rows }]
}
/// Every node's rows, parallel to `engine.nodes`. `objects` holds the
/// object nodes' rows, which only the app can build.
pub fn sections(&self, mut objects: HashMap<NodeId, Vec<NodeSection>>) -> Vec<Vec<NodeSection>> {
self.engine
.nodes
.iter()
.map(|node| match node.kind {
Kind::Op(spec) => self.op_sections(node.id, spec),
Kind::Object(_) => objects.remove(&node.id).unwrap_or_default(),
})
.collect()
}
fn is_open(&self, id: NodeId, section: &NodeSection) -> bool {
section.title.is_empty()
|| self.ui.get(&id).is_some_and(|ui| ui.open.contains(&section.title))
}
/// Row centre of `field`, relative to the node's top. Rows of a collapsed
/// section keep their ports on its header.
fn port_offset(&self, id: NodeId, sections: &[NodeSection], field: &str, input: bool) -> Option<f32> {
let mut y = HEADER_H;
for section in sections {
let matches = |row: &NodeRow| row.field == field && if input { row.input } else { row.output };
let header = if section.title.is_empty() { 0.0 } else { SECTION_H };
if !self.is_open(id, section) {
if section.rows.iter().any(matches) {
return Some(y + SECTION_H * 0.5);
}
y += header;
continue;
}
y += header;
for row in &section.rows {
if matches(row) {
return Some(y + ROW_H * 0.5);
}
y += ROW_H;
}
}
None
}
fn port_point(&self, sections: &[Vec<NodeSection>], port: &Port, input: bool) -> Option<Point> {
let index = self.engine.nodes.iter().position(|node| node.id == port.node)?;
let ui = self.ui.get(&port.node)?;
let y = self.port_offset(port.node, &sections[index], &port.field, input)?;
let x = if input { PORT_W * 0.5 } else { NODE_W - PORT_W * 0.5 };
Some(self.to_screen(ui.pos + Vector::new(x, y)))
}
/// The input port under the cursor.
pub fn hit_input(&self, sections: &[Vec<NodeSection>]) -> Option<Port> {
self.engine.nodes.iter().zip(sections).find_map(|(node, node_sections)| {
node_sections
.iter()
.filter(|section| self.is_open(node.id, section))
.flat_map(|section| &section.rows)
.filter(|row| row.input)
.map(|row| Port { node: node.id, field: row.field.clone() })
.find(|port| {
self.port_point(sections, port, true)
.is_some_and(|p| p.distance(self.cursor) <= PORT_HIT * self.zoom().max(0.5))
})
})
}
pub fn view(&self, sections: Vec<Vec<NodeSection>>) -> Element<'_, Message> {
let wires = self
.engine
.links
.iter()
.filter_map(|link| {
Some((
self.port_point(&sections, &link.from, false)?,
self.port_point(&sections, &link.to, true)?,
))
})
.collect();
let pending = match &self.drag {
Some(Drag::Link(from)) => self
.port_point(&sections, from, false)
.map(|start| (start, self.cursor)),
_ => None,
};
let zoom = self.zoom();
let mut nodes = stack![];
for (node, node_sections) in self.engine.nodes.iter().zip(sections) {
let Some(ui) = self.ui.get(&node.id) else {
continue;
};
nodes = nodes.push(pin(self.node_view(node, node_sections)).x(ui.pos.x).y(ui.pos.y));
}
let mut layers = stack![
canvas(Wires { wires, pending, width: 2.0 * zoom.max(0.5) })
.width(Length::Fill)
.height(Length::Fill),
Zoomed {
content: nodes.width(Length::Fill).height(Length::Fill).into(),
pan: self.pan,
zoom,
},
self.palette_view(),
];
if let Some(Drag::Palette(item)) = self.drag {
let ghost = container(text(t!(item.label())).size(11))
.padding([3, 8])
.style(container::bordered_box);
layers = layers.push(pin(ghost).x(self.cursor.x + 10.0).y(self.cursor.y + 10.0));
}
let area = mouse_area(layers.width(Length::Fill).height(Length::Fill))
.on_move(|p| msg(GraphMsg::Moved(p)))
.on_press(msg(GraphMsg::Pressed))
.on_release(msg(GraphMsg::Released))
.on_middle_press(msg(GraphMsg::Pressed))
.on_middle_release(msg(GraphMsg::Released))
.on_scroll(|delta| msg(GraphMsg::Zoom(delta)));
opaque(area)
}
fn palette_entry(&self, item: PaletteItem) -> Element<'_, Message> {
let icon: Element<'_, Message> = match item {
PaletteItem::Object(kind) => crate::modules::registry::command_icon(kind.command())
.map_or_else(|| Space::new().width(14.0).into(), |bytes| {
crate::ui::icons::semantic(bytes, 14.0)
}),
PaletteItem::Op(_) => Space::new().width(14.0).into(),
};
mouse_area(
container(
row![icon, text(t!(item.label())).size(11)]
.spacing(6)
.align_y(iced::Center),
)
.padding([3, 16])
.width(Length::Fill),
)
.on_press(msg(GraphMsg::PalettePress(item)))
.interaction(mouse::Interaction::Grab)
.into()
}
fn palette_view(&self) -> Element<'_, Message> {
let mut col = column![text(t!("Nodes")).size(12)].spacing(2).padding(8);
let categories = std::iter::once("Objects").chain(graph::CATEGORIES.iter().copied());
for category in categories {
let open = !self.closed_categories.contains(category);
col = col.push(
button(
row![
crate::ui::icons::themed_arrow_toggle(open, 9.0),
text(t!(category)).size(11)
]
.spacing(4)
.align_y(iced::Center),
)
.on_press(msg(GraphMsg::Category(category)))
.style(button::text)
.width(Length::Fill)
.padding([2, 2]),
);
if !open {
continue;
}
if category == "Objects" {
for &kind in OBJECTS {
col = col.push(self.palette_entry(PaletteItem::Object(kind)));
}
} else {
for spec in graph::LIBRARY.iter().filter(|spec| spec.category == category) {
col = col.push(self.palette_entry(PaletteItem::Op(spec)));
}
}
}
opaque(
container(scrollable(col))
.width(TREE_W)
.height(Length::Fill)
.style(|theme: &Theme| container::Style {
background: Some(Background::Color(theme.palette().background.base.color)),
border: Border {
color: theme.palette().background.strong.color,
width: 1.0,
radius: 0.0.into(),
},
..Default::default()
}),
)
}
fn node_view(&self, node: &graph::Node, sections: Vec<NodeSection>) -> Element<'_, Message> {
let id = node.id;
let title = match &node.kind {
Kind::Op(spec) => t!(spec.name).into_owned(),
Kind::Object(name) => {
let count = self.ui.get(&id).map_or(0, |ui| ui.handles.len());
let name = t!(name.as_str()).into_owned();
if count > 1 { format!("{name} ×{count}") } else { name }
}
};
let header = row![
mouse_area(
container(text(title).size(12))
.padding([4, 8])
.width(Length::Fill)
.height(HEADER_H),
)
.on_press(msg(GraphMsg::NodePress(id)))
.interaction(mouse::Interaction::Grab),
button(crate::ui::icons::themed(crate::ui::icons::CLOSE, 10.0))
.on_press(msg(GraphMsg::NodeDelete(id)))
.style(button::text)
.padding([6, 8]),
]
.height(HEADER_H);
let header = container(header).style(|theme: &Theme| container::Style {
background: Some(Background::Color(theme.palette().primary.weak.color)),
text_color: Some(theme.palette().primary.weak.text),
..Default::default()
});
let mut col = column![header];
if sections.is_empty() {
col = col.push(
container(text(t!("Object deleted")).size(11))
.padding([4, 8])
.height(ROW_H),
);
}
for section in sections {
let open = self.is_open(id, &section);
if !section.title.is_empty() {
col = col.push(
button(
row![
crate::ui::icons::themed_arrow_toggle(open, 9.0),
text(section.title.clone()).size(11)
]
.spacing(4)
.align_y(iced::Center),
)
.on_press(msg(GraphMsg::Section(id, section.title)))
.style(button::secondary)
.width(Length::Fill)
.height(SECTION_H)
.padding([0, 6]),
);
}
if open {
for node_row in section.rows {
col = col.push(self.row_view(id, node_row));
}
}
}
opaque(
container(col)
.width(NODE_W)
.style(|theme: &Theme| container::Style {
background: Some(Background::Color(theme.palette().background.base.color)),
border: Border {
color: theme.palette().background.strong.color,
width: 1.0,
radius: 4.0.into(),
},
..Default::default()
}),
)
}
fn row_view(&self, id: NodeId, node_row: NodeRow) -> Element<'_, Message> {
let port = Port { node: id, field: node_row.field };
let linked_in = self.engine.is_linked(&port);
let linked_out = self.engine.links.iter().any(|link| link.from == port);
let shown = display(&node_row.value);
let in_port: Element<'_, Message> = if node_row.input {
mouse_area(port_dot(linked_in))
.on_press(msg(GraphMsg::InPress(port.clone())))
.into()
} else {
Space::new().width(PORT_W).into()
};
let out_port: Element<'_, Message> = if node_row.output {
mouse_area(port_dot(linked_out))
.on_press(msg(GraphMsg::OutPress(port.clone())))
.into()
} else {
Space::new().width(PORT_W).into()
};
let value: Element<'_, Message> = if node_row.input && !linked_in {
match node_row.widget {
RowWidget::Slider { min, max, step } => {
let current = graph::value::num(&node_row.value).unwrap_or(min);
let set = port.clone();
let mut bar = slider(min.min(max)..=max.max(min), current, move |x| {
msg(GraphMsg::Set(set.clone(), graph::value::number(x)))
});
if step > 0.0 {
bar = bar.step(step);
}
row![bar.width(Length::Fill), text(shown).size(11)]
.spacing(4)
.align_y(iced::Center)
.width(Length::Fill)
.into()
}
RowWidget::Toggle => {
let set = port.clone();
checkbox(graph::value::boolean(&node_row.value).unwrap_or(false))
.on_toggle(move |on| msg(GraphMsg::Set(set.clone(), Value::Bool(on))))
.size(14)
.width(Length::Fill)
.into()
}
RowWidget::Field => {
let draft = self.drafts.get(&port).cloned().unwrap_or(shown);
let edit = port.clone();
text_input("", &draft)
.on_input(move |s| msg(GraphMsg::Input(edit.clone(), s)))
.on_submit(msg(GraphMsg::Commit(port)))
.size(11)
.padding([2, 4])
.width(Length::Fill)
.into()
}
}
} else {
text(shown).size(11).width(Length::Fill).into()
};
row![in_port, text(node_row.label).size(11).width(LABEL_W), value, out_port]
.spacing(2)
.height(ROW_H)
.align_y(iced::Center)
.into()
}
/// Pure canvas state; document and evaluation work is the app's.
pub fn update_ui(&mut self, message: &GraphMsg) {
match message {
GraphMsg::Category(category) => {
if !self.closed_categories.remove(category) {
self.closed_categories.insert(category);
}
}
GraphMsg::PalettePress(item) => self.drag = Some(Drag::Palette(*item)),
GraphMsg::Moved(p) => {
self.cursor = *p;
match self.drag {
Some(Drag::Node(id, grab)) => {
let pos = self.to_graph(*p) - grab;
if let Some(ui) = self.ui.get_mut(&id) {
ui.pos = pos;
}
}
Some(Drag::Pan(start, start_pan)) => self.pan = start_pan + (*p - start),
_ => {}
}
}
GraphMsg::Pressed => self.drag = Some(Drag::Pan(self.cursor, self.pan)),
GraphMsg::NodePress(id) => {
// Raise the grabbed node above the others.
if let Some(index) = self.engine.nodes.iter().position(|node| node.id == *id) {
let node = self.engine.nodes.remove(index);
self.engine.nodes.push(node);
}
if let Some(ui) = self.ui.get(id) {
self.drag = Some(Drag::Node(*id, self.to_graph(self.cursor) - ui.pos));
}
}
GraphMsg::Section(id, title) => {
if let Some(ui) = self.ui.get_mut(id) {
if !ui.open.remove(title) {
ui.open.insert(title.clone());
}
}
}
GraphMsg::OutPress(port) => self.drag = Some(Drag::Link(port.clone())),
GraphMsg::InPress(port) => {
// Grabbing a linked input detaches the link to re-route it.
if let Some(link) = self.engine.disconnect(port) {
self.drag = Some(Drag::Link(link.from));
}
}
GraphMsg::Zoom(delta) => {
let lines = match delta {
mouse::ScrollDelta::Lines { y, .. } => *y,
mouse::ScrollDelta::Pixels { y, .. } => *y / 40.0,
};
if lines != 0.0 {
// Keep the graph point under the cursor where it is.
let anchor = self.to_graph(self.cursor);
self.zoom_steps = (self.zoom_steps + lines.signum() as i32)
.clamp(*ZOOM_STEPS.start(), *ZOOM_STEPS.end());
let zoom = self.zoom();
self.pan = Vector::new(self.cursor.x - anchor.x * zoom, self.cursor.y - anchor.y * zoom);
}
}
GraphMsg::Input(port, value) => {
self.drafts.insert(port.clone(), value.clone());
}
_ => {}
}
}
}
fn port_dot<'a>(linked: bool) -> Element<'a, Message> {
container(
container(Space::new())
.width(8.0)
.height(8.0)
.style(move |theme: &Theme| {
let palette = theme.palette();
container::Style {
background: linked.then_some(Background::Color(palette.primary.base.color)),
border: Border {
color: palette.primary.base.color,
width: 1.5,
radius: 4.0.into(),
},
..Default::default()
}
}),
)
.width(PORT_W)
.height(ROW_H)
.align_x(iced::Center)
.align_y(iced::Center)
.into()
}
/// Translucent backdrop plus link curves.
struct Wires {
wires: Vec<(Point, Point)>,
pending: Option<(Point, Point)>,
width: f32,
}
fn wire_path(a: Point, b: Point) -> canvas::Path {
let dx = ((b.x - a.x).abs() * 0.5).max(40.0);
canvas::Path::new(|path| {
path.move_to(a);
path.bezier_curve_to(Point::new(a.x + dx, a.y), Point::new(b.x - dx, b.y), b);
})
}
impl canvas::Program<Message> for Wires {
type State = ();
fn draw(
&self,
_state: &(),
renderer: &iced::Renderer,
theme: &Theme,
bounds: Rectangle,
_cursor: mouse::Cursor,
) -> Vec<canvas::Geometry> {
let palette = theme.palette();
let mut frame = canvas::Frame::new(renderer, bounds.size());
frame.fill_rectangle(
Point::ORIGIN,
bounds.size(),
palette.background.base.color.scale_alpha(0.6),
);
let stroke = canvas::Stroke::default()
.with_color(palette.primary.base.color)
.with_width(self.width);
for (a, b) in &self.wires {
frame.stroke(&wire_path(*a, *b), stroke);
}
if let Some((a, b)) = self.pending {
frame.stroke(
&wire_path(a, b),
stroke.with_color(palette.primary.weak.color),
);
}
vec![frame.into_geometry()]
}
}
/// Lays its content out in graph space and draws and hit-tests it through
/// `pan` and `zoom`, so every widget inside scales as one picture.
struct Zoomed<'a> {
content: Element<'a, Message>,
pan: Vector,
zoom: f32,
}
impl Zoomed<'_> {
/// Content coordinates → screen, for a layer whose top-left is `origin`.
fn transformation(&self, origin: Point) -> Transformation {
Transformation::translate(origin.x + self.pan.x, origin.y + self.pan.y)
* Transformation::scale(self.zoom)
* Transformation::translate(-origin.x, -origin.y)
}
}
impl Widget<Message, Theme, iced::Renderer> for Zoomed<'_> {
fn size(&self) -> Size<Length> {
Size::new(Length::Fill, Length::Fill)
}
fn diff(&mut self, tree: &mut widget::Tree) {
tree.diff_children(std::slice::from_mut(&mut self.content));
}
fn layout(
&mut self,
tree: &mut widget::Tree,
renderer: &iced::Renderer,
limits: &layout::Limits,
) -> layout::Node {
let size = limits.max();
let inner = layout::Limits::new(Size::ZERO, size * (1.0 / self.zoom));
let content = self
.content
.as_widget_mut()
.layout(&mut tree.children[0], renderer, &inner);
layout::Node::with_children(size, vec![content])
}
fn update(
&mut self,
tree: &mut widget::Tree,
event: &iced::Event,
layout: Layout<'_>,
cursor: mouse::Cursor,
renderer: &iced::Renderer,
shell: &mut Shell<'_, Message>,
viewport: &Rectangle,
) {
let inverse = self.transformation(layout.position()).inverse();
let Some(content) = layout.children().next() else {
return;
};
self.content.as_widget_mut().update(
&mut tree.children[0],
event,
content,
cursor * inverse,
renderer,
shell,
&(*viewport * inverse),
);
}
fn mouse_interaction(
&self,
tree: &widget::Tree,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
renderer: &iced::Renderer,
) -> mouse::Interaction {
let inverse = self.transformation(layout.position()).inverse();
layout.children().next().map_or(mouse::Interaction::None, |content| {
self.content.as_widget().mouse_interaction(
&tree.children[0],
content,
cursor * inverse,
&(*viewport * inverse),
renderer,
)
})
}
fn operate(
&mut self,
tree: &mut widget::Tree,
layout: Layout<'_>,
renderer: &iced::Renderer,
operation: &mut dyn widget::Operation,
) {
if let Some(content) = layout.children().next() {
self.content
.as_widget_mut()
.operate(&mut tree.children[0], content, renderer, operation);
}
}
fn draw(
&self,
tree: &widget::Tree,
renderer: &mut iced::Renderer,
theme: &Theme,
style: &renderer::Style,
layout: Layout<'_>,
cursor: mouse::Cursor,
_viewport: &Rectangle,
) {
let Some(content) = layout.children().next() else {
return;
};
let bounds = layout.bounds();
let transformation = self.transformation(bounds.position());
let inverse = transformation.inverse();
renderer.with_layer(bounds, |renderer| {
renderer.with_transformation(transformation, |renderer| {
self.content.as_widget().draw(
&tree.children[0],
renderer,
theme,
style,
content,
cursor * inverse,
&(bounds * inverse),
);
});
});
}
}
impl<'a> From<Zoomed<'a>> for Element<'a, Message> {
fn from(zoomed: Zoomed<'a>) -> Self {
Element::new(zoomed)
}
}
+4 -4
View File
@@ -475,7 +475,7 @@ pub fn resolve_selection_base_color(
// ACI 0 (BYBLOCK) and 256 (BYLAYER) are not explicit overrides;
// the sysvar uses 0 as the unset sentinel; valid user picks are 1..=255.
if custom > 0 {
if let Some((r, g, b)) = acadrust::types::aci_table::aci_to_rgb(custom) {
if let Some((r, g, b)) = codec::types::aci_table::aci_to_rgb(custom) {
return Color::from_rgb8(r, g, b);
}
}
@@ -1029,7 +1029,7 @@ fn draw_grip_marker(
if grip.is_hot {
let hot_color = if visual.grip_hot > 0 {
if let Some((r, g, b)) = acadrust::types::aci_table::aci_to_rgb(visual.grip_hot) {
if let Some((r, g, b)) = codec::types::aci_table::aci_to_rgb(visual.grip_hot) {
Color::from_rgb8(r, g, b)
} else {
theme.palette().danger.base.color
@@ -1041,7 +1041,7 @@ fn draw_grip_marker(
} else if grip.is_hovered {
let pair = theme.palette().primary.strong;
let hover_color = if visual.grip_hover > 0 {
if let Some((r, g, b)) = acadrust::types::aci_table::aci_to_rgb(visual.grip_hover) {
if let Some((r, g, b)) = codec::types::aci_table::aci_to_rgb(visual.grip_hover) {
Color::from_rgb8(r, g, b)
} else {
pair.color
@@ -1061,7 +1061,7 @@ fn draw_grip_marker(
} else {
let palette = theme.palette();
let color = if visual.grip_color > 0 {
if let Some((r, g, b)) = acadrust::types::aci_table::aci_to_rgb(visual.grip_color) {
if let Some((r, g, b)) = codec::types::aci_table::aci_to_rgb(visual.grip_color) {
Color::from_rgb8(r, g, b)
} else {
palette.primary.base.color
+2 -2
View File
@@ -11,7 +11,7 @@ use crate::app::Message;
/// Row content for one overlapping candidate.
pub struct CycleCandidate {
pub handle: acadrust::Handle,
pub handle: codec::Handle,
pub type_name: String,
pub layer: String,
/// The color the object is drawn with (layer-inherited when ByLayer).
@@ -53,7 +53,7 @@ fn clamp_col_width(labels: impl Iterator<Item = usize>, glyph_w: f32, min: f32,
}
fn item_row(
handle: acadrust::Handle,
handle: codec::Handle,
type_name: String,
layer: String,
color: [f32; 4],
+4 -4
View File
@@ -11,8 +11,8 @@ use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
use std::{fmt, sync::Arc};
use crate::ui::ROW_H;
use acadrust::types::{Color as AcadColor, LineWeight};
use acadrust::Handle;
use codec::types::{Color as AcadColor, LineWeight};
use codec::Handle;
use iced::widget::{
button, canvas, column, combo_box, container, mouse_area, row, scrollable, text, text_input,
tooltip, Space,
@@ -146,7 +146,7 @@ impl canvas::Program<Message> for HatchPatternPreview {
boundary_exterior: None,
boundary_sources: None,
boundary_paths: None,
style: acadrust::entities::HatchStyleType::Normal,
style: codec::entities::HatchStyleType::Normal,
pattern: self.pattern.clone(),
name: String::new(),
color: [1.0; 4],
@@ -2130,7 +2130,7 @@ pub fn acad_color_display(c: AcadColor) -> (Color, &'static str) {
"ByBlock",
),
AcadColor::Index(i) => {
let (r, g, b) = acadrust::types::aci_table::aci_to_rgb(i).unwrap_or((200, 200, 200));
let (r, g, b) = codec::types::aci_table::aci_to_rgb(i).unwrap_or((200, 200, 200));
(
Color::from_rgb(r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0),
aci_label(i),
+2 -2
View File
@@ -11,7 +11,7 @@ use super::widgets::{muted_text_style, popup_panel_style, popup_row_style};
use crate::app::Message;
use crate::t;
use crate::ui::properties::acad_color_display;
use acadrust::types::Color as AcadColor;
use codec::types::Color as AcadColor;
use iced::widget::{button, column, container, row, text, Space};
use iced::{Background, Border, Element, Length, Padding, Theme};
@@ -82,7 +82,7 @@ pub const QUICK_PICK_GRID: [[(u8, u8, u8); 9]; 5] = [
#[allow(dead_code)]
pub fn aci_1_9() -> [(u8, u8, u8); 9] {
std::array::from_fn(|i| {
acadrust::types::aci_table::aci_to_rgb((i + 1) as u8).unwrap_or((128, 128, 128))
codec::types::aci_table::aci_to_rgb((i + 1) as u8).unwrap_or((128, 128, 128))
})
}
+1 -1
View File
@@ -11,7 +11,7 @@ use std::sync::Arc;
use rustc_hash::FxHashMap as HashMap;
use acadrust::types::{Color as AcadColor, LineWeight};
use codec::types::{Color as AcadColor, LineWeight};
use iced::widget::{button, column, container, mouse_area, row, scrollable, text};
use iced::{Background, Border, Color, Element, Fill, Length, Padding, Theme};
+1 -1
View File
@@ -5,7 +5,7 @@ use rustc_hash::FxHashMap as HashMap;
use std::cell::RefCell;
use std::time::Duration;
use acadrust::types::{Color as AcadColor, LineWeight};
use codec::types::{Color as AcadColor, LineWeight};
use iced::advanced::{
layout, mouse, overlay, renderer, text as advanced_text, widget, Layout, Shell, Widget,
};
+1 -1
View File
@@ -33,7 +33,7 @@ fn choices(values: &[(&str, &str)]) -> Vec<EnumChoice> {
pub struct MLeaderStyleView<'a> {
pub styles: Vec<String>,
pub selected: &'a str,
pub style: Option<&'a acadrust::objects::MultiLeaderStyle>,
pub style: Option<&'a codec::objects::MultiLeaderStyle>,
pub current: String,
pub tab: u8,
pub compare_name: String,
+1 -1
View File
@@ -10,7 +10,7 @@ use std::borrow::Cow;
pub struct MlStyleView<'a> {
pub styles: Vec<String>,
pub selected: &'a str,
pub style: Option<&'a acadrust::objects::MLineStyle>,
pub style: Option<&'a codec::objects::MLineStyle>,
pub current: String,
pub tab: u8,
pub compare_name: String,
+14 -14
View File
@@ -92,11 +92,11 @@ fn field_style(theme: &Theme, status: text_input::Status) -> text_input::Style {
/// unit-tested and benched without building widgets. `pub` (not
/// `pub(crate)`) so the `cargo bench` harness (`benches/`, an external
/// crate) can measure it as `ui_plotstyle_layer_usage`.
pub fn build_layer_usage(document: &acadrust::CadDocument) -> Vec<Vec<String>> {
pub fn build_layer_usage(document: &codec::CadDocument) -> Vec<Vec<String>> {
let mut layer_usage = vec![Vec::<String>::new(); 256];
for layer in document.layers.iter() {
if let acadrust::types::Color::Index(aci) = &layer.color {
if let codec::types::Color::Index(aci) = &layer.color {
let index = *aci as usize;
if index > 0 && index < layer_usage.len() {
@@ -114,7 +114,7 @@ pub fn build_layer_usage(document: &acadrust::CadDocument) -> Vec<Vec<String>> {
}
pub fn view_window<'a>(
document: &'a acadrust::CadDocument,
document: &'a codec::CadDocument,
table: Option<&'a crate::io::plot_style::PlotStyleTable>,
selected_aci: u8,
color_buf: &'a str,
@@ -182,7 +182,7 @@ pub fn view_window<'a>(
String::new()
};
let (aci_color, _) = crate::ui::properties::acad_color_display(
acadrust::types::Color::Index(aci),
codec::types::Color::Index(aci),
);
let has_override = table
.and_then(|t| t.aci_entries.get(aci as usize))
@@ -379,14 +379,14 @@ pub fn view_window<'a>(
.strip_prefix('#')
.filter(|hex| hex.len() == 6)
.and_then(|hex| u32::from_str_radix(hex, 16).ok())
.map(|rgb| acadrust::types::Color::Rgb {
.map(|rgb| codec::types::Color::Rgb {
r: ((rgb >> 16) & 0xFF) as u8,
g: ((rgb >> 8) & 0xFF) as u8,
b: (rgb & 0xFF) as u8,
});
let display_color = selected_color
.unwrap_or(acadrust::types::Color::Index(selected_aci));
.unwrap_or(codec::types::Color::Index(selected_aci));
let (swatch_color, _) =
crate::ui::properties::acad_color_display(display_color);
@@ -559,19 +559,19 @@ mod layer_usage_tests {
use super::*;
fn indexed_layer(
doc: &mut acadrust::CadDocument,
doc: &mut codec::CadDocument,
name: &str,
aci: u8,
) -> acadrust::tables::Layer {
let mut layer = acadrust::tables::Layer::new(name);
) -> codec::tables::Layer {
let mut layer = codec::tables::Layer::new(name);
layer.handle = doc.allocate_handle();
layer.color = acadrust::types::Color::Index(aci);
layer.color = codec::types::Color::Index(aci);
layer
}
#[test]
fn build_layer_usage_buckets_index_colors() {
let mut doc = acadrust::CadDocument::new();
let mut doc = codec::CadDocument::new();
let a = indexed_layer(&mut doc, "WALLS", 1);
let b = indexed_layer(&mut doc, "doors", 1);
let c = indexed_layer(&mut doc, "ROOF", 3);
@@ -589,10 +589,10 @@ mod layer_usage_tests {
#[test]
fn build_layer_usage_ignores_non_index_colors() {
let mut doc = acadrust::CadDocument::new();
let mut truecolor = acadrust::tables::Layer::new("TRUECOLOR");
let mut doc = codec::CadDocument::new();
let mut truecolor = codec::tables::Layer::new("TRUECOLOR");
truecolor.handle = doc.allocate_handle();
truecolor.color = acadrust::types::Color::Rgb {
truecolor.color = codec::types::Color::Rgb {
r: 10,
g: 20,
b: 30,
+1 -1
View File
@@ -34,7 +34,7 @@ pub struct TableStyleView<'a> {
pub styles: Vec<String>,
pub selected: &'a str,
pub current: &'a str,
pub style: Option<&'a acadrust::objects::TableStyle>,
pub style: Option<&'a codec::objects::TableStyle>,
pub tab: u8,
pub compare_name: String,
pub compare_opts: Vec<String>,
+1 -1
View File
@@ -7,7 +7,7 @@
use std::collections::BTreeSet;
use std::fmt;
use acadrust::types::Handle;
use codec::types::Handle;
use iced::widget::{button, checkbox, column, container, pick_list, row, scrollable, text, text_input, Space};
use iced::{Border, Element, Fill, Length, Theme};
+2 -2
View File
@@ -14,8 +14,8 @@
//! edits, undo and repaint live in the update handler (`Message::AttrEditorApply`).
use crate::app::Message;
use acadrust::entities::{HorizontalAlignment, VerticalAlignment};
use acadrust::types::{Color as AcadColor, LineWeight};
use codec::entities::{HorizontalAlignment, VerticalAlignment};
use codec::types::{Color as AcadColor, LineWeight};
use iced::widget::{
button, checkbox, column, container, row, scrollable, text, text_input, Space,
};
+1 -1
View File
@@ -3,7 +3,7 @@
use std::fmt;
use acadrust::Handle;
use codec::Handle;
use iced::widget::{
button, checkbox, column, combo_box, container, mouse_area, pick_list, row, stack, text,
text_editor, text_input, Space,
+2 -2
View File
@@ -17,8 +17,8 @@
use crate::app::Message;
use crate::ui::dock::{DockMsg, PanelId};
use acadrust::objects::SolidHistoryOperation;
use acadrust::{CadDocument, EntityType, Handle};
use codec::objects::SolidHistoryOperation;
use codec::{CadDocument, EntityType, Handle};
use iced::widget::{button, column, container, mouse_area, row, scrollable, text, tooltip};
use iced::{Background, Border, Element, Fill, Length, Theme};
+1 -1
View File
@@ -7,7 +7,7 @@
use std::fmt;
use acadrust::Handle;
use codec::Handle;
use iced::widget::{button, checkbox, column, container, row, text, text_input, Space};
use iced::{Border, Element, Fill, Length, Theme};
+5 -5
View File
@@ -2,7 +2,7 @@
use crate::app::{LayerStateLayerFlag, LayerStateProperty, Message};
use crate::ui::properties::{lw_options, LwItem};
use acadrust::{LayerState, LayerStateMask};
use codec::{LayerState, LayerStateMask};
use iced::widget::{
button, checkbox, column, container, row, scrollable, text, text_input, Space,
};
@@ -12,7 +12,7 @@ use std::borrow::Cow;
use std::fmt;
#[derive(Clone, PartialEq, Debug)]
struct TransparencyItem(Option<acadrust::types::Transparency>);
struct TransparencyItem(Option<codec::types::Transparency>);
impl fmt::Display for TransparencyItem {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
@@ -23,11 +23,11 @@ impl fmt::Display for TransparencyItem {
}
}
fn transparency_options(current: Option<acadrust::types::Transparency>) -> Vec<TransparencyItem> {
fn transparency_options(current: Option<codec::types::Transparency>) -> Vec<TransparencyItem> {
let mut options = vec![TransparencyItem(None)];
for percent in (0..=90).step_by(10) {
options.push(TransparencyItem(Some(
acadrust::types::Transparency::from_percent(percent as f64 / 100.0),
codec::types::Transparency::from_percent(percent as f64 / 100.0),
)));
}
let current = TransparencyItem(current);
@@ -400,7 +400,7 @@ fn editor_header<'a>() -> Element<'a, Message> {
fn editor_layer_row<'a>(
index: usize,
layer: &'a acadrust::LayerStateLayer,
layer: &'a codec::LayerStateLayer,
color_open: bool,
linetypes: Vec<String>,
) -> Element<'a, Message> {
+5 -5
View File
@@ -4,11 +4,11 @@ use crate::app::Message;
use crate::ui::properties::{lw_options, LinetypeItem, LwItem};
use crate::ui::style::common::muted_style;
use crate::ui::ROW_H;
use acadrust::tables::layer::Layer as DocLayer;
use acadrust::tables::Table;
use acadrust::types::aci_table::aci_to_rgb;
use acadrust::types::{Color as AcadColor, LineWeight};
use acadrust::Handle;
use codec::tables::layer::Layer as DocLayer;
use codec::tables::Table;
use codec::types::aci_table::aci_to_rgb;
use codec::types::{Color as AcadColor, LineWeight};
use codec::Handle;
use iced::widget::{
button, column, combo_box, container, mouse_area, row, scrollable, text, text_input, tooltip,
};
+7 -7
View File
@@ -18,8 +18,8 @@ use crate::scene::named_parameters::ParameterTable;
use crate::scene::Scene;
use crate::t;
use crate::ui::style::common::muted_style;
use acadrust::types::Handle;
use acadrust::EntityType;
use codec::types::Handle;
use codec::EntityType;
use iced::widget::tooltip::Position as TipPos;
use iced::widget::{button, column, container, row, scrollable, text, text_input, tooltip, Space};
use iced::{Background, Element, Length, Theme};
@@ -392,10 +392,10 @@ mod tests {
ConstraintKind, ParametricRef, ParametricScope,
};
let mut scene = Scene::new();
let line = scene.add_entity(acadrust::EntityType::Line(
acadrust::entities::Line::from_points(
acadrust::types::Vector3::new(0.0, 0.0, 0.0),
acadrust::types::Vector3::new(10.0, 0.0, 0.0),
let line = scene.add_entity(codec::EntityType::Line(
codec::entities::Line::from_points(
codec::types::Vector3::new(0.0, 0.0, 0.0),
codec::types::Vector3::new(10.0, 0.0, 0.0),
),
));
scene
@@ -426,7 +426,7 @@ mod tests {
#[test]
fn entity_label_reports_erased_for_a_dangling_handle() {
let scene = Scene::new();
let label = entity_label(&scene, acadrust::types::Handle::new(999));
let label = entity_label(&scene, codec::types::Handle::new(999));
assert!(label.starts_with("(erased "), "got {label}");
}
}
+1 -1
View File
@@ -526,7 +526,7 @@ pub fn view_attach<'a>(
#[derive(Clone)]
pub struct LayerTarget {
pub name: String,
pub handle: acadrust::Handle,
pub handle: codec::Handle,
pub layers: Vec<String>,
pub hidden: Vec<String>,
}
+3 -3
View File
@@ -158,13 +158,13 @@ pub struct PageSetupImportDraft {
pub file: String,
/// Each setup with whether it is ticked for import. The settings are
/// carried along so the source file is read once.
pub setups: Vec<(String, acadrust::objects::PlotSettings, bool)>,
pub setups: Vec<(String, codec::objects::PlotSettings, bool)>,
/// Why the file gave nothing, when it did not.
pub error: Option<String>,
}
impl PageSetupImportDraft {
pub fn selected(&self) -> impl Iterator<Item = (&str, &acadrust::objects::PlotSettings)> {
pub fn selected(&self) -> impl Iterator<Item = (&str, &codec::objects::PlotSettings)> {
self.setups
.iter()
.filter(|(_, _, on)| *on)
@@ -178,7 +178,7 @@ pub enum PageSetupImportMsg {
/// Ask for the drawing to import from.
Pick,
/// The drawing was read (or could not be): its name and page setups.
Loaded(Result<(String, Vec<(String, acadrust::objects::PlotSettings)>), String>),
Loaded(Result<(String, Vec<(String, codec::objects::PlotSettings)>), String>),
/// Tick or untick one setup.
Toggle(String),
/// Tick or untick every setup.
+2 -2
View File
@@ -1033,7 +1033,7 @@ mod tests {
tag: "v1.4.0".to_string(),
api_version: 4,
acadrust_source: Some(
"git+https://github.com/HakanSeven12/cadcodec.git?rev=94df2c3#94df2c3f87fa051b16ffc3923f80e9247c85c5fd".to_string(),
"git+https://github.com/HakanSeven12/opencadcodec.git?rev=94df2c3#94df2c3f87fa051b16ffc3923f80e9247c85c5fd".to_string(),
),
acadrust_declared: true,
acadrust_compatible: true,
@@ -1045,7 +1045,7 @@ mod tests {
tag: "v2.0.0".to_string(),
api_version: 4,
acadrust_source: Some(
"git+https://github.com/HakanSeven12/cadcodec.git?rev=0908da7#0908da7b6e4f702a6c78359a57f53e2b79cf39eb".to_string(),
"git+https://github.com/HakanSeven12/opencadcodec.git?rev=0908da7#0908da7b6e4f702a6c78359a57f53e2b79cf39eb".to_string(),
),
acadrust_declared: true,
acadrust_compatible: false,
+1 -1
View File
@@ -2,7 +2,7 @@
use std::fmt;
use acadrust::Handle;
use codec::Handle;
use iced::widget::{
button, column, combo_box, container, pick_list, row, text, text_input, Space,
};
+23 -23
View File
@@ -10,7 +10,7 @@ use crate::io::xref::collect_entries_with_prev;
use crate::io::xref_model::{normalize_lexical, Pathtype, RefKind, RefStatus, RefType, ReferenceEntry};
use crate::ui::ROW_H;
use crate::ui::style::common::muted_style;
use acadrust::CadDocument;
use codec::CadDocument;
use iced::widget::{button, column, container, mouse_area, row, scrollable, text, tooltip};
use iced::Padding;
use iced::{Background, Border, Element, Fill, Length, Theme};
@@ -1135,8 +1135,8 @@ impl XrefManagerPanel {
/// directly — mirrors the three [`collect_entries`] scans so nested entries
/// (foreign handles) classify correctly even on handle collisions.
fn direct_identities(doc: &CadDocument) -> HashSet<(u64, String)> {
use acadrust::entities::UnderlayType;
use acadrust::objects::ObjectType;
use codec::entities::UnderlayType;
use codec::objects::ObjectType;
let mut ids: HashSet<(u64, String)> = HashSet::new();
for br in doc.block_records.iter() {
@@ -2175,17 +2175,17 @@ fn reference_preview(entry: &ReferenceEntry) -> Option<image::RgbaImage> {
fn find_image_def(
doc: &CadDocument,
key: u64,
) -> Option<&acadrust::objects::ImageDefinition> {
doc.objects.get(&acadrust::types::Handle::from(key)).and_then(|o| match o {
acadrust::objects::ObjectType::ImageDefinition(def) => Some(def),
) -> Option<&codec::objects::ImageDefinition> {
doc.objects.get(&codec::types::Handle::from(key)).and_then(|o| match o {
codec::objects::ObjectType::ImageDefinition(def) => Some(def),
_ => None,
})
}
fn find_image_display_size(doc: &CadDocument, key: u64) -> Option<(f64, f64)> {
let handle = acadrust::types::Handle::from(key);
let handle = codec::types::Handle::from(key);
for entity in doc.entities() {
if let acadrust::EntityType::RasterImage(img) = entity {
if let codec::EntityType::RasterImage(img) = entity {
if img.definition_handle == Some(handle) {
let w = (img.u_vector.x.powi(2) + img.u_vector.y.powi(2) + img.u_vector.z.powi(2)).sqrt();
let h = (img.v_vector.x.powi(2) + img.v_vector.y.powi(2) + img.v_vector.z.powi(2)).sqrt();
@@ -2442,10 +2442,10 @@ mod tests {
assert!(!panel.display_rows().iter().any(|r| r.is_nested));
}
fn preview_doc2(dir: &std::path::Path) -> acadrust::CadDocument {
fn preview_doc2(dir: &std::path::Path) -> codec::CadDocument {
// Two referenced images → genuine multi-select.
use acadrust::objects::{ImageDefinition, ObjectType};
let mut doc = acadrust::CadDocument::new();
use codec::objects::{ImageDefinition, ObjectType};
let mut doc = codec::CadDocument::new();
for (i, name) in ["a.png", "b.png"].iter().enumerate() {
let img = image::RgbaImage::from_pixel(8, 8, image::Rgba([9, 9, 9, 255]));
img.save(dir.join(name)).unwrap();
@@ -2454,37 +2454,37 @@ mod tests {
let mut def = ImageDefinition::with_dimensions(path.clone(), 8, 8);
def.handle = h;
doc.objects.insert(h, ObjectType::ImageDefinition(def));
let mut ent = acadrust::entities::RasterImage::new(
let mut ent = codec::entities::RasterImage::new(
&path,
acadrust::types::Vector3::ZERO,
codec::types::Vector3::ZERO,
8.0 + i as f64,
8.0,
);
ent.definition_handle = Some(h);
doc.add_entity(acadrust::EntityType::RasterImage(ent)).unwrap();
doc.add_entity(codec::EntityType::RasterImage(ent)).unwrap();
}
doc
}
fn preview_doc(dir: &std::path::Path, name: &str) -> acadrust::CadDocument {
fn preview_doc(dir: &std::path::Path, name: &str) -> codec::CadDocument {
// Referenced 8x8 PNG under `dir`; the entry resolves Loaded.
use acadrust::objects::{ImageDefinition, ObjectType};
use codec::objects::{ImageDefinition, ObjectType};
let img = image::RgbaImage::from_pixel(8, 8, image::Rgba([9, 9, 9, 255]));
img.save(dir.join(name)).unwrap();
let img_path = dir.join(name).to_string_lossy().into_owned();
let mut doc = acadrust::CadDocument::new();
let mut doc = codec::CadDocument::new();
let h = doc.allocate_handle();
let mut def = ImageDefinition::with_dimensions(img_path.clone(), 8, 8);
def.handle = h;
doc.objects.insert(h, ObjectType::ImageDefinition(def));
let mut ent = acadrust::entities::RasterImage::new(
let mut ent = codec::entities::RasterImage::new(
&img_path,
acadrust::types::Vector3::ZERO,
codec::types::Vector3::ZERO,
8.0,
8.0,
);
ent.definition_handle = Some(h);
doc.add_entity(acadrust::EntityType::RasterImage(ent)).unwrap();
doc.add_entity(codec::EntityType::RasterImage(ent)).unwrap();
doc
}
@@ -2558,8 +2558,8 @@ mod tests {
));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("plan.dwg"), b"not-a-real-dwg").unwrap();
let mut doc = acadrust::CadDocument::new();
let mut br = acadrust::tables::BlockRecord::new("PLAN");
let mut doc = codec::CadDocument::new();
let mut br = codec::tables::BlockRecord::new("PLAN");
br.flags.is_xref = true;
br.xref_path = dir.join("plan.dwg").to_string_lossy().into_owned();
br.handle = doc.allocate_handle();
@@ -2596,7 +2596,7 @@ mod tests {
.objects
.iter()
.find_map(|(h, o)| match o {
acadrust::objects::ObjectType::ImageDefinition(_) => Some(h.value()),
codec::objects::ObjectType::ImageDefinition(_) => Some(h.value()),
_ => None,
})
.unwrap();