Compare commits

..
28 Commits
Author SHA1 Message Date
Tanish Manku 9d6f82dc9f Merge pull request #3422 from storytold/land/899
Land #899: opening a drawing that is already open selects its tab
2026-11-23 13:10:06 -07:00
Tanish Manku e811a5183e Merge pull request #3421 from storytold/stack/i1
Land #2235, #2898, #2900, #3260, #2901: French, Arabic, Georgian and Swedish catalog updates
2026-11-23 13:09:55 -07:00
Tanish Manku 223314c8eb Merge #899: Reuse existing drawing tabs when reopening paths 2026-11-23 12:49:15 -07:00
Tanish Manku 7b8ca63926 Arabic catalog test: check the words themselves, so it fails on the old catalog and on a missing row 2026-11-23 12:48:57 -07:00
Tanish Manku 7506ffc83d Merge #2901: i18n(sv): translate 705 new strings 2026-11-23 12:46:26 -07:00
Tanish Manku 9254277db3 Merge #3260: i18n(ka): update the Georgian catalog (33 strings) 2026-11-23 12:46:24 -07:00
Tanish Manku 3a4cf04b76 Merge #2900: i18n(ka): Georgian for 20 new strings 2026-11-23 12:46:23 -07:00
Tanish Manku 61b420cfbe Merge #2898: i18n(ar): tell Trim, Stretch and Extend apart, and call Point a point 2026-11-23 12:46:21 -07:00
Tanish Manku 59f27fb38c Merge #2235: i18n(fr): consistent French CAD terminology in existing rows 2026-11-23 12:46:19 -07:00
Patrik LermonandClaude Opus 5.5 8725cc48b2 i18n(sv): translate 172 new strings
Brings the Swedish catalog up to date with upstream main (a770fa5a).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 10:21:05 +01:00
Patrik Lermon a4364499d4 Merge upstream/main into swedish-ui-2026-11-07 2026-11-19 09:59:44 +01:00
Davit Matchakhelidze 6fb27ffa9e Merge origin/main into ka-update-2026-11-07 2026-11-18 15:06:41 +04:00
Davit Matchakhelidze b84f6a8994 i18n(ka): leave the rows of #2900 to that PR 2026-11-18 04:55:22 +04:00
Davit Matchakhelidze a0f3f25760 i18n(ka): update the Georgian catalog 2026-11-18 04:54:20 +04:00
markmonkey 9b05dbed43 Reuse existing drawing tabs when reopening paths 2026-11-16 11:16:11 +08:00
SoldierPePe 59d5d20ab2 Merge remote-tracking branch 'origin/main' into i18n/ar-trim-stretch-point
# Conflicts:
#	crates/ui-egui/src/i18n/tests.rs
2026-11-16 02:02:48 +03:00
Patrik LermonandClaude Opus 5.5 32d5bd85db i18n(sv): update the Swedish catalog
Brings the Swedish catalog up to date with upstream main (7064a685).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 15:46:19 +01:00
Patrik Lermon a684cd506d Merge upstream/main into swedish-ui-2026-11-07 2026-11-15 15:34:55 +01:00
Davit Matchakhelidze b4ca4fd2b0 Merge origin/main into ka-update-2026-11-07 2026-11-14 20:36:13 +04:00
YannFR81 6ac52455d9 i18n(fr): credit the terminology review in the catalog header 2026-11-11 23:30:10 +01:00
YannFR81 4e482cf617 i18n(fr): align four shared rows with #2580
Dimension Space, Dimension Style Override and Object Snap Tracking (with its
F11 variant) are also changed by #2580. Use one wording in both pull requests
so they merge in either order:

- Dimension Space: "Espacer les cotes" (menu labels keep the infinitive)
- Dimension Style Override: "Remplacement de style de cote"
- Object Snap Tracking: "Repérage d'accrochage aux objets", as #2102 already
  uses for Object Snap Tracking Settings
2026-11-11 18:26:14 +01:00
YannFR81andClaude Opus 5.5 c17cbc9c73 i18n(fr): consistent French CAD terminology in existing rows
Follow-up to the French catalog: harmonises rows already on main, without
touching the rows added by #2102.

- Command-line prompts use the imperative (Sélectionnez, Spécifiez, Entrez),
  as the other prompts already did; menu and button labels keep the infinitive.
- A dimension object and its style are "cote" / "style de cote"; "Cotation"
  stays for the Dimension menu and Quick Dimension.
- Model space is "espace objet", Array is "réseau", a layout is a
  "présentation", tracking is "repérage" (object snap and polar).

Rebased on main after #2563: the prompts that lost their trailing "or" keep
the imperative wording on their new keys. The docs/localization-parity.md
row is left to the maintainers, as AGENTS.md asks.

Original wording written from CADCraft's English strings; no proprietary
localization resources were used.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01C4cGqxCFJD1m28x2aqwf7Q
2026-11-11 18:22:47 +01:00
Davit Matchakhelidze 0e40437d8f i18n(ka): Export = ექსპორტირება, Print = ბეჭდვა (the wording used across the Craft apps) 2026-11-11 02:06:36 +04:00
SoldierPePe 410bdc733f i18n(ar): test that Stretch, Trim and Point keep words of their own 2026-11-08 07:24:34 +03:00
Patrik LermonandClaude Opus 5.5 2dd428dc2d i18n(sv): translate 41 new strings
Brings the Swedish catalog up to date with upstream main (865fa9af).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 08:48:19 +01:00
SoldierPePe 17da6ab38a i18n(ar): call Stretch «تمطيط», in the same form as the other edit verbs 2026-11-07 10:29:56 +03:00
SoldierPePe 53cebb9020 i18n(ar): tell Trim, Stretch and Extend apart, and call Point a point
Trim read «حدود التشذيب» ("trim boundaries"), Stretch read «تمديد», the
same word as Extend, and Point read «تأشير», the word the catalog uses
for Dimension. Trim is now «تشذيب», and its two selection prompts match
it (they said «قص», which is also Cut). Stretch, its grip and vertex
items and its selection prompt use «مط». Point is «نقطة», as in Point
Style and Single Point. Written from the meaning of the English strings.
2026-11-07 10:14:07 +03:00
Davit MatchakhelidzeandClaude Sonnet 5.5 9eb81b3588 i18n(ka): Georgian for 20 new strings
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 03:01:02 +04:00
39 changed files with 1374 additions and 6031 deletions
+1 -1
View File
@@ -72,7 +72,7 @@ Generated-in-code assets are original and have no file to list:
| `crates/ui-egui/src/i18n/bs.tsv` | Nine (@nine-codes) with Claude Code (AI-assisted) | Original Bosnian translations of CADCraft English strings, shared with storytold/craft-i18n `locales/bs/` | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; not yet reviewed by a native speaker |
| `crates/ui-egui/src/i18n/cs.tsv` | @Losminek (AI-assisted) | Original Czech translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/ru.tsv` | @pechnikov2026-star | Original Russian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/fr.tsv` | @pechnikov2026-star | Original French translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/fr.tsv` | @pechnikov2026-star; terminology pass by @YannFR81 | Original French translations of CADCraft English strings; AI-assisted consistency pass (imperative prompts, cote/espace objet/réseau/présentation) | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/zh.tsv` | @mayloglog | Original Simplified Chinese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/sv.tsv` | Erik Holmbom (@holmbom) with Claude Code (AI-assisted) | Original Swedish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology and the running app reviewed by a native speaker |
| `crates/ui-egui/src/i18n/it.tsv` | Emanuele Bottelli (AI-assisted); terminology corrections: Andrea Brandi (@starise) with OpenAI Codex (AI-assisted) | Original Italian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; targeted Chamfer terminology review by a native speaker |
+47 -246
View File
@@ -22,7 +22,7 @@ use crate::{Drawing, Handle, RawTag};
mod apply;
mod grips;
mod reference;
pub use apply::{align_grip, drag_grip, grip_stops, set_property};
pub use apply::{drag_grip, set_property};
pub use grips::{DynGrip, GripPart, GripShape, grips};
pub use reference::{CustomProperty, Reference, Value, custom_properties, reference};
@@ -52,13 +52,6 @@ pub struct DynamicBlock {
/// the grips shown in them by object).
#[serde(skip)]
pub grip_objects: Vec<(i32, Handle)>,
/// Where each grip object is in the dynamic block, by graph id (a flip grip's place along its
/// reflection line).
#[serde(skip)]
pub grip_points: Vec<(i32, Vec3)>,
/// The block's base point (where a base point parameter is in the block).
#[serde(skip)]
pub base: Vec3,
}
/// One parameter: a property a reference to the block can change.
@@ -94,41 +87,16 @@ pub enum ParameterKind {
/// The value changes the end point (`false`) or both points from the midpoint (`true`).
from_midpoint: bool,
},
/// A distance and an angle from a base point (Distance1, Angle1): the end point's distance
/// from the base and its direction (counterclockwise from the X axis of the block).
Polar {
base: Vec3,
end: Vec3,
label: String,
description: String,
angle_label: String,
angle_description: String,
values: ValueSet,
angle_values: ValueSet,
},
/// Horizontal and vertical distances from a base point (X Distance1, Y Distance1): how far
/// the end point is from the base along the block's X and Y axes.
Xy {
base: Vec3,
end: Vec3,
x_label: String,
y_label: String,
x_description: String,
y_description: String,
x_values: ValueSet,
y_values: ValueSet,
},
/// An angle about a base point (Angle1): the end point turns about the base. The angle is
/// measured from the direction the dynamic block has from base to end.
Rotation { base: Vec3, end: Vec3, label: String, description: String, values: ValueSet },
/// Aligns the reference with nearby geometry: dragged next to an object, its base point lands
/// on the object and the direction from base to end runs along it. `perpendicular` is the
/// parameter's type (perpendicular, else tangent); AutoCAD aligned both types the same way in
/// every case measured.
Alignment { base: Vec3, end: Vec3, perpendicular: bool },
/// Mirrors the objects about the reflection line from base to end (Flip state1); the names
/// of its two states, not flipped and flipped.
Flip { base: Vec3, end: Vec3, label: String, description: String, states: [String; 2] },
/// A distance and an angle from a base point.
Polar { base: Vec3, end: Vec3 },
/// Horizontal and vertical distances from a base point.
Xy { base: Vec3, end: Vec3 },
/// An angle about a base point.
Rotation { base: Vec3, end: Vec3 },
/// Aligns the reference with nearby geometry.
Alignment { base: Vec3, end: Vec3 },
/// Mirrors the objects about a reflection line.
Flip { base: Vec3, end: Vec3 },
/// A position (Position1).
Point { at: Vec3, label: String, description: String },
/// Named sets of visible objects.
@@ -142,9 +110,7 @@ pub enum ParameterKind {
},
/// A named value chosen from a lookup table.
Lookup { at: Vec3, label: String, description: String },
/// The block's base point: the reference's insertion point is here, and an action that moves
/// it moves the reference's insertion point. `at` is where the block editor showed it; the
/// block itself has it at its base point (AutoCAD moves the block's objects to put it there).
/// Moves the block's base point.
BasePoint { at: Vec3 },
/// A parameter type not modelled yet.
Other { dxf_type: String },
@@ -156,23 +122,11 @@ impl ParameterKind {
match self {
ParameterKind::Linear { label, .. }
| ParameterKind::Point { label, .. }
| ParameterKind::Rotation { label, .. }
| ParameterKind::Flip { label, .. }
| ParameterKind::Visibility { label, .. }
| ParameterKind::Lookup { label, .. } => Some(label),
_ => None,
}
}
/// Every property name a reference shows for the parameter: a polar parameter's distance
/// and angle, an XY parameter's two distances, else its one label.
pub fn labels(&self) -> Vec<&str> {
match self {
ParameterKind::Polar { label, angle_label, .. } => vec![label, angle_label],
ParameterKind::Xy { x_label, y_label, .. } => vec![x_label, y_label],
other => other.label().into_iter().collect(),
}
}
}
/// One visibility state: its name and the objects shown in it (the parameter's other controlled
@@ -251,46 +205,24 @@ pub enum ActionKind {
angle_offset: f64,
},
/// A table: each row sets the listed parameter values together.
Lookup { columns: Vec<LookupColumn>, rows: Vec<Vec<String>> },
Lookup {
columns: Vec<LookupColumn>,
rows: Vec<Vec<String>>,
},
/// Moves the objects by the change of the parameter values it follows.
Move { multiplier: f64, angle_offset: f64 },
/// Scales the objects about its base point by how much the distance it follows grew (a linear
/// or polar parameter's distance, an XY parameter's diagonal). Its connections name what each
/// reads ("Scale", "XScale", "YScale").
Scale { base: ActionBase },
/// Turns the objects about its base point by the change of a rotation parameter's angle.
Rotate { base: ActionBase },
/// Mirrors the objects across a flip parameter's reflection line when its state changes.
Flip,
/// Repeats the objects as far as the parameter it follows reaches: along a distance (linear
/// or polar parameter) every `column` units, or in a grid of columns and rows across an XY
/// parameter's distances. The objects follow the parameter's base point.
Array { column: f64, row: f64 },
/// Follows a polar parameter: turns its objects about the parameter's base point by the change
/// of its angle, and moves the vertices inside `frame` of the objects listed (all of an object
/// not listed) along the parameter's new direction by the change of its distance. The
/// `rotate_only` objects (outside the selection) only turn.
PolarStretch {
frame: Vec<Vec2>,
#[serde(serialize_with = "hex_vertices")]
vertices: Vec<(Handle, Vec<i32>)>,
#[serde(serialize_with = "hexes")]
rotate_only: Vec<Handle>,
Move {
multiplier: f64,
angle_offset: f64,
},
Scale,
Rotate,
Flip,
Array,
PolarStretch,
/// An action type not modelled yet.
Other { dxf_type: String },
}
/// Where an action that turns or scales its objects has its base point.
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ActionBase {
/// It follows the parameter's base point, at `offset` from it; else it stays at `at`.
pub dependent: bool,
pub offset: Vec3,
pub at: Vec3,
Other {
dxf_type: String,
},
}
/// A lookup table column: the parameter value it reads or sets.
@@ -451,7 +383,7 @@ pub fn is_dynamic_block_in(d: &Drawing, objects: &ObjectIndex<'_>, name: &str) -
/// [`dynamic_block`] with the drawing's [`ObjectIndex`] already built.
pub fn dynamic_block_in(d: &Drawing, objects: &ObjectIndex<'_>, name: &str) -> Option<DynamicBlock> {
let xdict = block_xdict(d, name)?;
let mut out = DynamicBlock { base: d.block(name.trim()).map(|b| b.base).unwrap_or_default(), ..Default::default() };
let mut out = DynamicBlock::default();
for o in graph_members(&objects.0, xdict)? {
let secs = sections(&o.tags);
let node = Cursor::new(section(&secs, "AcDbEvalExpr")).int(90);
@@ -466,7 +398,6 @@ pub fn dynamic_block_in(d: &Drawing, objects: &ObjectIndex<'_>, name: &str) -> O
} else {
if kind.ends_with("GRIP") {
out.grip_objects.push((node, o.handle));
out.grip_points.push((node, Cursor::new(section(&secs, "AcDbBlockGrip")).point(1010)));
}
out.other.push(o.kind.clone());
}
@@ -475,21 +406,15 @@ pub fn dynamic_block_in(d: &Drawing, objects: &ObjectIndex<'_>, name: &str) -> O
}
/// A parameter's grip ids: after a two-point parameter's points, the grip count (170) and the
/// base and end grips (91), then an XY parameter's corner grips (base X and end Y, base Y and end
/// X); after a one-point parameter's point, its grip (93).
/// base and end grips (91); after a one-point parameter's point, its grip (93).
fn grip_ids(secs: &[(&str, &[RawTag])]) -> Vec<i32> {
let two = section(secs, "AcDbBlock2PtParameter");
if !two.is_empty() {
let mut c = Cursor::new(two);
c.point(1010);
c.point(1011);
let n = c.count(170).min(4);
let mut ids: Vec<i32> = (0..n).map(|_| c.int(91)).collect();
// Corner grips only an XY parameter has (the others write 0 for them).
while ids.len() > 2 && ids.last() == Some(&0) {
ids.pop();
}
return ids;
let n = c.count(170).min(2);
return (0..n).map(|_| c.int(91)).collect();
}
let mut c = Cursor::new(section(secs, "AcDbBlock1PtParameter"));
c.point(1010);
@@ -521,49 +446,15 @@ fn parameter(kind: &str, secs: &[(&str, &[RawTag])]) -> ParameterKind {
ParameterKind::Lookup { at: one(), label: c.string(303), description: c.string(304) }
}
"BLOCKBASEPOINTPARAMETER" => ParameterKind::BasePoint { at: one() },
// Its name and description (305, 306), the base angle point (1011) and angle (140), then
// the value set.
"BLOCKROTATIONPARAMETER" => {
"BLOCKPOLARPARAMETER" | "BLOCKXYPARAMETER" | "BLOCKROTATIONPARAMETER" | "BLOCKALIGNMENTPARAMETER" | "BLOCKFLIPPARAMETER" => {
let (base, end) = two();
let mut c = Cursor::new(section(secs, "AcDbBlockRotationParameter"));
let (label, description) = (c.string(305), c.string(306));
ParameterKind::Rotation { base, end, label, description, values: value_set(&mut c) }
}
// Its name and description (305, 306) and its states' names (307 not flipped, 308 flipped).
"BLOCKFLIPPARAMETER" => {
let (base, end) = two();
let mut c = Cursor::new(section(secs, "AcDbBlockFlipParameter"));
let (label, description) = (c.string(305), c.string(306));
let states = [c.string(307), c.string(308)];
ParameterKind::Flip { base, end, label, description, states }
}
// The distance's name and description (305, 306), the angle's (307, 308), the label
// offset (140), then the distance's value set (309, 96, 141–144, 175) and the angle's
// (410, 97, 145–148, 176).
"BLOCKPOLARPARAMETER" => {
let (base, end) = two();
let mut c = Cursor::new(section(secs, "AcDbBlockPolarParameter"));
let (label, description, angle_label, angle_description) = (c.string(305), c.string(306), c.string(307), c.string(308));
let values = value_set_at(&mut c, [309, 96, 141, 175]);
let angle_values = value_set_at(&mut c, [410, 97, 145, 176]);
ParameterKind::Polar { base, end, label, description, angle_label, angle_description, values, angle_values }
}
// The vertical distance's name (305) before the horizontal's (306), then their
// descriptions (307, 308), label offsets (141, 140), the vertical value set (309, 97,
// 146–149, 176) and the horizontal one (410, 96, 142–145, 175).
"BLOCKXYPARAMETER" => {
let (base, end) = two();
let mut c = Cursor::new(section(secs, "AcDbBlockXYParameter"));
let (y_label, x_label, y_description, x_description) = (c.string(305), c.string(306), c.string(307), c.string(308));
let y_values = value_set_at(&mut c, [309, 97, 146, 176]);
let x_values = value_set_at(&mut c, [410, 96, 142, 175]);
ParameterKind::Xy { base, end, x_label, y_label, x_description, y_description, x_values, y_values }
}
// Its type (280): 1 perpendicular, 0 tangent.
"BLOCKALIGNMENTPARAMETER" => {
let (base, end) = two();
let perpendicular = Cursor::new(section(secs, "AcDbBlockAlignmentParameter")).int(280) != 0;
ParameterKind::Alignment { base, end, perpendicular }
match kind {
"BLOCKPOLARPARAMETER" => ParameterKind::Polar { base, end },
"BLOCKXYPARAMETER" => ParameterKind::Xy { base, end },
"BLOCKROTATIONPARAMETER" => ParameterKind::Rotation { base, end },
"BLOCKALIGNMENTPARAMETER" => ParameterKind::Alignment { base, end },
_ => ParameterKind::Flip { base, end },
}
}
other => ParameterKind::Other { dxf_type: other.to_string() },
}
@@ -572,17 +463,11 @@ fn parameter(kind: &str, secs: &[(&str, &[RawTag])]) -> ParameterKind {
/// A value set after a parameter's name and description: description (307), flags (96),
/// minimum, maximum and increment (141–143), then the listed values (175 count, 144 each).
fn value_set(c: &mut Cursor) -> ValueSet {
value_set_at(c, [307, 96, 141, 175])
}
/// A value set written with codes `[description, flags, minimum, count]`: the maximum and
/// increment follow the minimum's code, each listed value is the code after the increment's.
fn value_set_at(c: &mut Cursor, [description, flags, min, count]: [i32; 4]) -> ValueSet {
c.next(description);
let flags = c.int(flags);
let (minimum, maximum, increment) = (c.real(min), c.real(min + 1), c.real(min + 2));
let n = c.count(count);
let list = (0..n).filter_map(|_| c.next(min + 3).and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| v.is_finite())).collect();
c.next(307);
let flags = c.int(96);
let (minimum, maximum, increment) = (c.real(141), c.real(142), c.real(143));
let n = c.count(175);
let list = (0..n).filter_map(|_| c.next(144).and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| v.is_finite())).collect();
ValueSet { flags, minimum, maximum, increment, list }
}
@@ -622,56 +507,16 @@ fn action(handle: Handle, node: i32, name: String, kind: &str, secs: &[(&str, &[
let (multiplier, angle_offset) = (c.real(140), c.real(141));
(two_connections(tags), ActionKind::Move { multiplier, angle_offset })
}
// The base point's two connections (as a rotate action's), then the scale's three: the
// parameters (94-96) and what each reads (303-305, "Scale", "XScale", "YScale").
"BLOCKSCALEACTION" => {
let with_base = section(secs, "AcDbBlockActionWithBasePt");
let mut connections = two_connections(with_base);
let tags = section(secs, "AcDbBlockScaleAction");
let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string();
connections.extend((0..3).map(|i| (first(94 + i).trim().parse().unwrap_or(0), first(303 + i))));
(connections, ActionKind::Scale { base: action_base(with_base) })
}
"BLOCKROTATEACTION" => {
let mut connections = two_connections(section(secs, "AcDbBlockActionWithBasePt"));
let mut c = Cursor::new(section(secs, "AcDbBlockRotationAction"));
connections.push((c.int(94), c.string(303)));
(connections, ActionKind::Rotate { base: action_base(section(secs, "AcDbBlockActionWithBasePt")) })
}
// Its four connections: the parameter (92-95) and the values it reads (301-304).
"BLOCKFLIPACTION" => {
let tags = section(secs, "AcDbBlockFlipAction");
let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string();
let connections = (0..4).map(|i| (first(92 + i).trim().parse().unwrap_or(0), first(301 + i))).collect();
(connections, ActionKind::Flip)
}
// Its four connections (92-95 with 301-304, as a flip action's), then the row (140) and
// column (141) offsets.
"BLOCKARRAYACTION" => {
let tags = section(secs, "AcDbBlockArrayAction");
let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string();
let connections = (0..4).map(|i| (first(92 + i).trim().parse().unwrap_or(0), first(301 + i))).collect();
let mut c = Cursor::new(tags);
let (row, column) = (c.real(140), c.real(141));
(connections, ActionKind::Array { column, row })
}
"BLOCKPOLARSTRETCHACTION" => polar_stretch(section(secs, "AcDbBlockPolarStretchAction")),
"BLOCKSCALEACTION" => (Vec::new(), ActionKind::Scale),
"BLOCKROTATEACTION" => (Vec::new(), ActionKind::Rotate),
"BLOCKFLIPACTION" => (Vec::new(), ActionKind::Flip),
"BLOCKARRAYACTION" => (Vec::new(), ActionKind::Array),
"BLOCKPOLARSTRETCHACTION" => (Vec::new(), ActionKind::PolarStretch),
other => (Vec::new(), ActionKind::Other { dxf_type: other.to_string() }),
};
Action { node, handle, name, at, selection, connections, kind }
}
/// The base point of an action that has one: after its two connections (92/93, 301/302), the
/// offset from the parameter's base point (1011), whether it follows that point (280), and the
/// point it stays at when it doesn't (1012).
fn action_base(tags: &[RawTag]) -> ActionBase {
let mut c = Cursor::new(tags);
c.next(302);
let offset = c.point(1011);
let dependent = c.int(280) != 0;
ActionBase { dependent, offset, at: c.point(1012) }
}
/// Two connections: parameter ids (92, 93) and the values they read (301, 302). Writers order
/// these groups differently (92 93 301 302, or 92 301 93 302), so each is read on its own.
fn two_connections(tags: &[RawTag]) -> Vec<(i32, String)> {
@@ -706,42 +551,6 @@ fn stretch(tags: &[RawTag]) -> (Vec<(i32, String)>, ActionKind) {
(connections, ActionKind::Stretch { frame, vertices, multiplier, angle_offset })
}
/// A polar stretch action: its six connections (92-97 with 301-306), the frame (73 count,
/// 1011/1021 points), the objects it only turns (72 count, 331 each), the objects whose vertices it
/// moves (74 count; each a 332 handle, a 75 count and 76 vertex indices), more vertex lists (78
/// count; each a 98 code, a 79 count and 76 indices), then the distance multiplier (141) and angle
/// offset (140).
fn polar_stretch(tags: &[RawTag]) -> (Vec<(i32, String)>, ActionKind) {
let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string();
let connections = (0..6).map(|i| (first(92 + i).trim().parse().unwrap_or(0), first(301 + i))).collect();
let mut c = Cursor::new(tags);
let n = c.count(73);
let frame = (0..n)
.map(|_| {
let x = c.real(1011);
Vec2::new(x, c.real(1021))
})
.collect();
let n = c.count(72);
let rotate_only = c.handles(331, n);
let objects = c.count(74);
let vertices = (0..objects)
.filter_map(|_| {
let h = c.handle(332)?;
let n = c.count(75);
Some((h, (0..n).map(|_| c.int(76)).collect()))
})
.collect();
for _ in 0..c.count(78) {
c.next(98);
for _ in 0..c.count(79) {
c.next(76);
}
}
let (multiplier, angle_offset) = (c.real(141), c.real(140));
(connections, ActionKind::PolarStretch { frame, vertices, rotate_only, multiplier, angle_offset })
}
/// A lookup table: rows (92) and columns (93), the cells row by row (302, after a 301 header),
/// then each column: unmatched name (303 then 305), parameter id (94), lookup flag (282) and the
/// parameter value it stands for (304).
@@ -789,13 +598,5 @@ mod tests {
let (_, ActionKind::Stretch { vertices, .. }) = stretch(&tags) else { panic!("a stretch action") };
let ints: usize = vertices.iter().map(|(_, v)| v.len()).sum();
assert!(ints <= 16 * tags.len() + 1024, "{ints}");
let mut tags = vec![tag(74, &n.to_string())];
tags.extend((0..n).flat_map(|_| [tag(332, "1F"), tag(75, &n.to_string())]));
tags.push(tag(78, &n.to_string()));
tags.extend((0..n).map(|_| tag(79, &n.to_string())));
let (_, ActionKind::PolarStretch { vertices, .. }) = polar_stretch(&tags) else { panic!("a polar stretch action") };
let ints: usize = vertices.iter().map(|(_, v)| v.len()).sum();
assert!(ints <= 16 * tags.len() + 1024, "{ints}");
}
}
File diff suppressed because it is too large Load Diff
+3 -151
View File
@@ -1,11 +1,7 @@
//! The grips of a dynamic block reference, as AutoCAD shows them on a selected reference: an
//! arrow at each end of a distance (linear parameter), a square at a position (point parameter),
//! a circle at the end of an angle (rotation parameter), a flip arrow across a reflection line
//! (flip parameter), a down-pointing triangle for a list (visibility states, lookup values) and a
//! pentagon pointing across the alignment direction at an alignment's base point (alignment
//! parameter; dragged next to an object it aligns the reference with it, [`super::align_grip`]).
//! Dragging an arrow, square or circle is [`super::drag_grip`]; a flip grip flips at a click; a
//! list grip offers its property's choices.
//! arrow at each end of a distance (linear parameter), a square at a position (point parameter)
//! and a down-pointing triangle for a list (visibility states, lookup values). Dragging an arrow
//! or square is [`super::drag_grip`]; a list grip offers its property's choices.
//!
//! With a visibility parameter, a state lists the grips shown in it; the others are hidden.
@@ -30,13 +26,6 @@ pub enum GripPart {
End,
/// A one-point parameter's point (a position, a visibility or lookup grip).
At,
/// An XY parameter's corner at the base's X and the end's Y (listed as `blocks.reference.grip`
/// takes it, as [`GripPart::name`] names it).
#[serde(rename = "basex-endy")]
BaseXEndY,
/// An XY parameter's corner at the end's X and the base's Y.
#[serde(rename = "basey-endx")]
BaseYEndX,
}
impl GripPart {
@@ -45,8 +34,6 @@ impl GripPart {
GripPart::Base => "base",
GripPart::End => "end",
GripPart::At => "at",
GripPart::BaseXEndY => "basex-endy",
GripPart::BaseYEndX => "basey-endx",
}
}
pub fn from_name(s: &str) -> Option<GripPart> {
@@ -54,28 +41,11 @@ impl GripPart {
"base" => Some(GripPart::Base),
"end" => Some(GripPart::End),
"at" => Some(GripPart::At),
"basex-endy" => Some(GripPart::BaseXEndY),
"basey-endx" => Some(GripPart::BaseYEndX),
_ => None,
}
}
}
#[cfg(test)]
mod tests {
use super::GripPart;
/// A grip is listed with the part name `blocks.reference.grip` takes back.
#[test]
fn listed_part_names_are_the_names_a_drag_takes() {
for p in [GripPart::Base, GripPart::End, GripPart::At, GripPart::BaseXEndY, GripPart::BaseYEndX] {
let listed = serde_json::to_value(p).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default();
assert_eq!(listed, p.name());
assert_eq!(GripPart::from_name(&listed), Some(p));
}
}
}
/// How a grip looks and what it does.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
@@ -86,13 +56,6 @@ pub enum GripShape {
Point,
/// A down-pointing triangle: click it for the property's choices.
List,
/// A circle at the end of an angle: drag it to turn the angle.
Rotation,
/// An arrow across a reflection line: click it to flip (its choices are the two states).
Flip,
/// A pentagon pointing to the left of an alignment's direction: drag it next to an object to
/// align the reference with it.
Alignment,
}
/// One grip of a dynamic block reference.
@@ -139,15 +102,6 @@ fn ends_used(m: &DynamicBlock, node: i32) -> Option<(bool, bool)> {
used
}
/// Where a grip object at `g` (from its parameter's base, in the dynamic block) is when the
/// parameter's line `home` (base to end, in the block) is now `now` from `base`: kept along and
/// across the line as it turns, moves or stretches. `home` and `now` aren't zero.
fn carried(g: Vec2, home: Vec2, base: Vec2, now: Vec2) -> Vec2 {
let (u0, u) = (home * (1.0 / home.len()), now * (1.0 / now.len()));
let (along, across) = (g.dot(u0) / home.len(), u0.x * g.y - u0.y * g.x);
base + now * along + u.perp() * across
}
fn point<S: serde::Serializer>(p: &Vec2, s: S) -> Result<S::Ok, S::Error> {
[p.x, p.y].serialize(s)
}
@@ -166,7 +120,6 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec<DynGrip> {
};
// The grips the current visibility state shows (all of them without visibility states).
let objects: HashMap<i32, Handle> = m.grip_objects.iter().copied().collect();
let points: HashMap<i32, Vec3> = m.grip_points.iter().copied().collect();
let mut shown_in_state: Option<HashSet<Handle>> = None;
let mut visibility_node = None;
for p in &m.parameters {
@@ -218,87 +171,6 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec<DynGrip> {
}
}
}
ParameterKind::Rotation { base: hb, end: he, label, .. } => {
let (b, e) = match r.values.get(&p.node) {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*hb, *he),
};
let id = grip(1);
let (home, now) = ((*he - *hb).xy(), (e - b).xy());
if shown(p.node, id) && home.len() > 1e-12 && now.len() > 1e-12 {
// The grip object's place (AutoCAD draws the circle there, not at the radius'
// end), turned and moved with the radius.
let at = carried(points.get(&id).copied().unwrap_or(*he).xy() - hb.xy(), home, b.xy(), now);
let at = Vec3::new(at.x, at.y, b.z);
let u = at - b;
let u = if u.len() > 1e-12 { u * (1.0 / u.len()) } else { Vec3::new(1.0, 0.0, 0.0) };
let (at, dir) = (world(at), toward(at, u));
out.push(DynGrip {
node: p.node,
part: GripPart::End,
shape: GripShape::Rotation,
at,
dir,
property: label.clone(),
choices: Vec::new(),
});
}
}
ParameterKind::Flip { base: hb, end: he, label, states, .. } => {
let (b, e, flipped) = match r.values.get(&p.node) {
Some(Value::Flip { base, end, flipped }) => (*base, *end, *flipped),
_ => (*hb, *he, false),
};
let id = grip(0);
let (home, now) = ((*he - *hb).xy(), (e - b).xy());
if shown(p.node, id) && home.len() > 1e-12 && now.len() > 1e-12 {
// The grip object's place, kept along and across the reflection line as the
// line turns or moves with other actions.
let g = points.get(&id).copied().unwrap_or(*hb).xy() - hb.xy();
let at = carried(g, home, b.xy(), now);
let u = now * (1.0 / now.len());
let across_dir = if flipped { -u.perp() } else { u.perp() };
let (at3, dir) = (Vec3::new(at.x, at.y, b.z), toward(Vec3::new(at.x, at.y, b.z), across_dir.to3(0.0)));
out.push(DynGrip {
node: p.node,
part: GripPart::Base,
shape: GripShape::Flip,
at: world(at3),
dir,
property: label.clone(),
choices: states.to_vec(),
});
}
}
// Squares at the base and the end (a polar parameter), and at the two other corners of
// the rectangle they span (an XY parameter), for the grips the parameter has; an end
// no action follows has none.
ParameterKind::Polar { base, end, label, .. } | ParameterKind::Xy { base, end, x_label: label, .. } => {
let (b, e) = match r.values.get(&p.node) {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*base, *end),
};
let used = ends_used(&m, p.node).map_or([true, true], |(base, end)| [base, end]);
let mut corners = vec![(0, GripPart::Base, b, used[0]), (1, GripPart::End, e, used[1])];
if matches!(p.kind, ParameterKind::Xy { .. }) {
let both = used[0] && used[1];
corners.push((2, GripPart::BaseXEndY, Vec3::new(b.x, e.y, b.z), both));
corners.push((3, GripPart::BaseYEndX, Vec3::new(e.x, b.y, b.z), both));
}
for (i, part, at, used) in corners {
if used && shown(p.node, grip(i)) {
out.push(DynGrip {
node: p.node,
part,
shape: GripShape::Point,
at: world(at),
dir: Vec2::ZERO,
property: label.clone(),
choices: Vec::new(),
});
}
}
}
ParameterKind::Point { at, label, .. } => {
let at = match r.values.get(&p.node) {
Some(Value::Point { at }) => *at,
@@ -317,26 +189,6 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec<DynGrip> {
});
}
}
// At the base point, pointing to the left of the direction (as AutoCAD draws it).
ParameterKind::Alignment { base, end, .. } => {
let (b, e) = match r.values.get(&p.node) {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*base, *end),
};
let u = (e - b).xy();
if shown(p.node, grip(0)) && u.len() > 1e-12 {
let (at, dir) = (world(b), toward(b, u.perp().to3(0.0)));
out.push(DynGrip {
node: p.node,
part: GripPart::Base,
shape: GripShape::Alignment,
at,
dir,
property: String::new(),
choices: Vec::new(),
});
}
}
ParameterKind::Visibility { at, label, .. } | ParameterKind::Lookup { at, label, .. } => {
let Some(list) = choices.get(&label.to_ascii_uppercase()).filter(|c| !c.is_empty()) else { continue };
if shown(p.node, grip(0)) {
+29 -106
View File
@@ -29,8 +29,6 @@ pub enum Value {
Point { at: Vec3 },
/// A two-point parameter's points.
Points { base: Vec3, end: Vec3 },
/// A flip parameter's reflection line and whether it is flipped.
Flip { base: Vec3, end: Vec3, flipped: bool },
}
/// A dynamic block reference.
@@ -53,8 +51,8 @@ pub struct CustomProperty {
/// The values it may be set to, when it is a choice (visibility states, lookup values, a
/// distance's list).
pub choices: Vec<String>,
/// CADCraft can change it ([`super::set_property`]): a visibility state, a distance, an angle,
/// a position, a flip state, or a lookup whose tables set only those.
/// CADCraft can change it ([`super::set_property`]): a visibility state, a distance, a
/// position, or a lookup whose tables set only those.
pub editable: bool,
}
@@ -93,9 +91,7 @@ fn entries(objects: &HashMap<Handle, &ForeignObject>, dict: Handle) -> Vec<(Stri
out
}
/// A value XRECORD: its text (group 1) when it has one, else its points (10/20/30); a flip
/// parameter's also has its state, a group 70 after its points (the header's `70 25`, `70 104`
/// come before them).
/// A value XRECORD: its text (group 1) when it has one, else its points (10/20/30).
fn value(o: &ForeignObject) -> Option<Value> {
if let Some(t) = o.tags.iter().find(|t| t.code == 1) {
return Some(Value::Text { value: t.value.clone() });
@@ -104,10 +100,7 @@ fn value(o: &ForeignObject) -> Option<Value> {
o.tags.iter().filter(|t| t.code == code).nth(i).and_then(|t| t.value.trim().parse::<f64>().ok()).filter(|v| v.is_finite())
};
let point = |i: usize| Some(Vec3::new(num(10, i)?, num(20, i)?, num(30, i).unwrap_or(0.0)));
let first_point = o.tags.iter().position(|t| t.code == 10).unwrap_or(o.tags.len());
let state = o.tags.get(first_point..).unwrap_or_default().iter().rev().find(|t| t.code == 70).map(|t| t.value.trim() == "1");
match (point(0), point(1)) {
(Some(base), Some(end)) if state.is_some() => Some(Value::Flip { base, end, flipped: state == Some(true) }),
(Some(base), Some(end)) => Some(Value::Points { base, end }),
(Some(at), None) => Some(Value::Point { at }),
_ => None,
@@ -129,52 +122,17 @@ pub fn reference(d: &Drawing, insert: Handle) -> Option<Reference> {
let target = data.tags.iter().find(|t| t.code == 340).and_then(|t| Handle::parse_hex(&t.value))?;
let (kind, name) = d.foreign.targets.get(&target)?;
let definition = d.block(name).filter(|_| kind == "BLOCK_RECORD")?.name.clone();
let m = dynamic_block(d, &definition)?;
dynamic_block(d, &definition)?;
let mut values = BTreeMap::new();
let cache = entry(&objects, rep, "AppDataCache").and_then(|c| entry(&objects, c, "ACAD_ENHANCEDBLOCKDATA"));
for (key, h) in cache.map(|c| entries(&objects, c)).unwrap_or_default().into_iter().take(MAX_VALUES) {
if let (Ok(node), Some(v)) = (key.trim().parse::<i32>(), objects.get(&h).and_then(|o| value(o))) {
// The record's groups alone can't tell a flip from another two-point parameter (a stray
// 70, or a flip without its state): the parameter it belongs to decides.
let flip = m.parameters.iter().any(|p| p.node == node && matches!(p.kind, ParameterKind::Flip { .. }));
let v = match (flip, v) {
(false, Value::Flip { base, end, .. }) => Value::Points { base, end },
(true, Value::Points { base, end }) => Value::Flip { base, end, flipped: false },
(_, v) => v,
};
values.insert(node, v);
}
}
Some(Reference { definition, values })
}
/// An angle (radians) as Properties shows it: degrees with AUPREC decimals.
/// An angle parameter's value `a` (radians, counterclockwise) as the drawing shows angles: from
/// ANGBASE, clockwise when ANGDIR is 1 (AutoCAD shows a 0 angle as 90 in a drawing measured
/// clockwise from north, and 0.5 rad as 61.35).
pub(super) fn angle_shown(d: &Drawing, a: f64) -> f64 {
let base = d.header.f64("ANGBASE", 0.0);
let shown = if d.header.i64("ANGDIR", 0) == 1 { base - a } else { a - base };
shown.rem_euclid(std::f64::consts::TAU)
}
/// The value of an angle parameter shown (or typed) as `v` (radians): the inverse of
/// [`angle_shown`].
pub(super) fn angle_from_shown(d: &Drawing, v: f64) -> f64 {
let base = d.header.f64("ANGBASE", 0.0);
let a = if d.header.i64("ANGDIR", 0) == 1 { base - v } else { v + base };
a.rem_euclid(std::f64::consts::TAU)
}
fn angle_text(d: &Drawing, a: f64) -> String {
let prec = usize::try_from(d.header.i64("AUPREC", 0).clamp(0, 8)).unwrap_or(0);
// Rounded to the shown decimals first: an angle just short of a full turn shows as 0, not 360.
let step = 10f64.powi(i32::try_from(prec).unwrap_or(0));
let shown = (angle_shown(d, a).to_degrees() * step).round() / step;
let shown = if shown >= 360.0 { shown - 360.0 } else { shown };
format!("{:.prec$}", shown + 0.0)
}
/// A number as the drawing shows lengths (LUPREC decimals).
fn number(d: &Drawing, v: f64) -> String {
let prec = usize::try_from(d.header.i64("LUPREC", 4).clamp(0, 8)).unwrap_or(4);
@@ -198,7 +156,26 @@ struct Current<'a> {
impl Current<'_> {
/// Parameter `node`'s value of property `property`, as table cells write it.
fn property(&self, node: i32, property: &str) -> Option<String> {
super::apply::property_text(self.m, self.values, node, property)
let p = self.m.parameters.iter().find(|p| p.node == node)?;
let v = self.values.get(&node);
match (&p.kind, property.to_ascii_lowercase().as_str()) {
(ParameterKind::Visibility { states, .. }, "visibilitystate") => match v {
Some(Value::Text { value }) => Some(value.clone()),
_ => states.first().map(|s| s.name.clone()),
},
(ParameterKind::Linear { base, end, .. }, "updateddistance" | "distance") => {
let (b, e) = match v {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*base, *end),
};
Some(format!("{}", (e - b).len()))
}
(ParameterKind::Lookup { .. }, "lookupstring") => match v {
Some(Value::Text { value }) => Some(value.clone()),
_ => None,
},
_ => None,
}
}
/// Lookup parameter `node`'s value: the value every lookup table that sets it gives for the
@@ -262,27 +239,6 @@ pub fn custom_properties(d: &Drawing, insert: Handle) -> Option<(String, Vec<Cus
let choices = if values.is_list() { values.list.iter().map(|x| number(d, x * sx)).collect() } else { Vec::new() };
out.push(CustomProperty { name: label.clone(), value: number(d, (e - b).len() * sx), choices, editable: true });
}
// The distance from the base to the end, and the end's direction (AutoCAD measures it
// from the block's X axis, not from where the dynamic block has it).
ParameterKind::Polar { base: b, end: e, label, angle_label, values, .. } => {
let (b, e) = match v {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*b, *e),
};
let choices = if values.is_list() { values.list.iter().map(|x| number(d, x * sx)).collect() } else { Vec::new() };
out.push(CustomProperty { name: label.clone(), value: number(d, (e - b).len() * sx), choices, editable: true });
let a = (e - b).xy().angle().rem_euclid(std::f64::consts::TAU);
out.push(CustomProperty { name: angle_label.clone(), value: angle_text(d, a), choices: Vec::new(), editable: true });
}
// How far the end is from the base along X and along Y.
ParameterKind::Xy { base: b, end: e, x_label, y_label, .. } => {
let (b, e) = match v {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*b, *e),
};
out.push(CustomProperty { name: x_label.clone(), value: number(d, (e.x - b.x) * sx), choices: Vec::new(), editable: true });
out.push(CustomProperty { name: y_label.clone(), value: number(d, (e.y - b.y) * sy), choices: Vec::new(), editable: true });
}
ParameterKind::Point { at, label, .. } => {
let at = match v {
Some(Value::Point { at }) => *at,
@@ -291,21 +247,6 @@ pub fn custom_properties(d: &Drawing, insert: Handle) -> Option<(String, Vec<Cus
out.push(CustomProperty { name: format!("{label} X"), value: number(d, (at.x - base.x) * sx), choices: Vec::new(), editable: true });
out.push(CustomProperty { name: format!("{label} Y"), value: number(d, (at.y - base.y) * sy), choices: Vec::new(), editable: true });
}
ParameterKind::Rotation { base: hb, end: he, label, .. } => {
let (b, e) = match v {
Some(Value::Points { base, end }) => (*base, *end),
_ => (*hb, *he),
};
let now = (e - b).xy();
let zero = (*he - *hb).xy();
let a = (now.y.atan2(now.x) - zero.y.atan2(zero.x)).rem_euclid(std::f64::consts::TAU);
out.push(CustomProperty { name: label.clone(), value: angle_text(d, a), choices: Vec::new(), editable: true });
}
ParameterKind::Flip { label, states, .. } => {
let flipped = matches!(v, Some(Value::Flip { flipped: true, .. }));
let value = states[usize::from(flipped)].clone();
out.push(CustomProperty { name: label.clone(), value, choices: states.to_vec(), editable: true });
}
ParameterKind::Visibility { label, states, .. } => {
let value = cur.property(p.node, "VisibilityState").unwrap_or_default();
out.push(CustomProperty { name: label.clone(), value, choices: states.iter().map(|s| s.name.clone()).collect(), editable: true });
@@ -322,8 +263,7 @@ pub fn custom_properties(d: &Drawing, insert: Handle) -> Option<(String, Vec<Cus
}
/// Whether every lookup table that sets lookup parameter `node` sets only what
/// [`super::set_property`] can apply with it: visibility states, distances, angles, positions and
/// flip states.
/// [`super::set_property`] can apply with it: visibility states and distances.
fn lookup_sets_what_changes(m: &DynamicBlock, node: i32) -> bool {
let mut any = false;
for a in &m.actions {
@@ -332,29 +272,12 @@ fn lookup_sets_what_changes(m: &DynamicBlock, node: i32) -> bool {
continue;
}
any = true;
let settable = |c: &super::LookupColumn| {
m.parameters.iter().find(|p| p.node == c.node).is_some_and(|p| super::apply::column(&p.kind, &c.property).is_some())
};
if !columns.iter().all(settable) {
if !columns
.iter()
.all(|c| matches!(c.property.to_ascii_lowercase().as_str(), "lookupstring" | "visibilitystate" | "updateddistance" | "distance"))
{
return false;
}
}
any
}
#[cfg(test)]
mod tests {
use super::angle_text;
use crate::Drawing;
#[test]
fn an_angle_just_short_of_a_full_turn_shows_as_zero() {
let mut d = Drawing::new_imperial();
d.header.set_i64("AUPREC", 0);
assert_eq!(angle_text(&d, 359.7f64.to_radians()), "0");
assert_eq!(angle_text(&d, 359.4f64.to_radians()), "359");
d.header.set_i64("AUPREC", 2);
assert_eq!(angle_text(&d, 359.996f64.to_radians()), "0.00");
assert_eq!(angle_text(&d, 90f64.to_radians()), "90.00");
}
}
+1 -1
View File
@@ -617,7 +617,7 @@ impl EntityKind {
EntityKind::Text(t) => vec![t.justify_point()],
EntityKind::MText(t) => vec![t.insert.xy()],
EntityKind::AttDef(a) => vec![a.text.justify_point()],
EntityKind::Insert(i) => std::iter::once(i.insert.xy()).chain(i.grip_attribs().map(|(_, a)| a.text.justify_point())).collect(),
EntityKind::Insert(i) => std::iter::once(i.insert.xy()).chain(i.attribs.iter().map(|a| a.text.justify_point())).collect(),
EntityKind::Dimension(d) => vec![d.p13.xy(), d.p14.xy(), d.defpt.xy(), d.text_mid.xy()],
EntityKind::MLine(m) => m.points(),
EntityKind::Leader(l) => l.vertices.iter().map(|v| v.xy()).collect(),
-6
View File
@@ -191,12 +191,6 @@ fn one_u() -> u32 {
}
impl Insert {
/// The attributes that have a grip of their own (grips 1, 2… after the insertion point), with
/// their index in `attribs`: those shown and not locked in position, as AutoCAD offers them.
pub fn grip_attribs(&self) -> impl Iterator<Item = (usize, &Attrib)> {
self.attribs.iter().enumerate().filter(|(_, a)| !a.invisible && !a.modes.lock_position)
}
/// Block-to-world transform (2D part).
pub fn transform(&self, base: Vec2) -> Mat3 {
Mat3::translate(self.insert.xy())
+3 -3
View File
@@ -70,14 +70,14 @@ pub fn specs() -> Vec<CommandSpec> {
.enabled(has_doc)
.noundo(),
CommandSpec::new("blocks.reference.set", "Set Dynamic Property", run_reference_set)
.params("{handle (a dynamic block reference), name (a custom property as Properties names it: a visibility state, a lookup, a distance, \"Position1 X\", an angle or a flip state), value (lengths in drawing units, angles in degrees; a flip state by name or 0/1)} → {properties}")
.params("{handle (a dynamic block reference), name (a custom property as Properties names it: a visibility state, a lookup, a distance or \"Position1 X\"), value (lengths in drawing units)} → {properties}")
.enabled(has_doc),
CommandSpec::new("blocks.reference.grips", "Dynamic Block Grips", dyngrip::run_grips)
.params("{handle} → [{node, part: base|end|at|basex-endy|basey-endx, shape: linear|point|list|rotation|flip, at: [x,y], dir: [x,y], property, choices?}] (empty: not a dynamic block reference)")
.params("{handle} → [{node, part: base|end|at, shape: linear|point|list, at: [x,y], dir: [x,y], property, choices?}] (empty: not a dynamic block reference)")
.enabled(has_doc)
.noundo(),
CommandSpec::new("blocks.reference.grip", "Drag Dynamic Grip", dyngrip::run_grip)
.params("{handle, node (the parameter's graph id), part: base|end|at|basex-endy|basey-endx, to: [x,y] (drawing coordinates)} → {properties}: a distance's arrow changes the distance (snapped to its values), a position's square moves it, a rotation's circle turns its angle, a polar or XY parameter's squares move its base, end or corners")
.params("{handle, node (the parameter's graph id), part: base|end|at, to: [x,y] (drawing coordinates)} → {properties}: a distance's arrow changes the distance (snapped to its values), a position's square moves it")
.enabled(has_doc),
CommandSpec::new("purge", "Purge", purge::run)
.alias(&["pu", "-purge"])
+22 -72
View File
@@ -1,7 +1,7 @@
//! Grips of dynamic block references: `blocks.reference.grips` lists them, `blocks.reference.grip`
//! drags one (one undo step), and [`Session::start_dyn_grip`] starts the drag the UI's click on a
//! grip begins, with the reference re-evaluated under the cursor as its preview. Typing a number
//! at a distance's grip sets the distance, at a rotation grip the angle (degrees).
//! at a distance's grip sets the distance.
use cadcraft_doc::color::Color;
use cadcraft_doc::dynblock::{self, GripPart, GripShape};
@@ -30,8 +30,7 @@ pub(super) fn run_grip(s: &mut Session, p: &Value) -> Result<Value> {
.and_then(Value::as_i64)
.and_then(|n| i32::try_from(n).ok())
.ok_or_else(|| bad(cmd, "`node` (a parameter's graph id) is required"))?;
let part =
str_param(p, "part").and_then(GripPart::from_name).ok_or_else(|| bad(cmd, "`part` must be base, end, at, basex-endy or basey-endx"))?;
let part = str_param(p, "part").and_then(GripPart::from_name).ok_or_else(|| bad(cmd, "`part` must be base, end or at"))?;
let to = point_param(p, "to").ok_or_else(|| bad(cmd, "`to` [x, y] is required"))?;
drag(s, h, node, part, to).map_err(|e| bad(cmd, e))?;
let properties = dynblock::custom_properties(s.doc()?, h).map(|(_, p)| p).unwrap_or_default();
@@ -47,25 +46,11 @@ fn drag(s: &mut Session, h: Handle, node: i32, part: GripPart, to: Vec2) -> std:
return Err("the reference is on a locked layer".into());
}
let mut d = s.doc().map_err(|e| e.to_string())?.clone();
drag_in(s, &mut d, h, node, part, to)?;
dynblock::drag_grip(&mut d, h, node, part, to)?;
*s.doc_mut().map_err(|e| e.to_string())? = d;
Ok(())
}
/// Drag grip (`node`, `part`) of reference `h` to `to` in drawing `d`; an alignment grip aligns
/// the reference with the object at the cursor (within the aperture), as AutoCAD does.
fn drag_in(s: &Session, d: &mut Drawing, h: Handle, node: i32, part: GripPart, to: Vec2) -> std::result::Result<(), String> {
let alignment = dynblock::reference(d, h)
.and_then(|r| dynblock::dynamic_block(d, &r.definition))
.is_some_and(|m| m.parameters.iter().any(|p| p.node == node && matches!(p.kind, dynblock::ParameterKind::Alignment { .. })));
if !alignment {
return dynblock::drag_grip(d, h, node, part, to);
}
let aperture = s.pixel_size() * s.settings.aperture.max(1.0);
let near = crate::snap::nearest_with_direction(d, &s.space(), to, aperture, h);
dynblock::align_grip(d, h, node, to, near)
}
/// The properties an object of a block draws with in reference `r`: on layer 0 it is on the
/// reference's layer, and its ByBlock colour, linetype, lineweight and transparency are the
/// reference's (as the renderer draws a block's contents).
@@ -117,11 +102,7 @@ fn drawn(d: &Drawing, h: Handle) -> Vec<Entity> {
_ => None,
});
let common = under(&a.props.over(def.unwrap_or(&by_block)), r);
let kind = match a.multiline_text() {
Some(m) => EntityKind::MText(m),
None => EntityKind::Text(a.text.clone()),
};
Entity { handle: Handle(0), common, kind }
Entity { handle: Handle(0), common, kind: EntityKind::Text(a.text.clone()) }
}));
out
}
@@ -133,16 +114,11 @@ struct DynGripEdit {
part: GripPart,
/// Where the grip is (the rubber band's start).
from: Vec2,
/// The property it changes, and the grip's shape (a typed number sets a distance or angle).
/// The property it changes, and whether it is a distance (a typed number sets it).
property: String,
shape: GripShape,
/// Where the grip can stop (a value list or increments): tick marks across its travel.
stops: Vec<(Vec2, Vec2)>,
distance: bool,
}
/// Half a tick mark's length, in pixels.
const TICK_PX: f64 = 6.0;
impl Interactive for DynGripEdit {
fn name(&self) -> &'static str {
"GRIP"
@@ -153,22 +129,19 @@ impl Interactive for DynGripEdit {
}
fn prompt(&self, _s: &Session) -> Prompt {
let (msg, accept) = match self.shape {
GripShape::Linear => ("** STRETCH ** Specify stretch point or distance", Accept::POINT_OR_NUMBER),
GripShape::Rotation => ("** ROTATE ** Specify rotation point or angle", Accept::POINT_OR_NUMBER),
GripShape::Alignment => ("Specify point location", Accept::POINT),
_ => ("** STRETCH ** Specify stretch point", Accept::POINT),
let (msg, accept) = if self.distance {
("** STRETCH ** Specify stretch point or distance", Accept::POINT_OR_NUMBER)
} else {
("** STRETCH ** Specify stretch point", Accept::POINT)
};
let p = Prompt::new(msg, accept).kw(&["eXit"]).base(self.from);
// A rotation grip asks for an angle: Dynamic Input shows one angle box.
if self.shape == GripShape::Rotation { p.angle() } else { p }
Prompt::new(msg, accept).kw(&["eXit"]).base(self.from)
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
let to = match i {
Input::Point(p) => p,
Input::Deferred(d) => d.at,
Input::Text(t) if matches!(self.shape, GripShape::Linear | GripShape::Rotation) => {
Input::Text(t) if self.distance => {
let mut d = s.doc()?.clone();
dynblock::set_property(&mut d, self.handle, &self.property, t.trim()).map_err(EngineError::Other)?;
*s.doc_mut()? = d;
@@ -182,30 +155,9 @@ impl Interactive for DynGripEdit {
Ok(Step::Done)
}
/// The rubber band from the grip, and ticks at the stops of a value list or increments.
fn preview(&self, s: &Session, c: Vec2) -> Vec<EntityKind> {
let half = TICK_PX * s.pixel_size();
let mut out: Vec<EntityKind> = self
.stops
.iter()
.map(|(at, way)| {
let n = way.perp() * half;
crate::cmd::helpers::line(*at - n, *at + n)
})
.collect();
out.push(crate::cmd::helpers::line(self.from, c));
out
}
/// A rotation grip's angle at the cursor, as Properties will show it.
fn live_value(&self, s: &Session, c: Vec2) -> Option<String> {
if self.shape != GripShape::Rotation {
return None;
}
let mut d = s.doc().ok()?.clone();
dynblock::drag_grip(&mut d, self.handle, self.node, self.part, c).ok()?;
let (_, props) = dynblock::custom_properties(&d, self.handle)?;
props.into_iter().find(|p| p.name.eq_ignore_ascii_case(&self.property)).map(|p| format!("{}°", p.value))
/// The rubber band from the grip.
fn preview(&self, _s: &Session, c: Vec2) -> Vec<EntityKind> {
vec![crate::cmd::helpers::line(self.from, c)]
}
/// The reference re-evaluated at the cursor, drawn as it will look (its own colours, so
@@ -213,7 +165,7 @@ impl Interactive for DynGripEdit {
fn preview_objects(&self, s: &Session, c: Vec2) -> Vec<Entity> {
let Ok(d) = s.doc() else { return Vec::new() };
let mut d = d.clone();
match drag_in(s, &mut d, self.handle, self.node, self.part, c) {
match dynblock::drag_grip(&mut d, self.handle, self.node, self.part, c) {
Ok(()) => drawn(&d, self.handle),
Err(_) => Vec::new(),
}
@@ -222,8 +174,8 @@ impl Interactive for DynGripEdit {
impl Session {
/// Start dragging grip `part` of parameter `node` of dynamic block reference `handle` (the
/// UI's click on a dynamic grip). A list grip (visibility, lookup) or a flip grip has no
/// drag: the UI offers the choices, or flips, with `blocks.reference.set`.
/// UI's click on a dynamic grip). A list grip (visibility, lookup) has no drag: the UI offers
/// its choices and sets them with `blocks.reference.set`.
pub fn start_dyn_grip(&mut self, handle: Handle, node: i32, part: GripPart) -> Result<()> {
if self.running.is_some() {
self.cancel();
@@ -232,19 +184,17 @@ impl Session {
.into_iter()
.find(|g| g.node == node && g.part == part)
.ok_or_else(|| EngineError::Other("no such grip".into()))?;
if matches!(g.shape, GripShape::List | GripShape::Flip) {
return Err(EngineError::Other("a list or flip grip is clicked, not dragged".into()));
if g.shape == GripShape::List {
return Err(EngineError::Other("a list grip is chosen from, not dragged".into()));
}
let label = if g.shape == GripShape::Rotation { "** ROTATE **" } else { "** STRETCH **" };
let stops = dynblock::grip_stops(self.doc()?, handle, node, part);
let edit = DynGripEdit { handle, node, part, from: g.at, property: g.property, shape: g.shape, stops };
let edit = DynGripEdit { handle, node, part, from: g.at, property: g.property, distance: g.shape == GripShape::Linear };
let machine = crate::guard::Guarded::wrap(Box::new(edit));
let st = self.state()?;
let (before, selection_before) = (st.doc.clone(), st.selection.clone());
self.running = Some(Running { id: "grip".into(), machine, before, selection_before });
self.pending_window = None;
self.point_mods.clear();
self.echo(label);
self.echo("** STRETCH **");
Ok(())
}
}
+1 -4
View File
@@ -170,16 +170,13 @@ pub fn stretch_grip(kind: &EntityKind, index: usize, to: Vec2) -> Option<EntityK
if index == 0 {
return Some(translated(kind, delta));
}
let k = i.grip_attribs().nth(index - 1).map(|(k, _)| k)?;
let a = i.attribs.get_mut(k)?;
let a = i.attribs.get_mut(index - 1)?;
let ip = a.text.insert.xy() + delta;
set_xy(&mut a.text.insert, ip);
if let Some(al) = &mut a.text.align_pt {
let q = al.xy() + delta;
set_xy(al, q);
}
// A multiline attribute is drawn from its multiline text: it moves too.
a.transform_multiline(&Mat3::translate(delta));
}
EntityKind::Dimension(d) => {
match index {
-9
View File
@@ -92,15 +92,6 @@ impl Interactive for Guarded {
Vec::new()
})
}
fn live_value(&self, s: &Session, cursor: Vec2) -> Option<String> {
if self.broken.get().is_some() {
return None;
}
catch_unwind(AssertUnwindSafe(|| self.inner.live_value(s, cursor))).unwrap_or_else(|_| {
self.broken.set(Some("panic in preview"));
None
})
}
fn drag(&self, s: &Session, cursor: Vec2) -> Option<crate::prompt::Drag> {
if self.broken.get().is_some() {
return None;
-14
View File
@@ -103,10 +103,6 @@ pub struct Prompt {
/// the routine writes, so it cannot be read for the word "Select" (#1598).
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub picks_one: bool,
/// The value asked for is an angle about the base (a rotation grip): Dynamic Input shows one
/// angle box, with the command's live value ([`Interactive::live_value`]).
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub angle: bool,
/// The prompt takes a block's name as well as its keywords: a Greek word that is an existing
/// block's name is that block, not a keyword read from its Latin keys.
#[serde(skip_serializing_if = "std::ops::Not::not")]
@@ -158,11 +154,6 @@ impl Prompt {
self.grip = Some(g);
self
}
/// An angle about the base is asked for (the `angle` field).
pub fn angle(mut self) -> Self {
self.angle = true;
self
}
/// The visual chooser the UI can show (the `picker` field).
pub fn picker(mut self, p: Picker) -> Self {
self.picker = Some(p);
@@ -335,11 +326,6 @@ pub trait Interactive: Send {
fn preview_objects(&self, _s: &Session, _cursor: Vec2) -> Vec<cadcraft_doc::Entity> {
Vec::new()
}
/// The value the cursor would give, as the prompt asks for it (an angle as the drawing
/// shows angles): what Dynamic Input shows in its box before anything is typed.
fn live_value(&self, _s: &Session, _cursor: Vec2) -> Option<String> {
None
}
/// The preview as existing objects under one transform, when it is that (MOVE, COPY,
/// ROTATE, SCALE). The UI then draws them from geometry uploaded once instead of rebuilding
/// the transformed copies every frame; `None` falls back to [`Interactive::preview`].
-6
View File
@@ -608,12 +608,6 @@ impl Session {
out
}
/// The value the cursor would give at the active command's prompt (see
/// [`Interactive::live_value`]).
pub fn live_value(&self, cursor: Vec2) -> Option<String> {
self.running.as_ref()?.machine.live_value(self, cursor)
}
/// What the drawing area shows in place of the drawing while a command runs (DVIEW's preview
/// set, see [`Interactive::display_only`]), also while a transparent command interrupts it.
/// `None`: the drawing.
+4 -46
View File
@@ -7,7 +7,7 @@ mod viewport;
pub use viewport::ViewportPoint;
use cadcraft_doc::{Drawing, EntityKind, Handle, Insert, MAX_BLOCK_DEPTH, Prim, Space};
use cadcraft_doc::{Drawing, EntityKind, Insert, MAX_BLOCK_DEPTH, Prim, Space};
use cadcraft_geom::{Bounds2, Circle, EPS, Ellipse, Mat3, PI, Segment, Vec2, intersect_ext};
use serde::Serialize;
@@ -385,7 +385,7 @@ fn osnap_in_with_prims(
frozen: &[String],
clip: Option<Bounds2>,
) -> Option<(Vec<SnapHit>, Vec<Prim>)> {
let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen, None)?;
let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen)?;
// Intersections between nearby primitives; Apparent Intersection also where their extensions
// meet (lines extended, arcs as full circles: in 2D, the "apparent" crossing of objects
// that don't reach each other).
@@ -475,50 +475,9 @@ pub(crate) fn gather(
aperture: f64,
osmode: u32,
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>)> {
gather_in(d, space, ix, cursor, aperture, osmode, &[], None)
gather_in(d, space, ix, cursor, aperture, osmode, &[])
}
/// The point nearest `cursor` within `aperture` on the visible objects of `space` other than
/// `skip` (and on the objects inside block references), with the object's direction there (a unit
/// vector; a circle's or arc's runs counterclockwise): what an alignment grip aligns a dynamic
/// block reference with.
pub(crate) fn nearest_with_direction(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, skip: Handle) -> Option<(Vec2, Vec2)> {
let ix = crate::spatial::index(d, space);
let (_, prims) = gather_in(d, space, &ix, cursor, aperture, 0, &[], Some(skip))?;
let mut best: Option<(f64, Vec2, Vec2)> = None;
let mut consider = |at: Vec2, dir: Vec2| {
let dd = at.dist(cursor);
if at.is_finite() && dir.len() > 1e-12 && dir.is_finite() && dd <= aperture && best.is_none_or(|(bd, _, _)| dd < bd) {
best = Some((dd, at, dir * (1.0 / dir.len())));
}
};
for p in prims.iter().take(2000) {
if let Prim::Circle(c) = p {
let at = c.closest(cursor);
consider(at, (at - c.center).perp());
continue;
}
if let Prim::Infinite { base, dir, .. } = p {
let len = dir.len();
if len > 1e-12 {
let u = *dir * (1.0 / len);
consider(*base + u * (cursor - *base).dot(u), u);
}
continue;
}
for seg in prim_segments(p) {
let seg = fix_circle(&seg);
let at = seg.closest(cursor);
match seg {
Segment::Line(l) => consider(at, l.b - l.a),
Segment::Arc { arc, .. } => consider(at, (at - arc.center).perp()),
}
}
}
best.map(|(_, at, dir)| (at, dir))
}
#[allow(clippy::too_many_arguments)]
fn gather_in(
d: &Drawing,
space: &Space,
@@ -527,7 +486,6 @@ fn gather_in(
aperture: f64,
osmode: u32,
frozen: &[String],
skip: Option<Handle>,
) -> Option<(Vec<(u32, Vec2)>, Vec<Prim>)> {
let probe = Bounds2::new(cursor, cursor).expand(aperture);
let mut cands: Vec<(u32, Vec2)> = Vec::new();
@@ -535,7 +493,7 @@ fn gather_in(
let mut count = 0usize;
let mut budget = MAX_BLOCK_LEAVES;
for (e, known) in crate::select::candidates(d, space, ix, &probe.expand(aperture), true, false)? {
if !d.is_visible(e) || frozen.iter().any(|l| l.eq_ignore_ascii_case(&e.common.layer)) || Some(e.handle) == skip {
if !d.is_visible(e) || frozen.iter().any(|l| l.eq_ignore_ascii_case(&e.common.layer)) {
continue;
}
let inf = crate::select::is_infinite(e);
+1 -64
View File
@@ -4,7 +4,7 @@
use std::sync::Arc;
use cadcraft_engine::Session;
use cadcraft_engine::doc::{Attrib, AttribModes, Block, Entity, EntityKind, MText, MultilineAttrib, Text};
use cadcraft_engine::doc::{Attrib, AttribModes, Block, Entity, EntityKind, Text};
use cadcraft_engine::geom::Vec3;
use serde_json::json;
@@ -45,66 +45,3 @@ fn references_take_lock_position_from_the_definition() {
let Some(EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| e.kind.clone()) else { panic!("no reference") };
assert_eq!(i.attribs[0].modes, AttribModes { verify: false, preset: false, lock_position: true });
}
/// A definition at `x` with `modes`, invisible or not, multiline or not.
fn definition(tag: &str, x: f64, modes: AttribModes, invisible: bool, multiline: bool) -> Attrib {
let text = Text {
insert: Vec3::new(x, 0.0, 0.0),
align_pt: None,
height: 2.0,
value: tag.into(),
rotation: 0.0,
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign: Default::default(),
valign: Default::default(),
};
let multiline = multiline.then(|| {
let mtext = MText {
insert: Vec3::new(x, 0.0, 0.0),
height: 2.0,
width: 0.0,
attach: 7,
rotation: 0.0,
style: "Standard".into(),
contents: format!("{tag}\\PTWO"),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
};
MultilineAttrib { mtext, read_as: format!("{tag}\nTWO") }
});
Attrib { tag: tag.into(), text, invisible, constant: false, prompt: tag.into(), props: Default::default(), multiline, modes }
}
#[test]
fn only_shown_unlocked_attributes_have_grips_and_a_multiline_one_moves_its_text() {
let mut d = cadcraft_engine::doc::Drawing::new_imperial();
let locked = AttribModes { lock_position: true, ..AttribModes::default() };
let mut b = Block::new("TAG");
for a in [
definition("FREE", 0.0, AttribModes::default(), false, false),
definition("LOCKED", 10.0, locked, false, false),
definition("HIDDEN", 20.0, AttribModes::default(), true, false),
definition("NOTE", 30.0, AttribModes::default(), false, true),
] {
let h = d.new_handle();
b.entities.push(Entity::new(h, EntityKind::AttDef(a)));
}
d.blocks.insert("TAG".into(), Arc::new(b));
let mut s = Session::empty();
s.open_drawing(d, "tags", None);
let r = s.execute("insert", &json!({ "name": "TAG", "at": [100, 0] })).unwrap();
let h = cadcraft_engine::doc::Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
// The insertion point, FREE and NOTE: no grip for the locked or the invisible attribute.
let g = s.grips_of(h).unwrap();
assert_eq!(g.iter().map(|p| p.x).collect::<Vec<_>>(), [100.0, 100.0, 130.0]);
// NOTE's grip (index 2) dragged up 5: its multiline text moves with it.
s.execute("grip.stretch", &json!({ "handle": h.hex(), "index": 2, "to": [130, 5] })).unwrap();
let Some(EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| e.kind.clone()) else { panic!("no reference") };
let note = i.attribs.iter().find(|a| a.tag == "NOTE").unwrap();
assert_eq!((note.text.insert.y, note.multiline.as_ref().unwrap().mtext.insert.y), (5.0, 5.0));
let free = i.attribs.iter().find(|a| a.tag == "FREE").unwrap();
assert_eq!(free.text.insert.y, 0.0, "the others stay");
}
-53
View File
@@ -145,56 +145,3 @@ fn a_grip_drag_previews_the_reference_in_its_own_colours() {
let blue = cadcraft_engine::doc::color::Color::True(cadcraft_engine::doc::color::Rgb(0x2f, 0x6b, 0xff));
assert!(preview[n..].iter().all(|e| e.common.color == blue));
}
#[test]
fn a_grip_with_a_value_list_marks_its_stops_while_dragged() {
let (mut s, h) = session();
// Width is a list (30, 32, 36) from (0, -4): its end can stop 30, 32 or 36 along it.
let stops = cadcraft_engine::doc::dynblock::grip_stops(s.doc().unwrap(), h, 2, GripPart::End);
let at: Vec<(f64, f64)> = stops.iter().map(|(p, _)| (p.x, p.y)).collect();
assert_eq!(at, [(130.0, -4.0), (132.0, -4.0), (136.0, -4.0)]);
assert!(stops.iter().all(|(_, way)| (way.x - 1.0).abs() < 1e-12 && way.y.abs() < 1e-12));
// A grip that isn't on a list or increments has none; nor a list grip.
assert!(cadcraft_engine::doc::dynblock::grip_stops(s.doc().unwrap(), h, 1, GripPart::At).is_empty());
// The preview marks each stop with a tick across the travel, a few pixels long.
s.start_dyn_grip(h, 2, GripPart::End).unwrap();
let half = 6.0 * s.pixel_size();
let ticks: Vec<(f64, f64)> = s
.preview(Vec2::new(133.0, 0.0))
.into_iter()
.filter_map(|e| match e.kind {
cadcraft_engine::doc::EntityKind::Line(l) if (l.a.x - l.b.x).abs() < 1e-9 && ((l.b.y - l.a.y).abs() - 2.0 * half).abs() < 1e-9 => {
Some((l.a.x, (l.a.y + l.b.y) / 2.0))
}
_ => None,
})
.collect();
assert_eq!(ticks, [(130.0, -4.0), (132.0, -4.0), (136.0, -4.0)]);
}
/// An alignment grip dragged onto a line (the synthetic Align block of the io tests, a line at
/// 30° from (120, 100)): the reference moves onto the line and turns along it, as AutoCAD does;
/// away from objects it only moves.
#[test]
fn an_alignment_grip_aligns_with_the_line_at_the_cursor() {
let src = include_str!("../../../io/tests/data/dynblock_params.txt").replace("\r\n", "\n");
let d = cadcraft_io::read_dxf(dxf(&src).as_bytes()).unwrap();
let mut s = Session::empty();
s.open_drawing(d, "params", None);
let r = s.execute("insert", &json!({ "name": "Align", "at": [100, 100] })).unwrap();
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
let g = s.execute("blocks.reference.grips", &json!({ "handle": h.hex() })).unwrap();
assert_eq!(g[0]["shape"], "alignment");
// A point on the line, a little below it.
let (c, sn) = (30f64.to_radians().cos(), 30f64.to_radians().sin());
let to = [120.0 + 10.0 * c + 0.01 * sn, 100.0 + 10.0 * sn - 0.01 * c];
s.execute("blocks.reference.grip", &json!({ "handle": h.hex(), "node": 1, "part": "base", "to": to })).unwrap();
let Some(cadcraft_engine::doc::EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| &e.kind) else { panic!("a reference") };
assert!((i.rotation.to_degrees() - 30.0).abs() < 1e-6, "{}", i.rotation.to_degrees());
assert!((i.insert.x - (120.0 + 10.0 * c)).abs() < 1e-6 && (i.insert.y - (100.0 + 10.0 * sn)).abs() < 1e-6, "{:?}", i.insert);
// Far from anything: it only moves.
s.execute("blocks.reference.grip", &json!({ "handle": h.hex(), "node": 1, "part": "base", "to": [0, -50] })).unwrap();
let Some(cadcraft_engine::doc::EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| &e.kind) else { panic!("a reference") };
assert!((i.rotation.to_degrees() - 30.0).abs() < 1e-6 && i.insert.x.abs() < 1e-9 && (i.insert.y + 50.0).abs() < 1e-9);
}
-1
View File
@@ -147,7 +147,6 @@ mod refedit;
mod region;
mod rename_cmdline;
mod rotate_reference;
mod rotation_grip_input;
mod scale_offset_z;
mod select_keywords;
mod select_similar;
@@ -1,44 +0,0 @@
//! The rotation grip of a dynamic block asks for an angle: Dynamic Input shows one angle box,
//! holding the angle the cursor would give as Properties will show it. The drawing is the
//! synthetic Symbol block of the io tests (Angle1 about its base, its grip at the radius' end).
use cadcraft_engine::Session;
use cadcraft_engine::doc::Handle;
use cadcraft_engine::doc::dynblock::GripPart;
use cadcraft_engine::geom::Vec2;
use serde_json::json;
fn dxf(src: &str) -> String {
src.lines()
.map(str::trim)
.filter(|l| !l.is_empty())
.map(|l| {
let (code, value) = l.split_once(' ').unwrap_or((l, ""));
format!("{code}\n{value}\n")
})
.collect()
}
/// A session with Symbol and a reference to it at (100, 100).
fn session() -> (Session, Handle) {
let src = include_str!("../../../io/tests/data/dynblock_symbol.txt").replace("\r\n", "\n");
let d = cadcraft_io::read_dxf(dxf(&src).as_bytes()).unwrap();
let mut s = Session::empty();
s.open_drawing(d, "symbol", None);
let r = s.execute("insert", &json!({ "name": "Symbol", "at": [100, 100] })).unwrap();
(s, Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap())
}
#[test]
fn the_rotation_grip_asks_for_an_angle_and_shows_it_live() {
let (mut s, h) = session();
s.start_dyn_grip(h, 15, GripPart::End).unwrap();
assert!(s.current_prompt().is_some_and(|p| p.angle), "{:?}", s.current_prompt());
// The grip is at (102, 100); straight above the base is a quarter turn.
assert_eq!(s.live_value(Vec2::new(100.0, 102.0)).as_deref(), Some("90°"));
assert_eq!(s.live_value(Vec2::new(98.0, 100.0)).as_deref(), Some("180°"));
// Nothing is changed by looking.
let props = s.execute("blocks.reference", &json!({ "handle": h.hex() })).unwrap();
let angle = props["properties"].as_array().unwrap().iter().find(|p| p["name"] == "Angle1").unwrap()["value"].clone();
assert_eq!(angle, json!("0"));
}
-508
View File
@@ -1,508 +0,0 @@
0 SECTION
2 HEADER
9 $ACADVER
1 AC1032
9 $HANDSEED
5 200
0 ENDSEC
0 SECTION
2 TABLES
0 TABLE
2 BLOCK_RECORD
5 1
330 0
100 AcDbSymbolTable
70 5
0 BLOCK_RECORD
5 1F
330 1
100 AcDbSymbolTableRecord
100 AcDbBlockTableRecord
2 *Model_Space
340 0
0 BLOCK_RECORD
5 1E
330 1
100 AcDbSymbolTableRecord
100 AcDbBlockTableRecord
2 *Paper_Space
340 0
0 BLOCK_RECORD
5 1D
102 {ACAD_XDICTIONARY
360 60
102 }
330 1
100 AcDbSymbolTableRecord
100 AcDbBlockTableRecord
2 Row
340 0
70 0
280 1
281 1
0 BLOCK_RECORD
5 1C
102 {ACAD_XDICTIONARY
360 70
102 }
330 1
100 AcDbSymbolTableRecord
100 AcDbBlockTableRecord
2 Fan
340 0
70 0
280 1
281 1
0 BLOCK_RECORD
5 1B
102 {ACAD_XDICTIONARY
360 80
102 }
330 1
100 AcDbSymbolTableRecord
100 AcDbBlockTableRecord
2 Grid
340 0
70 0
280 1
281 1
0 ENDTAB
0 ENDSEC
0 SECTION
2 BLOCKS
0 BLOCK
5 20
330 1F
100 AcDbEntity
8 0
100 AcDbBlockBegin
2 *Model_Space
70 0
10 0
20 0
30 0
3 *Model_Space
1
0 ENDBLK
5 21
330 1F
100 AcDbEntity
8 0
100 AcDbBlockEnd
0 BLOCK
5 24
330 1D
100 AcDbEntity
8 0
100 AcDbBlockBegin
2 Row
70 2
10 0
20 0
30 0
3 Row
1
0 LWPOLYLINE
5 30
330 1D
100 AcDbEntity
8 0
100 AcDbPolyline
90 4
70 1
10 0
20 0
10 2
20 0
10 2
20 2
10 0
20 2
1001 AcDbBlockRepETag
1070 1
1071 0
1005 30
0 ENDBLK
5 25
330 1D
100 AcDbEntity
8 0
100 AcDbBlockEnd
0 BLOCK
5 26
330 1C
100 AcDbEntity
8 0
100 AcDbBlockBegin
2 Fan
70 2
10 0
20 0
30 0
3 Fan
1
0 CIRCLE
5 40
330 1C
100 AcDbEntity
8 0
100 AcDbCircle
10 0
20 0
30 0
40 1
1001 AcDbBlockRepETag
1070 1
1071 0
1005 40
0 ENDBLK
5 27
330 1C
100 AcDbEntity
8 0
100 AcDbBlockEnd
0 BLOCK
5 28
330 1B
100 AcDbEntity
8 0
100 AcDbBlockBegin
2 Grid
70 2
10 0
20 0
30 0
3 Grid
1
0 CIRCLE
5 50
330 1B
100 AcDbEntity
8 0
100 AcDbCircle
10 0
20 0
30 0
40 1
1001 AcDbBlockRepETag
1070 1
1071 0
1005 50
0 ENDBLK
5 29
330 1B
100 AcDbEntity
8 0
100 AcDbBlockEnd
0 ENDSEC
0 SECTION
2 ENTITIES
0 ENDSEC
0 SECTION
2 OBJECTS
0 DICTIONARY
5 C
330 0
100 AcDbDictionary
281 1
0 DICTIONARY
5 60
330 1D
100 AcDbDictionary
280 1
281 1
3 ACAD_ENHANCEDBLOCK
360 61
0 ACAD_EVALUATION_GRAPH
5 61
330 60
100 AcDbEvalGraph
96 4
97 4
91 0
93 32
95 1
360 62
91 1
93 32
95 4
360 63
0 BLOCKLINEARPARAMETER
5 62
330 61
100 AcDbEvalExpr
90 1
98 33
99 232
100 AcDbBlockElement
300 Linear
98 33
99 232
1071 0
100 AcDbBlockParameter
280 1
281 0
100 AcDbBlock2PtParameter
1010 0
1020 0
1030 0
1011 2
1021 0
1031 0
170 4
91 3
91 2
91 0
91 0
171 0
172 0
173 0
174 0
177 0
100 AcDbBlockLinearParameter
305 Distance1
306
140 0
307
96 0
141 0
142 0
143 0
175 0
0 BLOCKARRAYACTION
5 63
330 61
100 AcDbEvalExpr
90 4
98 33
99 232
100 AcDbBlockElement
300 Array
98 33
99 232
1071 0
100 AcDbBlockAction
70 0
71 1
330 30
1010 4
1020 3
1030 0
100 AcDbBlockArrayAction
92 1
93 1
94 1
95 1
301 Base
302 End
303 UpdatedBase
304 UpdatedEnd
140 1
141 3
0 DICTIONARY
5 70
330 1C
100 AcDbDictionary
280 1
281 1
3 ACAD_ENHANCEDBLOCK
360 71
0 ACAD_EVALUATION_GRAPH
5 71
330 70
100 AcDbEvalGraph
96 4
97 4
91 0
93 32
95 1
360 72
91 1
93 32
95 4
360 73
0 BLOCKPOLARPARAMETER
5 72
330 71
100 AcDbEvalExpr
90 1
98 33
99 232
100 AcDbBlockElement
300 Polar
98 33
99 232
1071 0
100 AcDbBlockParameter
280 1
281 0
100 AcDbBlock2PtParameter
1010 0
1020 0
1030 0
1011 3
1021 4
1031 0
170 4
91 3
91 2
91 0
91 0
171 0
172 0
173 0
174 0
177 0
100 AcDbBlockPolarParameter
305 Distance1
306
307 Angle1
308
140 0
309
96 0
141 0
142 0
143 0
175 0
410
97 0
145 0
146 0
147 0
176 0
0 BLOCKARRAYACTION
5 73
330 71
100 AcDbEvalExpr
90 4
98 33
99 232
100 AcDbBlockElement
300 Array
98 33
99 232
1071 0
100 AcDbBlockAction
70 0
71 1
330 40
1010 4
1020 5
1030 0
100 AcDbBlockArrayAction
92 1
93 1
94 1
95 1
301 Base
302 End
303 UpdatedBase
304 UpdatedEnd
140 1
141 2
0 DICTIONARY
5 80
330 1B
100 AcDbDictionary
280 1
281 1
3 ACAD_ENHANCEDBLOCK
360 81
0 ACAD_EVALUATION_GRAPH
5 81
330 80
100 AcDbEvalGraph
96 4
97 4
91 0
93 32
95 1
360 82
91 1
93 32
95 6
360 83
0 BLOCKXYPARAMETER
5 82
330 81
100 AcDbEvalExpr
90 1
98 33
99 232
100 AcDbBlockElement
300 XY
98 33
99 232
1071 0
100 AcDbBlockParameter
280 1
281 0
100 AcDbBlock2PtParameter
1010 0
1020 0
1030 0
1011 10
1021 10
1031 0
170 4
91 3
91 2
91 4
91 5
171 0
172 0
173 0
174 0
177 0
100 AcDbBlockXYParameter
305 Y Distance1
306 X Distance1
307
308
141 0
140 0
309
97 1
146 0
147 0
148 0
176 0
410
96 1
142 0
143 0
144 0
175 0
0 BLOCKARRAYACTION
5 83
330 81
100 AcDbEvalExpr
90 6
98 33
99 232
100 AcDbBlockElement
300 Array
98 33
99 232
1071 0
100 AcDbBlockAction
70 0
71 1
330 50
1010 12
1020 12
1030 0
100 AcDbBlockArrayAction
92 1
93 1
94 1
95 1
301 Base
302 End
303 UpdatedBase
304 UpdatedEnd
140 4
141 5
0 ENDSEC
0 EOF
File diff suppressed because it is too large Load Diff
@@ -1,813 +0,0 @@
0 SECTION
2 HEADER
9 $ACADVER
1 AC1032
9 $HANDSEED
5 200
0 ENDSEC
0 SECTION
2 TABLES
0 TABLE
2 BLOCK_RECORD
5 1
330 0
100 AcDbSymbolTable
70 6
0 BLOCK_RECORD
5 1F
330 1
100 AcDbSymbolTableRecord
100 AcDbBlockTableRecord
2 *Model_Space
340 0
0 BLOCK_RECORD
5 1E
330 1
100 AcDbSymbolTableRecord
100 AcDbBlockTableRecord
2 *Paper_Space
340 0
0 BLOCK_RECORD
5 1D
102 {ACAD_XDICTIONARY
360 60
102 }
330 1
100 AcDbSymbolTableRecord
100 AcDbBlockTableRecord
2 Grow
340 0
70 0
280 1
281 1
0 BLOCK_RECORD
5 1C
102 {ACAD_XDICTIONARY
360 70
102 }
330 1
100 AcDbSymbolTableRecord
100 AcDbBlockTableRecord
2 Pinned
340 0
70 0
280 1
281 1
0 BLOCK_RECORD
5 1B
102 {ACAD_XDICTIONARY
360 80
102 }
330 1
100 AcDbSymbolTableRecord
100 AcDbBlockTableRecord
2 Sheet
340 0
70 0
280 1
281 1
0 BLOCK_RECORD
5 1A
102 {ACAD_XDICTIONARY
360 90
102 }
330 1
100 AcDbSymbolTableRecord
100 AcDbBlockTableRecord
2 Tag
340 0
70 0
280 1
281 1
0 ENDTAB
0 ENDSEC
0 SECTION
2 BLOCKS
0 BLOCK
5 20
330 1F
100 AcDbEntity
8 0
100 AcDbBlockBegin
2 *Model_Space
70 0
10 0
20 0
30 0
3 *Model_Space
1
0 ENDBLK
5 21
330 1F
100 AcDbEntity
8 0
100 AcDbBlockEnd
0 BLOCK
5 24
330 1D
100 AcDbEntity
8 0
100 AcDbBlockBegin
2 Grow
70 2
10 0
20 0
30 0
3 Grow
1
0 LWPOLYLINE
5 30
330 1D
100 AcDbEntity
8 0
100 AcDbPolyline
90 4
70 1
10 0
20 0
10 2
20 0
10 2
20 2
10 0
20 2
1001 AcDbBlockRepETag
1070 1
1071 1
1005 30
0 CIRCLE
5 31
330 1D
100 AcDbEntity
8 0
100 AcDbCircle
10 1
20 1
30 0
40 0.5
1001 AcDbBlockRepETag
1070 1
1071 2
1005 31
0 ENDBLK
5 25
330 1D
100 AcDbEntity
8 0
100 AcDbBlockEnd
0 BLOCK
5 26
330 1C
100 AcDbEntity
8 0
100 AcDbBlockBegin
2 Pinned
70 2
10 0
20 0
30 0
3 Pinned
1
0 LWPOLYLINE
5 40
330 1C
100 AcDbEntity
8 0
100 AcDbPolyline
90 4
70 1
10 0
20 0
10 2
20 0
10 2
20 2
10 0
20 2
1001 AcDbBlockRepETag
1070 1
1071 1
1005 40
0 ENDBLK
5 27
330 1C
100 AcDbEntity
8 0
100 AcDbBlockEnd
0 BLOCK
5 28
330 1B
100 AcDbEntity
8 0
100 AcDbBlockBegin
2 Sheet
70 2
10 0
20 0
30 0
3 Sheet
1
0 LWPOLYLINE
5 50
330 1B
100 AcDbEntity
8 0
100 AcDbPolyline
90 4
70 1
10 0
20 0
10 2
20 0
10 2
20 2
10 0
20 2
1001 AcDbBlockRepETag
1070 1
1071 1
1005 50
0 ENDBLK
5 29
330 1B
100 AcDbEntity
8 0
100 AcDbBlockEnd
0 BLOCK
5 2A
330 1A
100 AcDbEntity
8 0
100 AcDbBlockBegin
2 Tag
70 2
10 0
20 0
30 0
3 Tag
1
0 LINE
5 B0
330 1A
100 AcDbEntity
8 0
100 AcDbLine
10 1
20 0
30 0
11 4
21 0
31 0
1001 AcDbBlockRepETag
1070 1
1071 1
1005 B0
0 CIRCLE
5 B1
330 1A
100 AcDbEntity
8 0
100 AcDbCircle
10 4
20 0
30 0
40 0.25
1001 AcDbBlockRepETag
1070 1
1071 2
1005 B1
0 CIRCLE
5 B2
330 1A
100 AcDbEntity
8 0
100 AcDbCircle
10 2
20 2
30 0
40 0.5
1001 AcDbBlockRepETag
1070 1
1071 3
1005 B2
0 ENDBLK
5 2B
330 1A
100 AcDbEntity
8 0
100 AcDbBlockEnd
0 ENDSEC
0 SECTION
2 ENTITIES
0 ENDSEC
0 SECTION
2 OBJECTS
0 DICTIONARY
5 C
330 0
100 AcDbDictionary
281 1
0 DICTIONARY
5 60
330 1D
100 AcDbDictionary
280 1
281 1
3 ACAD_ENHANCEDBLOCK
360 61
0 ACAD_EVALUATION_GRAPH
5 61
330 60
100 AcDbEvalGraph
96 3
97 3
91 0
93 32
95 1
360 62
91 1
93 32
95 2
360 63
91 2
93 32
95 3
360 64
0 BLOCKLINEARPARAMETER
5 62
330 61
100 AcDbEvalExpr
90 1
98 33
99 232
100 AcDbBlockElement
300 Linear
98 33
99 232
1071 0
100 AcDbBlockParameter
280 1
281 0
100 AcDbBlock2PtParameter
1010 0
1020 0
1030 0
1011 2
1021 0
1031 0
170 4
91 3
91 2
91 0
91 0
171 0
172 0
173 0
174 0
177 0
100 AcDbBlockLinearParameter
305 Distance1
306
140 0
307
96 1
141 0
142 0
143 0
175 0
0 BLOCKPOINTPARAMETER
5 63
330 61
100 AcDbEvalExpr
90 2
98 33
99 232
100 AcDbBlockElement
300 Point
98 33
99 232
1071 0
100 AcDbBlockParameter
280 1
281 0
100 AcDbBlock1PtParameter
1010 2
1020 2
1030 0
93 0
170 0
171 0
100 AcDbBlockPointParameter
303 Position1
304
1011 2
1021 2
1031 0
0 BLOCKSCALEACTION
5 64
330 61
100 AcDbEvalExpr
90 3
98 33
99 232
100 AcDbBlockElement
300 Scale
98 33
99 232
1071 0
100 AcDbBlockAction
70 0
71 3
330 30
330 31
330 63
1010 4
1020 3
1030 0
100 AcDbBlockActionWithBasePt
92 1
93 1
301 UpdatedBaseX
302 UpdatedBaseY
1011 0
1021 0
1031 0
280 1
1012 0
1022 0
1032 0
100 AcDbBlockScaleAction
94 1
95 1
96 1
303 Scale
304 XScale
305 YScale
0 DICTIONARY
5 70
330 1C
100 AcDbDictionary
280 1
281 1
3 ACAD_ENHANCEDBLOCK
360 71
0 ACAD_EVALUATION_GRAPH
5 71
330 70
100 AcDbEvalGraph
96 2
97 2
91 0
93 32
95 1
360 72
91 1
93 32
95 2
360 73
0 BLOCKLINEARPARAMETER
5 72
330 71
100 AcDbEvalExpr
90 1
98 33
99 232
100 AcDbBlockElement
300 Linear
98 33
99 232
1071 0
100 AcDbBlockParameter
280 1
281 0
100 AcDbBlock2PtParameter
1010 0
1020 0
1030 0
1011 2
1021 0
1031 0
170 4
91 3
91 2
91 0
91 0
171 0
172 0
173 0
174 0
177 0
100 AcDbBlockLinearParameter
305 Distance1
306
140 0
307
96 0
141 0
142 0
143 0
175 0
0 BLOCKSCALEACTION
5 73
330 71
100 AcDbEvalExpr
90 2
98 33
99 232
100 AcDbBlockElement
300 Scale
98 33
99 232
1071 0
100 AcDbBlockAction
70 0
71 1
330 40
1010 4
1020 3
1030 0
100 AcDbBlockActionWithBasePt
92 1
93 1
301 UpdatedBaseX
302 UpdatedBaseY
1011 0
1021 0
1031 0
280 0
1012 2
1022 2
1032 0
100 AcDbBlockScaleAction
94 1
95 1
96 1
303 Scale
304 XScale
305 YScale
0 DICTIONARY
5 80
330 1B
100 AcDbDictionary
280 1
281 1
3 ACAD_ENHANCEDBLOCK
360 81
0 ACAD_EVALUATION_GRAPH
5 81
330 80
100 AcDbEvalGraph
96 2
97 2
91 0
93 32
95 1
360 82
91 1
93 32
95 2
360 83
0 BLOCKXYPARAMETER
5 82
330 81
100 AcDbEvalExpr
90 1
98 33
99 232
100 AcDbBlockElement
300 XY
98 33
99 232
1071 0
100 AcDbBlockParameter
280 1
281 0
100 AcDbBlock2PtParameter
1010 0
1020 0
1030 0
1011 2
1021 2
1031 0
170 4
91 3
91 2
91 4
91 5
171 0
172 0
173 0
174 0
177 0
100 AcDbBlockXYParameter
305 Y Distance1
306 X Distance1
307
308
141 0
140 0
309
97 0
146 0
147 0
148 0
176 0
410
96 0
142 0
143 0
144 0
175 0
0 BLOCKSCALEACTION
5 83
330 81
100 AcDbEvalExpr
90 2
98 33
99 232
100 AcDbBlockElement
300 Scale
98 33
99 232
1071 0
100 AcDbBlockAction
70 0
71 1
330 50
1010 4
1020 3
1030 0
100 AcDbBlockActionWithBasePt
92 1
93 1
301 UpdatedBaseX
302 UpdatedBaseY
1011 0
1021 0
1031 0
280 1
1012 0
1022 0
1032 0
100 AcDbBlockScaleAction
94 1
95 1
96 1
303 Scale
304 XScale
305 YScale
0 DICTIONARY
5 90
330 1A
100 AcDbDictionary
280 1
281 1
3 ACAD_ENHANCEDBLOCK
360 91
0 ACAD_EVALUATION_GRAPH
5 91
330 90
100 AcDbEvalGraph
96 3
97 3
91 0
93 32
95 1
360 92
91 1
93 32
95 2
360 93
91 2
93 32
95 3
360 94
0 BLOCKPOLARPARAMETER
5 92
330 91
100 AcDbEvalExpr
90 1
98 33
99 232
100 AcDbBlockElement
300 Polar
98 33
99 232
1071 0
100 AcDbBlockParameter
280 1
281 0
100 AcDbBlock2PtParameter
1010 0
1020 0
1030 0
1011 4
1021 0
1031 0
170 4
91 3
91 2
91 0
91 0
171 0
172 0
173 0
174 0
177 0
100 AcDbBlockPolarParameter
305 Distance1
306
307 Angle1
308
140 0
309
96 0
141 0
142 0
143 0
175 0
410
97 0
145 0
146 0
147 0
176 0
0 BLOCKPOINTPARAMETER
5 93
330 91
100 AcDbEvalExpr
90 2
98 33
99 232
100 AcDbBlockElement
300 Point
98 33
99 232
1071 0
100 AcDbBlockParameter
280 1
281 0
100 AcDbBlock1PtParameter
1010 4
1020 1
1030 0
93 0
170 0
171 0
100 AcDbBlockPointParameter
303 Position1
304
1011 4
1021 1
1031 0
0 BLOCKPOLARSTRETCHACTION
5 94
330 91
100 AcDbEvalExpr
90 3
98 33
99 232
100 AcDbBlockElement
300 Polar Stretch
98 33
99 232
1071 0
100 AcDbBlockAction
70 0
71 3
330 B0
330 B1
330 93
1010 5
1020 -1
1030 0
100 AcDbBlockPolarStretchAction
92 1
301 EndXDelta
93 1
302 EndYDelta
94 1
303 Base
95 1
304 End
96 1
305 UpdatedBase
97 1
306 UpdatedEnd
73 2
1011 3.5
1021 -0.5
1011 4.5
1021 1.5
72 1
331 B2
74 1
332 B0
75 1
76 1
78 0
141 1
140 0
77 0
0 ENDSEC
0 EOF
-469
View File
@@ -1,469 +0,0 @@
0 SECTION
2 HEADER
9 $ACADVER
1 AC1032
9 $HANDSEED
5 200
0 ENDSEC
0 SECTION
2 TABLES
0 TABLE
2 BLOCK_RECORD
5 1
330 0
100 AcDbSymbolTable
70 3
0 BLOCK_RECORD
5 1F
330 1
100 AcDbSymbolTableRecord
100 AcDbBlockTableRecord
2 *Model_Space
340 0
0 BLOCK_RECORD
5 1E
330 1
100 AcDbSymbolTableRecord
100 AcDbBlockTableRecord
2 *Paper_Space
340 0
0 BLOCK_RECORD
5 1D
102 {ACAD_XDICTIONARY
360 60
102 }
330 1
100 AcDbSymbolTableRecord
100 AcDbBlockTableRecord
2 Symbol
340 0
70 0
280 1
281 1
0 ENDTAB
0 ENDSEC
0 SECTION
2 BLOCKS
0 BLOCK
5 20
330 1F
100 AcDbEntity
8 0
100 AcDbBlockBegin
2 *Model_Space
70 0
10 0
20 0
30 0
3 *Model_Space
1
0 ENDBLK
5 21
330 1F
100 AcDbEntity
8 0
100 AcDbBlockEnd
0 BLOCK
5 24
330 1D
100 AcDbEntity
8 0
100 AcDbBlockBegin
2 Symbol
70 2
10 0
20 0
30 0
3 Symbol
1
0 CIRCLE
5 30
330 1D
100 AcDbEntity
8 0
100 AcDbCircle
10 0
20 0
30 0
40 1
0 LINE
5 31
330 1D
100 AcDbEntity
8 0
100 AcDbLine
10 0
20 0
30 0
11 0
21 3
31 0
0 ATTDEF
5 32
330 1D
100 AcDbEntity
8 0
100 AcDbText
10 1
20 2
30 0
40 1
1 X
50 90
7 Standard
100 AcDbAttributeDefinition
3 Tag
2 TAG
70 0
0 ENDBLK
5 25
330 1D
100 AcDbEntity
8 0
100 AcDbBlockEnd
0 ENDSEC
0 SECTION
2 ENTITIES
0 ENDSEC
0 SECTION
2 OBJECTS
0 DICTIONARY
5 C
330 0
100 AcDbDictionary
281 1
0 DICTIONARY
5 60
330 1D
100 AcDbDictionary
280 1
281 1
3 ACAD_ENHANCEDBLOCK
360 61
0 ACAD_EVALUATION_GRAPH
5 61
102 {ACAD_REACTORS
330 60
102 }
330 60
100 AcDbEvalGraph
96 8
97 8
91 0
93 32
95 15
360 62
92 -1
92 -1
92 -1
92 -1
91 1
93 32
95 16
360 63
92 -1
92 -1
92 -1
92 -1
91 2
93 32
95 19
360 64
92 -1
92 -1
92 -1
92 -1
91 3
93 32
95 20
360 65
92 -1
92 -1
92 -1
92 -1
91 4
93 32
95 21
360 66
92 -1
92 -1
92 -1
92 -1
91 5
93 32
95 25
360 67
92 -1
92 -1
92 -1
92 -1
91 6
93 32
95 26
360 68
92 -1
92 -1
92 -1
92 -1
91 7
93 32
95 30
360 69
0 BLOCKROTATIONPARAMETER
5 62
330 61
100 AcDbEvalExpr
90 15
98 33
99 232
100 AcDbBlockElement
300 Rotation
98 33
99 232
1071 0
100 AcDbBlockParameter
280 1
281 0
100 AcDbBlock2PtParameter
1010 0
1020 0
1030 0
1011 2
1021 0
1031 0
170 4
91 0
91 16
91 0
91 0
171 0
172 0
173 0
174 0
177 0
100 AcDbBlockRotationParameter
305 Angle1
306
1011 2
1021 0
1031 0
140 0
307
96 3
141 0
142 6.283185307179586
143 0
175 0
0 BLOCKROTATIONGRIP
5 63
330 61
100 AcDbEvalExpr
90 16
98 33
99 232
100 AcDbBlockElement
300 Grip
98 33
99 232
1071 0
100 AcDbBlockGrip
91 0
92 0
1010 2
1020 0
1030 0
280 0
93 -1
100 AcDbBlockRotationGrip
0 BLOCKROTATEACTION
5 64
330 61
100 AcDbEvalExpr
90 19
98 33
99 232
100 AcDbBlockElement
300 Rotate
98 33
99 232
1071 0
100 AcDbBlockAction
70 2
91 0
91 0
71 4
330 31
330 32
330 65
330 68
1010 1
1020 1
1030 0
100 AcDbBlockActionWithBasePt
92 15
93 15
301 UpdatedBaseX
302 UpdatedBaseY
1011 0
1021 0
1031 0
280 1
1012 0
1022 0
1032 0
100 AcDbBlockRotationAction
94 15
303 AngleDelta
0 BLOCKFLIPPARAMETER
5 65
330 61
100 AcDbEvalExpr
90 20
98 33
99 232
100 AcDbBlockElement
300 Flip
98 33
99 232
1071 0
100 AcDbBlockParameter
280 1
281 0
100 AcDbBlock2PtParameter
1010 0
1020 0
1030 0
1011 -10
1021 0
1031 0
170 4
91 21
91 0
91 0
91 0
171 0
172 0
173 0
174 0
177 0
100 AcDbBlockFlipParameter
305 Flip state1
306
307 Not flipped
308 Flipped
1012 -12
1022 0
1032 0
309 UpdatedFlip
96 21
0 BLOCKFLIPGRIP
5 66
330 61
100 AcDbEvalExpr
90 21
98 33
99 232
100 AcDbBlockElement
300 Grip
98 33
99 232
1071 0
100 AcDbBlockGrip
91 0
92 0
1010 -2
1020 0
1030 0
280 0
93 -1
100 AcDbBlockFlipGrip
0 BLOCKFLIPACTION
5 67
330 61
100 AcDbEvalExpr
90 25
98 33
99 232
100 AcDbBlockElement
300 Flip1
98 33
99 232
1071 0
100 AcDbBlockAction
70 2
91 0
91 0
71 3
330 31
330 32
330 68
1010 -6
1020 0
1030 0
100 AcDbBlockFlipAction
92 20
93 20
94 20
95 20
301 Flip
302 UpdatedFlip
303 UpdatedBase
304 UpdatedEnd
0 BLOCKPOINTPARAMETER
5 68
330 61
100 AcDbEvalExpr
90 26
98 33
99 232
100 AcDbBlockElement
300 Point
98 33
99 232
1071 0
100 AcDbBlockParameter
280 1
281 0
100 AcDbBlock1PtParameter
1010 0
1020 3
1030 0
93 0
170 0
171 0
100 AcDbBlockPointParameter
303 Position1
304
1011 0
1021 4
1031 0
0 BLOCKMOVEACTION
5 69
330 61
100 AcDbEvalExpr
90 30
98 33
99 232
100 AcDbBlockElement
300 Move
98 33
99 232
1071 0
100 AcDbBlockAction
70 2
91 0
91 0
71 1
330 32
1010 0
1020 4
1030 0
100 AcDbBlockMoveAction
92 26
93 26
301 XDelta
302 YDelta
140 1
141 0
0 ENDSEC
0 EOF
-206
View File
@@ -1,206 +0,0 @@
//! Array actions of dynamic blocks: a reference repeats the arrayed objects as far as its linear,
//! polar or XY parameter reaches, as AutoCAD does (one copy per whole column along a distance; a
//! whole number of columns by rows across an XY parameter, or just the object when either is
//! short of one), marks the copies as AutoCAD marks them, and keeps the right number of copies
//! through later changes and a save.
//!
//! The fixture is synthetic: block Row (a 2×2 square, Distance1 from the origin to (2, 0), copies
//! every 3), Fan (a circle, Distance1/Angle1 from the origin to (3, 4), copies every 2) and Grid
//! (a circle, X Distance1/Y Distance1 from the origin to (10, 10), columns every 5 and rows every
//! 4, distances at least 0).
use cadcraft_doc::dynblock::{ActionKind, GripPart, GripShape, ParameterKind, custom_properties, drag_grip, dynamic_block, grips, set_property};
use cadcraft_doc::geom::{Vec2, Vec3};
use cadcraft_doc::{Drawing, EntityKind, Handle};
use cadcraft_io::{read_dxf, write_dxf};
fn dxf(src: &str) -> String {
src.lines()
.map(str::trim)
.filter(|l| !l.is_empty())
.map(|l| {
let (code, value) = l.split_once(' ').unwrap_or((l, ""));
format!("{code}\n{value}\n")
})
.collect()
}
/// The fixture with a reference to `block` at (100, 100).
fn reference(block: &str) -> (Drawing, Handle) {
let mut d = read_dxf(dxf(&include_str!("../data/dynblock_arrays.txt").replace("\r\n", "\n")).as_bytes()).unwrap();
let ins = cadcraft_doc::Insert {
block: block.into(),
insert: Vec3::new(100.0, 100.0, 0.0),
scale: Vec3::new(1.0, 1.0, 1.0),
rotation: 0.0,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
let r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap();
(d, r)
}
fn props(d: &Drawing, r: Handle) -> Vec<(String, String)> {
custom_properties(d, r).unwrap().1.into_iter().map(|p| (p.name, p.value)).collect()
}
fn pairs(v: &[(&str, &str)]) -> Vec<(String, String)> {
v.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect()
}
/// Where each object of the reference's block is (a circle's centre, a polyline's first vertex).
fn places(d: &Drawing, r: Handle) -> Vec<(f64, f64)> {
let Some(EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("a reference") };
let round = |v: f64| (v * 1000.0).round() / 1000.0;
d.block(&i.block)
.unwrap()
.entities
.iter()
.map(|e| match &e.kind {
EntityKind::Circle(c) => (round(c.center.x), round(c.center.y)),
EntityKind::LwPolyline(p) => (round(p.vertices[0].p.x), round(p.vertices[0].p.y)),
k => panic!("unexpected {k:?}"),
})
.collect()
}
/// Whether each object of the reference's block is marked as an array's copy.
fn marked(d: &Drawing, r: Handle) -> Vec<bool> {
let Some(EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("a reference") };
let mark = |e: &cadcraft_doc::Entity| e.common.xdata.iter().any(|t| t.code == 1001 && t.value == "AcDbBlockArrayActionTag");
d.block(&i.block).unwrap().entities.iter().map(|e| mark(e)).collect()
}
#[test]
fn reads_array_actions_and_polar_and_xy_parameters() {
let (d, _) = reference("Row");
let m = dynamic_block(&d, "Row").unwrap();
assert!(matches!(m.actions[0].kind, ActionKind::Array { column: 3.0, row: 1.0 }));
assert_eq!(m.actions[0].connections.len(), 4);
let m = dynamic_block(&d, "Fan").unwrap();
let ParameterKind::Polar { label, angle_label, .. } = &m.parameters[0].kind else { panic!("a polar parameter") };
assert_eq!((label.as_str(), angle_label.as_str()), ("Distance1", "Angle1"));
let m = dynamic_block(&d, "Grid").unwrap();
let ParameterKind::Xy { x_label, y_label, x_values, y_values, .. } = &m.parameters[0].kind else { panic!("an XY parameter") };
assert_eq!((x_label.as_str(), y_label.as_str()), ("X Distance1", "Y Distance1"));
assert!(x_values.has_minimum() && y_values.has_minimum());
assert_eq!(m.parameters[0].grips, vec![3, 2, 4, 5], "base, end and the two corner grips");
assert!(matches!(m.actions[0].kind, ActionKind::Array { column: 5.0, row: 4.0 }));
}
#[test]
fn polar_and_xy_parameters_show_their_two_properties() {
let (d, r) = reference("Fan");
assert_eq!(props(&d, r), pairs(&[("Distance1", "5.0000"), ("Angle1", "53")]));
let (d, r) = reference("Grid");
assert_eq!(props(&d, r), pairs(&[("X Distance1", "10.0000"), ("Y Distance1", "10.0000")]));
}
#[test]
fn a_distance_repeats_the_objects_once_per_whole_column() {
let (mut d, r) = reference("Row");
set_property(&mut d, r, "Distance1", "9").unwrap();
assert_eq!(places(&d, r), vec![(0.0, 0.0), (3.0, 0.0), (6.0, 0.0)]);
assert_eq!(marked(&d, r), vec![false, true, true], "AutoCAD marks every copy but the first");
// Short of a whole column: one fewer; short of one: the object alone.
set_property(&mut d, r, "Distance1", "8.9").unwrap();
assert_eq!(places(&d, r), vec![(0.0, 0.0), (3.0, 0.0)]);
set_property(&mut d, r, "Distance1", "2.5").unwrap();
assert_eq!(places(&d, r), vec![(0.0, 0.0)]);
assert_eq!(marked(&d, r), vec![false]);
set_property(&mut d, r, "Distance1", "12").unwrap();
assert_eq!(places(&d, r).len(), 4);
}
#[test]
fn a_polar_parameter_repeats_along_its_angle() {
let (mut d, r) = reference("Fan");
set_property(&mut d, r, "Distance1", "7").unwrap();
assert_eq!(places(&d, r), vec![(0.0, 0.0), (1.2, 1.6), (2.4, 3.2)]);
set_property(&mut d, r, "Angle1", "90").unwrap();
assert_eq!(places(&d, r), vec![(0.0, 0.0), (0.0, 2.0), (0.0, 4.0)]);
assert_eq!(props(&d, r), pairs(&[("Distance1", "7.0000"), ("Angle1", "90")]));
}
#[test]
fn an_xy_parameter_repeats_in_columns_and_rows() {
let (mut d, r) = reference("Grid");
// 10 × 10 with columns every 5 and rows every 4: 2 by 2.
set_property(&mut d, r, "Y Distance1", "10").unwrap();
assert_eq!(places(&d, r), vec![(0.0, 0.0), (5.0, 0.0), (0.0, 4.0), (5.0, 4.0)]);
set_property(&mut d, r, "Y Distance1", "13").unwrap();
assert_eq!(places(&d, r).len(), 6, "2 columns by 3 rows, the earlier copies replaced");
assert_eq!(marked(&d, r), vec![false, true, true, true, true, true]);
// Short of one column: the object alone, however many rows fit.
set_property(&mut d, r, "X Distance1", "4").unwrap();
assert_eq!(places(&d, r), vec![(0.0, 0.0)]);
// Below the value set's minimum: refused, as AutoCAD refuses it.
assert!(set_property(&mut d, r, "X Distance1", "-10").is_err());
assert_eq!(props(&d, r), pairs(&[("X Distance1", "4.0000"), ("Y Distance1", "13.0000")]));
}
#[test]
fn xy_grips_move_the_base_end_and_corners() {
let (mut d, r) = reference("Grid");
let gs = grips(&d, r);
let summary: Vec<(GripPart, GripShape, (f64, f64))> = gs.iter().map(|g| (g.part, g.shape, (g.at.x, g.at.y))).collect();
assert_eq!(
summary,
vec![
(GripPart::Base, GripShape::Point, (100.0, 100.0)),
(GripPart::End, GripShape::Point, (110.0, 110.0)),
(GripPart::BaseXEndY, GripShape::Point, (100.0, 110.0)),
(GripPart::BaseYEndX, GripShape::Point, (110.0, 100.0)),
]
);
// The base X and end Y corner, dragged left and up: the base moves left (the circle with
// it, as AutoCAD's arrays follow the base), the end up.
drag_grip(&mut d, r, 1, GripPart::BaseXEndY, Vec2::new(95.0, 112.0)).unwrap();
assert_eq!(props(&d, r), pairs(&[("X Distance1", "15.0000"), ("Y Distance1", "12.0000")]));
assert_eq!(places(&d, r), vec![(-5.0, 0.0), (0.0, 0.0), (5.0, 0.0), (-5.0, 4.0), (0.0, 4.0), (5.0, 4.0), (-5.0, 8.0), (0.0, 8.0), (5.0, 8.0)]);
// A corner past the base: below the minimum, refused.
assert!(drag_grip(&mut d, r, 1, GripPart::BaseYEndX, Vec2::new(90.0, 100.0)).is_err());
assert!(drag_grip(&mut d, r, 1, GripPart::At, Vec2::new(90.0, 100.0)).is_err());
}
#[test]
fn polar_grips_move_the_end_and_the_base() {
let (mut d, r) = reference("Fan");
let parts: Vec<GripPart> = grips(&d, r).into_iter().map(|g| g.part).collect();
assert_eq!(parts, vec![GripPart::Base, GripPart::End]);
drag_grip(&mut d, r, 1, GripPart::End, Vec2::new(100.0, 106.0)).unwrap();
assert_eq!(props(&d, r), pairs(&[("Distance1", "6.0000"), ("Angle1", "90")]));
assert_eq!(places(&d, r), vec![(0.0, 0.0), (0.0, 2.0), (0.0, 4.0)]);
}
#[test]
fn copies_and_values_survive_a_save() {
let (mut d, r) = reference("Grid");
set_property(&mut d, r, "X Distance1", "12").unwrap();
let back = read_dxf(write_dxf(&d).as_bytes()).unwrap();
assert_eq!(props(&back, r), props(&d, r));
assert_eq!(places(&back, r), places(&d, r));
// Changed again after the save: still one set of copies.
let mut back = back;
set_property(&mut back, r, "Y Distance1", "5").unwrap();
assert_eq!(places(&back, r), vec![(0.0, 0.0), (5.0, 0.0)]);
}
#[test]
fn hostile_arrays_are_refused_not_built() {
let (mut d, r) = reference("Grid");
// A billion columns: refused before any copy is made.
assert!(set_property(&mut d, r, "X Distance1", "1e10").is_err());
assert!(set_property(&mut d, r, "X Distance1", "NaN").is_err());
assert!(set_property(&mut d, r, "X Distance1", "inf").is_err());
assert_eq!(places(&d, r), vec![(0.0, 0.0)]);
let (mut d, r) = reference("Row");
assert!(set_property(&mut d, r, "Distance1", "1e300").is_err());
let (mut d, r) = reference("Fan");
assert!(set_property(&mut d, r, "Angle1", "nan").is_err());
assert!(set_property(&mut d, r, "Distance1", "0").is_err());
}
-287
View File
@@ -1,287 +0,0 @@
//! Base point and alignment parameters of dynamic blocks, and lookup tables that set angles, flip
//! states, XY distances and positions, as AutoCAD applies them:
//! - an action that moves a base point parameter moves the reference's insertion point with it,
//! and the block's objects move back so the parameter stays at the block's base point;
//! - an alignment grip dragged next to an object moves the reference so the alignment's base is on
//! the object and turns it so the alignment runs along the object, its right side toward the
//! cursor;
//! - lookup tables set and read rotation angles (`UpdatedAngle`, radians), flip states
//! (`UpdatedFlip`), XY distances (`UpdatedDistanceX`/`Y`), polar distances and angles and
//! positions (`UpdatedX`/`Y`, from the block's base point).
//!
//! The fixture is synthetic, laid out as AutoCAD writes these blocks: Shift (a 10×5 rectangle left
//! of the origin, Distance1 along its bottom, a stretch of its right side holding the base point
//! parameter, an attribute TAG at (-8, 0); a reference at (100, 100) with its attribute at (92, 100)),
//! Align (a 4×2 rectangle, a perpendicular alignment from the origin along X), Turn (a 4×2
//! rectangle turned by Angle1 about the origin; Lookup1 gives Up 90°, Left 180°, Zero 0°) and Many
//! (Flip state1, X/Y Distance1, polar Distance1/Angle1 and Position1, all set by Lookup1's rows A
//! and B, B being the block's own values). A line at 30° runs from (120, 100) to (140, 111.547).
use cadcraft_doc::dynblock::{GripShape, ParameterKind, Value, align_grip, custom_properties, dynamic_block, grips, reference, set_property};
use cadcraft_doc::geom::{Vec2, Vec3};
use cadcraft_doc::{Drawing, EntityKind, Handle};
use cadcraft_io::{read_dxf, write_dxf};
fn dxf(src: &str) -> String {
src.lines()
.map(str::trim)
.filter(|l| !l.is_empty())
.map(|l| {
let (code, value) = l.split_once(' ').unwrap_or((l, ""));
format!("{code}\n{value}\n")
})
.collect()
}
fn fixture() -> Drawing {
read_dxf(dxf(&include_str!("../data/dynblock_params.txt").replace("\r\n", "\n")).as_bytes()).unwrap()
}
/// The fixture with a reference to `block` at (100, 100) turned by `rotation`.
fn reference_to(block: &str, rotation: f64) -> (Drawing, Handle) {
let mut d = fixture();
let ins = cadcraft_doc::Insert {
block: block.into(),
insert: Vec3::new(100.0, 100.0, 0.0),
scale: Vec3::new(1.0, 1.0, 1.0),
rotation,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
let r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap();
(d, r)
}
fn props(d: &Drawing, r: Handle) -> Vec<(String, String)> {
custom_properties(d, r).unwrap().1.into_iter().map(|p| (p.name, p.value)).collect()
}
fn prop(d: &Drawing, r: Handle, name: &str) -> String {
props(d, r).into_iter().find(|(n, _)| n == name).map(|(_, v)| v).unwrap_or_else(|| panic!("no {name}"))
}
fn round(v: f64) -> f64 {
(v * 1000.0).round() / 1000.0 + 0.0
}
fn insert(d: &Drawing, r: Handle) -> &cadcraft_doc::Insert {
let Some(EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("a reference") };
i
}
/// The reference's polyline corners (lowest and highest) in block coordinates.
fn outline(d: &Drawing, r: Handle) -> [f64; 4] {
let b = d.block(&insert(d, r).block).unwrap();
let pl = b
.entities
.iter()
.find_map(|e| match &e.kind {
EntityKind::LwPolyline(p) => Some(p),
_ => None,
})
.unwrap();
let xs = pl.vertices.iter().map(|v| v.p.x);
let ys = pl.vertices.iter().map(|v| v.p.y);
[
round(xs.clone().fold(f64::MAX, f64::min)),
round(ys.clone().fold(f64::MAX, f64::min)),
round(xs.fold(f64::MIN, f64::max)),
round(ys.fold(f64::MIN, f64::max)),
]
}
fn at(d: &Drawing, r: Handle) -> (f64, f64) {
let i = insert(d, r);
(round(i.insert.x), round(i.insert.y))
}
#[test]
fn reads_the_alignment_type_and_shows_its_grip() {
let (d, r) = reference_to("Align", 0.0);
let m = dynamic_block(&d, "Align").unwrap();
assert!(matches!(m.parameters[0].kind, ParameterKind::Alignment { perpendicular: true, .. }));
let g = grips(&d, r);
let a = g.iter().find(|g| g.shape == GripShape::Alignment).expect("an alignment grip");
// At the base point, pointing to the left of the alignment's direction (as AutoCAD draws it).
assert_eq!((round(a.at.x), round(a.at.y)), (100.0, 100.0));
assert_eq!((round(a.dir.x), round(a.dir.y)), (0.0, 1.0));
}
#[test]
fn a_moved_base_point_moves_the_insertion_point() {
let mut d = fixture();
let r = Handle(0xE0);
set_property(&mut d, r, "Distance1", "15").unwrap();
// Measured in AutoCAD: the reference moves to (105, 100) and its block runs from -15 to 0.
assert_eq!(at(&d, r), (105.0, 100.0));
assert_eq!(outline(&d, r), [-15.0, -2.5, 0.0, 2.5]);
assert_eq!(prop(&d, r, "Distance1"), "15.0000");
// The values as AutoCAD records them: the base point at the block's base, the distance moved back.
let v = reference(&d, r).unwrap().values;
assert_eq!(v.get(&1), Some(&Value::Point { at: Vec3::new(0.0, 0.0, 0.0) }));
assert_eq!(v.get(&2), Some(&Value::Points { base: Vec3::new(-15.0, -2.5, 0.0), end: Vec3::new(0.0, -2.5, 0.0) }));
// The attribute stays where it was in the drawing (its definition didn't move).
let a = &insert(&d, r).attribs[0];
assert_eq!((round(a.text.insert.x), round(a.text.insert.y)), (92.0, 100.0));
// And back, from there.
set_property(&mut d, r, "Distance1", "12").unwrap();
assert_eq!(at(&d, r), (102.0, 100.0));
assert_eq!(outline(&d, r), [-12.0, -2.5, 0.0, 2.5]);
// A save keeps it.
let back = read_dxf(write_dxf(&d).as_bytes()).unwrap();
assert_eq!(at(&back, r), (102.0, 100.0));
assert_eq!(prop(&back, r, "Distance1"), "12.0000");
}
/// AutoCAD takes a distance of 0 (title block value lists offer it); the distance keeps its
/// direction for the next change.
#[test]
fn a_distance_of_0_keeps_its_direction() {
let mut d = fixture();
let r = Handle(0xE0);
set_property(&mut d, r, "Distance1", "0").unwrap();
assert_eq!(prop(&d, r, "Distance1"), "0.0000");
assert_eq!(at(&d, r), (90.0, 100.0));
set_property(&mut d, r, "Distance1", "15").unwrap();
assert_eq!(at(&d, r), (105.0, 100.0));
assert_eq!(outline(&d, r), [-15.0, -2.5, 0.0, 2.5]);
assert!(set_property(&mut d, r, "Distance1", "-1").is_err());
}
#[test]
fn a_turned_reference_moves_along_its_own_axis() {
let (mut d, r) = reference_to("Shift", std::f64::consts::FRAC_PI_2);
set_property(&mut d, r, "Distance1", "15").unwrap();
assert_eq!(at(&d, r), (100.0, 105.0));
}
#[test]
fn an_alignment_follows_a_line() {
let line = Vec2::new(30f64.to_radians().cos(), 30f64.to_radians().sin());
let foot = Vec2::new(120.0, 100.0) + line * 10.0;
// Measured in AutoCAD: from below the line the reference turns to 30°, from above to 210°, its
// alignment's base on the line.
for (side, rotation) in [(-0.5, 30.0), (0.5, 210.0)] {
let (mut d, r) = reference_to("Align", 0.0);
let cursor = foot + line.perp() * side;
align_grip(&mut d, r, 1, cursor, Some((foot, line))).unwrap();
assert_eq!(round(insert(&d, r).rotation.to_degrees()), rotation);
assert_eq!(at(&d, r), (round(foot.x), round(foot.y)));
}
}
#[test]
fn an_alignment_follows_a_circle() {
// A circle about (150, 150), its nearest point at 225°: outside, the reference turns to 315°
// (counterclockwise along the circle), inside to 135°, as in AutoCAD.
let c = Vec2::new(150.0, 150.0);
let out = Vec2::new(225f64.to_radians().cos(), 225f64.to_radians().sin());
let foot = c + out * 10.0;
for (r_cursor, rotation) in [(10.5, 315.0), (9.5, 135.0)] {
let (mut d, r) = reference_to("Align", 0.0);
align_grip(&mut d, r, 1, c + out * r_cursor, Some((foot, out.perp()))).unwrap();
assert_eq!(round(insert(&d, r).rotation.to_degrees()), rotation);
}
}
#[test]
fn an_alignment_grip_away_from_objects_only_moves() {
let (mut d, r) = reference_to("Align", 0.5);
align_grip(&mut d, r, 1, Vec2::new(90.0, 80.0), None).unwrap();
assert_eq!(at(&d, r), (90.0, 80.0));
assert_eq!(insert(&d, r).rotation, 0.5);
// On the object itself, the side the grip came from decides.
let (mut d, r) = reference_to("Align", 0.0);
let line = Vec2::new(1.0, 0.0);
align_grip(&mut d, r, 1, Vec2::new(110.0, 90.0), Some((Vec2::new(110.0, 90.0), line))).unwrap();
// The grip was above the line (y = 90): its right side faces up, so the alignment runs to -X.
assert_eq!(round(insert(&d, r).rotation.to_degrees()), 180.0);
assert!(align_grip(&mut d, r, 1, Vec2::new(f64::NAN, 0.0), None).is_err());
assert!(align_grip(&mut d, r, 7, Vec2::new(0.0, 0.0), None).is_err());
}
#[test]
fn a_lookup_sets_and_reads_an_angle() {
let (mut d, r) = reference_to("Turn", 0.0);
assert_eq!(prop(&d, r, "Lookup1"), "Zero");
set_property(&mut d, r, "Lookup1", "Up").unwrap();
assert_eq!(prop(&d, r, "Angle1"), "90");
assert_eq!(outline(&d, r), [-2.0, 0.0, 0.0, 4.0]);
// Reverse: an angle in the table gives its row.
set_property(&mut d, r, "Angle1", "180").unwrap();
assert_eq!(prop(&d, r, "Lookup1"), "Left");
set_property(&mut d, r, "Angle1", "45").unwrap();
assert_eq!(prop(&d, r, "Lookup1"), "Custom");
assert!(custom_properties(&d, r).unwrap().1.iter().any(|p| p.name == "Lookup1" && p.editable));
}
#[test]
fn a_lookup_sets_flips_xy_polar_and_positions() {
let (mut d, r) = reference_to("Many", 0.0);
// The block's own values are row B.
assert_eq!(prop(&d, r, "Lookup1"), "B");
set_property(&mut d, r, "Lookup1", "A").unwrap();
// As AutoCAD sets them.
for (name, value) in [
("Flip state1", "Flipped"),
("X Distance1", "6.0000"),
("Y Distance1", "3.0000"),
("Distance1", "5.0000"),
("Angle1", "30"),
("Position1 X", "1.0000"),
("Position1 Y", "0.5000"),
("Lookup1", "A"),
] {
assert_eq!(prop(&d, r, name), value, "{name}");
}
// The values are recorded as AutoCAD lays them out (it doesn't take the reference otherwise): a
// flip state after its points, and the flip grip's state on its own after two header groups.
let codes: Vec<Vec<i32>> = d
.foreign
.objects
.iter()
.filter(|o| o.kind == "XRECORD")
.map(|o| o.tags.iter().map(|t| t.code).filter(|c| [10, 70].contains(c)).collect())
.collect();
assert!(codes.contains(&vec![10, 10, 70]), "{codes:?}");
assert!(codes.contains(&vec![70, 70, 70, 70]), "{codes:?}");
// A save keeps it, and the reverse lookup reads it back.
let back = read_dxf(write_dxf(&d).as_bytes()).unwrap();
assert_eq!(prop(&back, r, "Lookup1"), "A");
assert_eq!(prop(&back, r, "Flip state1"), "Flipped");
// One input off the table's rows: no row matches.
set_property(&mut d, r, "Flip state1", "Not flipped").unwrap();
assert_eq!(prop(&d, r, "Lookup1"), "Custom");
set_property(&mut d, r, "Lookup1", "B").unwrap();
assert_eq!(prop(&d, r, "X Distance1"), "4.0000");
assert_eq!(prop(&d, r, "Position1 X"), "2.0000");
}
#[test]
fn a_lookup_cell_that_isnt_a_number_is_refused() {
let src = include_str!("../data/dynblock_params.txt").replace("\r\n", "\n").replace("302 1.570796326794896", "302 up-ish");
let mut d = read_dxf(dxf(&src).as_bytes()).unwrap();
let ins = cadcraft_doc::Insert {
block: "Turn".into(),
insert: Vec3::new(0.0, 0.0, 0.0),
scale: Vec3::new(1.0, 1.0, 1.0),
rotation: 0.0,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
let r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap();
let before = insert(&d, r).block.clone();
assert!(set_property(&mut d, r, "Lookup1", "Up").is_err());
assert_eq!(insert(&d, r).block, before);
// The other rows still work, and reading the table doesn't trip on the bad cell.
set_property(&mut d, r, "Lookup1", "Left").unwrap();
assert_eq!(prop(&d, r, "Angle1"), "180");
}
+4 -54
View File
@@ -114,7 +114,7 @@ fn a_scale_action_survives_a_dwg_save() {
cadcraft_io::dwg_worker::allow_in_process();
let d = read_dxf(dxf(&with_scale_action()).as_bytes()).unwrap();
let before = dynamic_block(&d, "Door").unwrap();
assert!(before.actions.iter().any(|a| a.node == 7 && matches!(a.kind, ActionKind::Scale { .. })), "{:?}", before.actions);
assert!(before.actions.iter().any(|a| a.node == 7 && matches!(a.kind, ActionKind::Scale)), "{:?}", before.actions);
let dwg = cadcraft_io::write(&d, "x.dwg").unwrap();
let doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(&dwg)).read().unwrap();
@@ -347,7 +347,9 @@ fn bad_values_are_refused_and_change_nothing() {
let ps = cadcraft_doc::dynblock::custom_properties(&d, h("80")).unwrap().1;
let editable: Vec<(&str, bool)> = ps.iter().map(|p| (p.name.as_str(), p.editable)).collect();
assert_eq!(editable, [("Visibility1", true), ("Width", true), ("Size", true)]);
for (name, value) in [("Visibility1", "Ajar"), ("Size", "Huge"), ("Width", "wide"), ("Width", "-3"), ("Width", "inf"), ("Nope", "x"), ("", "")] {
for (name, value) in
[("Visibility1", "Ajar"), ("Size", "Huge"), ("Width", "wide"), ("Width", "0"), ("Width", "-3"), ("Width", "inf"), ("Nope", "x"), ("", "")]
{
assert!(cadcraft_doc::dynblock::set_property(&mut d, h("80"), name, value).is_err(), "{name}={value}");
}
assert!(cadcraft_doc::dynblock::set_property(&mut d, h("30"), "Visibility1", "Open").is_err(), "not a reference");
@@ -798,55 +800,3 @@ fn a_dynamic_block_with_handles_above_2_pow_48_is_kept() {
let again = read_dxf(write_dxf(&d).as_bytes()).unwrap();
assert_eq!(by_node(dynamic_block(&again, "Door").unwrap()), by_node(before));
}
/// A multiline attribute (LABEL, two lines) in the stretch's selection: when Width changes, the
/// reference's attribute moves with its definition, its multiline text too.
#[test]
fn a_stretch_moves_a_multiline_attributes_text() {
let attdef = "0 ATTDEF\n5 3A\n330 1D\n100 AcDbEntity\n8 0\n100 AcDbText\n10 35\n20 0\n30 0\n40 1\n1 SITE\n7 Standard\n100 AcDbAttributeDefinition\n280 0\n3 Label\n2 LABEL\n70 0\n280 1\n71 4\n72 0\n11 35\n21 0\n31 0\n101 Embedded Object\n10 35\n20 0\n30 0\n40 1\n41 0\n46 0\n71 1\n72 5\n1 SITE\\PNAME\n7 Standard\n73 1\n44 1\n";
let src = fixture().replace("71 1\n330 30\n1010 40", "71 2\n330 30\n330 3A\n1010 40");
// Into Door's block, before its end.
let door = src.find("2 Door\n70 0").unwrap();
let end = door + src[door..].find("0 ENDBLK").unwrap();
let src = format!("{}{attdef}{}", &src[..end], &src[end..]);
let mut d = read_dxf(dxf(&src).as_bytes()).unwrap();
let def = d
.block("Door")
.unwrap()
.entities
.iter()
.find_map(|e| if let cadcraft_doc::EntityKind::AttDef(a) = &e.kind { Some(a.clone()) } else { None })
.expect("the attribute definition");
assert!(def.multiline.is_some(), "a multiline definition");
// A reference at (100, 0) with its attribute where the definition puts it.
let r = door_at_100(&mut d);
d.modify_entity(r, |e| {
if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind {
let mut a = def.clone();
let m = cadcraft_doc::geom::Mat3::translate(cadcraft_doc::geom::Vec2::new(100.0, 0.0));
let mut k = cadcraft_doc::EntityKind::Text(a.text.clone());
k.transform(&m);
if let cadcraft_doc::EntityKind::Text(t) = k {
a.text = t;
}
a.transform_multiline(&m);
i.attribs.push(a);
}
})
.unwrap();
// Width 36 → 30: the attribute moves 6 to the left, its multiline text with it.
cadcraft_doc::dynblock::set_property(&mut d, r, "Width", "30").unwrap();
let Some(cadcraft_doc::EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("no reference") };
let a = &i.attribs[0];
assert_eq!(a.text.insert.x, 129.0);
assert_eq!(a.multiline.as_ref().unwrap().mtext.insert.x, 129.0);
// Saved (in the drawing's version, 2018: R2000 DXF has no multiline attributes) and reopened:
// the moved attribute and its multiline text stay where they went.
let again = cadcraft_io::read(&cadcraft_io::write(&d, "door.dxf").unwrap(), "door.dxf").unwrap();
let Some(cadcraft_doc::EntityKind::Insert(i)) = again.entity(r).map(|e| &e.kind) else { panic!("no reference after reopening") };
let a = &i.attribs[0];
assert_eq!((a.text.insert.x, a.text.insert.y), (129.0, 0.0));
let m = &a.multiline.as_ref().expect("still multiline").mtext;
assert_eq!((m.insert.x, m.insert.y), (129.0, 0.0));
assert_eq!(m.contents, r"SITE\PNAME");
}
-285
View File
@@ -1,285 +0,0 @@
//! Rotation and flip parameters of dynamic blocks: their rotate and flip actions turn and mirror
//! the objects (text stays readable), carry the parameters in their selection, record the
//! change as AutoCAD does, and give the reference a rotation grip and a flip grip.
//!
//! The fixture is synthetic: block Symbol (a circle, a line from the origin to (0, 3) and an
//! attribute TAG at (1, 2) turned 90°) with Angle1 (base at the origin, radius to (2, 0)) and its
//! rotate action, Flip state1 (reflection line from the origin to (-10, 0)) and its flip action,
//! and Position1 at (0, 3) with a move action.
use cadcraft_doc::dynblock::{
ActionKind, GripPart, GripShape, ParameterKind, Value, custom_properties, drag_grip, dynamic_block, grip_stops, grips, reference, set_property,
};
use cadcraft_doc::geom::{Vec2, Vec3};
use cadcraft_doc::{Drawing, EntityKind, Handle, RawTag};
use cadcraft_io::{read_dxf, write_dxf};
fn dxf(src: &str) -> String {
src.lines()
.map(str::trim)
.filter(|l| !l.is_empty())
.map(|l| {
let (code, value) = l.split_once(' ').unwrap_or((l, ""));
format!("{code}\n{value}\n")
})
.collect()
}
/// Symbol and a reference to it at (100, 100) with its attribute.
fn symbol() -> (Drawing, Handle) {
symbol_from(&include_str!("../data/dynblock_symbol.txt").replace("\r\n", "\n"))
}
/// As [`symbol`], from the fixture's text `src` (changed by a test).
fn symbol_from(src: &str) -> (Drawing, Handle) {
let mut d = read_dxf(dxf(src).as_bytes()).unwrap();
let def =
d.block("Symbol").unwrap().entities.iter().find_map(|e| if let EntityKind::AttDef(a) = &e.kind { Some(a.clone()) } else { None }).unwrap();
let mut a = def.clone();
a.text.insert = a.text.insert + Vec3::new(100.0, 100.0, 0.0);
let ins = cadcraft_doc::Insert {
block: "Symbol".into(),
insert: Vec3::new(100.0, 100.0, 0.0),
scale: Vec3::new(1.0, 1.0, 1.0),
rotation: 0.0,
attribs: vec![a],
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
let r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap();
(d, r)
}
fn props(d: &Drawing, r: Handle) -> Vec<(String, String)> {
custom_properties(d, r).unwrap().1.into_iter().map(|p| (p.name, p.value)).collect()
}
fn pairs(v: &[(&str, &str)]) -> Vec<(String, String)> {
v.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect()
}
/// The reference's block: its line's end and attribute definition (insertion, rotation in degrees).
fn shown(d: &Drawing, r: Handle) -> (Vec2, Vec2, f64) {
let Some(EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("no reference") };
let b = d.block(&i.block).unwrap();
let line = b.entities.iter().find_map(|e| if let EntityKind::Line(l) = &e.kind { Some(l.b.xy()) } else { None }).unwrap();
let (at, rot) =
b.entities.iter().find_map(|e| if let EntityKind::AttDef(a) = &e.kind { Some((a.text.insert.xy(), a.text.rotation)) } else { None }).unwrap();
(line, at, rot.to_degrees())
}
fn near(a: Vec2, b: (f64, f64)) -> bool {
(a.x - b.0).abs() < 1e-6 && (a.y - b.1).abs() < 1e-6
}
#[test]
fn rotation_and_flip_are_read() {
let (d, _) = symbol();
let m = dynamic_block(&d, "Symbol").unwrap();
let p = |node: i32| &m.parameters.iter().find(|p| p.node == node).unwrap().kind;
assert!(matches!(p(15), ParameterKind::Rotation { label, values, .. } if label == "Angle1" && values.maximum > 6.0));
assert!(
matches!(p(20), ParameterKind::Flip { label, states, .. } if label == "Flip state1" && states == &["Not flipped".to_string(), "Flipped".to_string()])
);
let a = |node: i32| m.actions.iter().find(|a| a.node == node).unwrap();
assert!(matches!(&a(19).kind, ActionKind::Rotate { base } if base.dependent));
assert_eq!(a(19).connections.last(), Some(&(15, "AngleDelta".to_string())));
assert!(matches!(a(25).kind, ActionKind::Flip));
assert_eq!(a(25).connections.len(), 4);
}
#[test]
fn an_angle_turns_and_a_flip_mirrors_what_their_actions_hold() {
let (mut d, r) = symbol();
assert_eq!(props(&d, r), pairs(&[("Angle1", "0"), ("Flip state1", "Not flipped"), ("Position1 X", "0.0000"), ("Position1 Y", "3.0000")]));
// 30°: the line, the attribute and Position1 turn about the origin; the text turns with them.
set_property(&mut d, r, "angle1", "30").unwrap();
let (c, s) = (30f64.to_radians().cos(), 30f64.to_radians().sin());
let (line, at, rot) = shown(&d, r);
assert!(near(line, (-3.0 * s, 3.0 * c)), "{line:?}");
assert!(near(at, (c - 2.0 * s, s + 2.0 * c)), "{at:?}");
assert!((rot - 120.0).abs() < 1e-9);
assert_eq!(props(&d, r), pairs(&[("Angle1", "30"), ("Flip state1", "Not flipped"), ("Position1 X", "-1.5000"), ("Position1 Y", "2.5981")]));
// The reference's attribute follows its definition.
let Some(EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("no reference") };
assert!(near(i.attribs[0].text.insert.xy(), (100.0 + at.x, 100.0 + at.y)));
// Flipped: mirrored across the reflection line, which turned with them (now at 30°); the
// text keeps reading left to right.
set_property(&mut d, r, "Flip state1", "Flipped").unwrap();
let (s2, c2) = (60f64.to_radians().sin(), 60f64.to_radians().cos());
let mirror = |p: Vec2| (p.x * c2 + p.y * s2, p.x * s2 - p.y * c2);
let (line2, at2, rot) = shown(&d, r);
assert!(near(line2, mirror(line)), "{line2:?}");
assert!(near(at2, mirror(at)), "{at2:?}");
assert!((rot - 120.0).abs() < 1e-9, "readable");
assert_eq!(props(&d, r)[1..], pairs(&[("Flip state1", "Flipped"), ("Position1 X", "1.5000"), ("Position1 Y", "-2.5981")]));
// Both survive a save.
let again = read_dxf(write_dxf(&d).as_bytes()).unwrap();
assert_eq!(props(&again, r), props(&d, r));
// Back to not flipped: back to the turned geometry.
set_property(&mut d, r, "Flip state1", "0").unwrap();
assert!(near(shown(&d, r).1, (at.x, at.y)));
}
#[test]
fn rotation_and_flip_grips() {
let (mut d, r) = symbol();
set_property(&mut d, r, "Angle1", "30").unwrap();
let (c, s) = (30f64.to_radians().cos(), 30f64.to_radians().sin());
let g = grips(&d, r);
let rot = g.iter().find(|g| g.shape == GripShape::Rotation).unwrap();
assert_eq!((rot.node, rot.part), (15, GripPart::End));
assert!(near(rot.at, (100.0 + 2.0 * c, 100.0 + 2.0 * s)), "at the radius' end: {:?}", rot.at);
let flip = g.iter().find(|g| g.shape == GripShape::Flip).unwrap();
assert_eq!((flip.node, flip.part, flip.choices.len()), (20, GripPart::Base, 2));
// The flip grip object at (-2, 0) turned with the reflection line.
assert!(near(flip.at, (100.0 - 2.0 * c, 100.0 - 2.0 * s)), "{:?}", flip.at);
// Dragging the rotation grip straight up from the base: 90°.
drag_grip(&mut d, r, 15, GripPart::End, Vec2::new(100.0, 105.0)).unwrap();
assert_eq!(props(&d, r)[0].1, "90");
// A flip grip is clicked, not dragged; the base of the angle is not a point to aim at.
assert!(drag_grip(&mut d, r, 20, GripPart::Base, Vec2::new(90.0, 90.0)).is_err());
assert!(drag_grip(&mut d, r, 15, GripPart::End, Vec2::new(100.0, 100.0)).is_err());
}
#[test]
fn a_rotation_grip_off_the_radius_stays_where_its_grip_object_is() {
// The grip object a quarter turn round from the radius' end (as AutoCAD saves blocks whose
// grip was moved there): the circle is drawn there and turns with the angle, and dragging
// it turns the block by the cursor's turn, not to the cursor's direction.
let src = include_str!("../data/dynblock_symbol.txt")
.replace("\r\n", "\n")
.replace("100 AcDbBlockGrip\n91 0\n92 0\n1010 2\n1020 0\n", "100 AcDbBlockGrip\n91 0\n92 0\n1010 0\n1020 2\n");
let (mut d, r) = symbol_from(&src);
let at = |d: &Drawing| grips(d, r).into_iter().find(|g| g.shape == GripShape::Rotation).map(|g| g.at).unwrap();
assert!(near(at(&d), (100.0, 102.0)), "{:?}", at(&d));
// Dropped where it is: no turn.
drag_grip(&mut d, r, 15, GripPart::End, Vec2::new(100.0, 102.0)).unwrap();
assert!(props(&d, r).contains(&("Angle1".to_string(), "0".to_string())), "{:?}", props(&d, r));
// A quarter turn further round: Angle1 90, and the grip is there.
drag_grip(&mut d, r, 15, GripPart::End, Vec2::new(98.0, 100.0)).unwrap();
assert!(props(&d, r).contains(&("Angle1".to_string(), "90".to_string())), "{:?}", props(&d, r));
assert!(near(at(&d), (98.0, 100.0)), "{:?}", at(&d));
}
#[test]
fn an_angle_shows_and_is_typed_as_the_drawing_measures_angles() {
// Angles measured clockwise from north (ANGBASE 90°, ANGDIR 1): AutoCAD shows Angle1 0 as
// 90 and 0.5 rad as 61.35, and a typed angle is read the same way.
let (mut d, r) = symbol();
d.header.set_f64("ANGBASE", std::f64::consts::FRAC_PI_2);
d.header.set_i64("ANGDIR", 1);
assert!(props(&d, r).contains(&("Angle1".to_string(), "90".to_string())), "{:?}", props(&d, r));
// 60 shown is 30° counterclockwise: the grip turns from (102, 100) to there.
set_property(&mut d, r, "Angle1", "60").unwrap();
assert!(props(&d, r).contains(&("Angle1".to_string(), "60".to_string())), "{:?}", props(&d, r));
let at = grips(&d, r).into_iter().find(|g| g.shape == GripShape::Rotation).map(|g| g.at).unwrap();
let want = (100.0 + 2.0 * 30f64.to_radians().cos(), 100.0 + 2.0 * 30f64.to_radians().sin());
assert!(near(at, want), "{at:?} vs {want:?}");
}
#[test]
fn an_angle_by_increments_marks_its_stops_round_the_circle() {
// Angle1 by 90° from 0 to a full turn: its grip stops at four points round the base, the
// full turn being no turn; the way it travels there is round the circle.
let src = include_str!("../data/dynblock_symbol.txt")
.replace("\r\n", "\n")
.replace("96 3\n141 0\n142 6.283185307179586\n143 0\n", "96 7\n141 0\n142 6.283185307179586\n143 1.5707963267948966\n");
let (d, r) = symbol_from(&src);
let stops = grip_stops(&d, r, 15, GripPart::End);
let at: Vec<Vec2> = stops.iter().map(|(p, _)| *p).collect();
assert_eq!(at.len(), 4, "{at:?}");
for (p, want) in at.iter().zip([(102.0, 100.0), (100.0, 102.0), (98.0, 100.0), (100.0, 98.0)]) {
assert!(near(*p, want), "{p:?} vs {want:?}");
}
for (p, way) in &stops {
assert!((*p - Vec2::new(100.0, 100.0)).dot(*way).abs() < 1e-9, "across the radius");
}
// The block as it comes (any angle) marks nothing; nor does a flip grip.
let (d, r) = symbol();
assert!(grip_stops(&d, r, 15, GripPart::End).is_empty());
assert!(grip_stops(&d, r, 20, GripPart::Base).is_empty());
}
#[test]
fn an_angle_s_stops_follow_a_grip_off_the_radius() {
// The grip object a quarter turn round and 90° increments: each stop is where the grip is
// at that angle, the first (0) where it is now.
let src = include_str!("../data/dynblock_symbol.txt")
.replace("\r\n", "\n")
.replace("96 3\n141 0\n142 6.283185307179586\n143 0\n", "96 7\n141 0\n142 6.283185307179586\n143 1.5707963267948966\n")
.replace("100 AcDbBlockGrip\n91 0\n92 0\n1010 2\n1020 0\n", "100 AcDbBlockGrip\n91 0\n92 0\n1010 0\n1020 2\n");
let (d, r) = symbol_from(&src);
let at: Vec<Vec2> = grip_stops(&d, r, 15, GripPart::End).into_iter().map(|(p, _)| p).collect();
assert_eq!(at.len(), 4, "{at:?}");
for (p, want) in at.iter().zip([(100.0, 102.0), (98.0, 100.0), (100.0, 98.0), (102.0, 100.0)]) {
assert!(near(*p, want), "{p:?} vs {want:?}");
}
}
#[test]
fn bad_angles_and_states_change_nothing() {
let (mut d, r) = symbol();
let before = d.clone();
for (name, value) in [("Angle1", "steep"), ("Angle1", "inf"), ("Flip state1", "Sideways"), ("Flip state1", "2")] {
assert!(set_property(&mut d, r, name, value).is_err(), "{name}={value}");
}
assert_eq!(d, before);
}
/// The saved value record of parameter `node` on the reference (the XRECORD its
/// `ACAD_ENHANCEDBLOCKDATA` entry names), as its index in the drawing's kept objects.
fn record(d: &Drawing, node: i32) -> usize {
let objects = &d.foreign.objects;
let after = |o: &cadcraft_doc::foreign::ForeignObject, key: &str| {
let i = o.tags.iter().position(|t| t.code == 3 && t.value == key)?;
Handle::parse_hex(&o.tags.get(i + 1)?.value)
};
let cache = objects.iter().find_map(|o| after(o, "ACAD_ENHANCEDBLOCKDATA")).unwrap();
let dict = objects.iter().find(|o| o.handle == cache).unwrap();
let h = after(dict, &node.to_string()).unwrap();
objects.iter().position(|o| o.handle == h).unwrap()
}
#[test]
fn a_value_record_takes_its_shape_from_its_parameter() {
let (mut d, r) = symbol();
set_property(&mut d, r, "Angle1", "30").unwrap();
set_property(&mut d, r, "Flip state1", "Flipped").unwrap();
let mut again = read_dxf(write_dxf(&d).as_bytes()).unwrap();
// A stray group 70 after the rotation's points, and a flip record without its state.
let rot = record(&again, 15);
std::sync::Arc::make_mut(&mut again.foreign).objects[rot].tags.push(RawTag { code: 70, value: "1".into() });
let flip = record(&again, 20);
let tags = &mut std::sync::Arc::make_mut(&mut again.foreign).objects[flip].tags;
let last70 = tags.iter().rposition(|t| t.code == 70).unwrap();
tags.remove(last70);
let values = reference(&again, r).unwrap().values;
assert!(matches!(values.get(&15), Some(Value::Points { .. })), "{:?}", values.get(&15));
assert!(matches!(values.get(&20), Some(Value::Flip { flipped: false, .. })), "{:?}", values.get(&20));
assert_eq!(props(&again, r)[..2], pairs(&[("Angle1", "30"), ("Flip state1", "Not flipped")]));
}
#[test]
fn a_flip_selection_that_repeats_its_objects_mirrors_them_once() {
// The flip action's selection lists the line, the circle and Position1 twice: each is mirrored
// once, as with the selection listing them once (twice would mirror them back).
let src = include_str!("../data/dynblock_symbol.txt").replace("\r\n", "\n");
let once = "71 3\n330 31\n330 32\n330 68\n1010 -6";
assert_eq!(src.matches(once).count(), 1);
let (mut twice, r) = symbol_from(&src.replace(once, "71 6\n330 31\n330 32\n330 68\n330 31\n330 32\n330 68\n1010 -6"));
let (mut plain, _) = symbol();
for d in [&mut twice, &mut plain] {
set_property(d, r, "Flip state1", "Flipped").unwrap();
}
let ((l1, a1, r1), (l2, a2, r2)) = (shown(&twice, r), shown(&plain, r));
assert!(near(l1, (l2.x, l2.y)) && near(a1, (a2.x, a2.y)) && (r1 - r2).abs() < 1e-9, "{l1:?} {l2:?}");
assert_eq!(props(&twice, r), props(&plain, r));
}
-214
View File
@@ -1,214 +0,0 @@
//! Scale and polar stretch actions of dynamic blocks, as AutoCAD applies them: a scale action
//! scales its objects about its base point by how much the distance it follows grew (a 2×2 square
//! scaled by a distance going from 2 to 4 is 4×4); a polar stretch turns its objects about the
//! polar parameter's base by the change of its angle and moves the vertices in its frame (and the
//! objects it doesn't stretch) with the end, while its rotate-only objects just turn. Both carry
//! the parameters in their selection, and the results survive a save.
//!
//! The fixture is synthetic: block Grow (a 2×2 square and a circle at (1, 1), Distance1 from the
//! origin to (2, 0), scaled about the distance's base; Position1 at (2, 2) is in the selection),
//! Pinned (the square, scaled about the fixed point (2, 2)) and Sheet (the square, scaled by the
//! diagonal of X Distance1 and Y Distance1, from the origin to (2, 2), as AutoCAD scales by an XY
//! parameter); Tag (a line from (1, 0) to (4, 0), a circle at its end and one at (2, 2), a polar
//! Distance1/Angle1 from the origin to (4, 0); the polar stretch's frame holds the line's end and
//! Position1 at (4, 1); the circle at (2, 2) only turns).
use cadcraft_doc::dynblock::{ActionKind, custom_properties, dynamic_block, set_property};
use cadcraft_doc::geom::Vec3;
use cadcraft_doc::{Drawing, EntityKind, Handle};
use cadcraft_io::{read_dxf, write_dxf};
fn dxf(src: &str) -> String {
src.lines()
.map(str::trim)
.filter(|l| !l.is_empty())
.map(|l| {
let (code, value) = l.split_once(' ').unwrap_or((l, ""));
format!("{code}\n{value}\n")
})
.collect()
}
/// The fixture with a reference to `block` at (100, 100).
fn reference(block: &str) -> (Drawing, Handle) {
let mut d = read_dxf(dxf(&include_str!("../data/dynblock_scale_polar.txt").replace("\r\n", "\n")).as_bytes()).unwrap();
let ins = cadcraft_doc::Insert {
block: block.into(),
insert: Vec3::new(100.0, 100.0, 0.0),
scale: Vec3::new(1.0, 1.0, 1.0),
rotation: 0.0,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
let r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap();
(d, r)
}
fn props(d: &Drawing, r: Handle) -> Vec<(String, String)> {
custom_properties(d, r).unwrap().1.into_iter().map(|p| (p.name, p.value)).collect()
}
/// Each object of the reference's block, in block coordinates: a polyline's corners (lowest and
/// highest), a circle's centre and radius, a line's ends.
fn shapes(d: &Drawing, r: Handle) -> Vec<[f64; 4]> {
let Some(EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("a reference") };
let round = |v: f64| (v * 1000.0).round() / 1000.0 + 0.0;
d.block(&i.block)
.unwrap()
.entities
.iter()
.map(|e| match &e.kind {
EntityKind::LwPolyline(p) => {
let xs = p.vertices.iter().map(|v| v.p.x);
let ys = p.vertices.iter().map(|v| v.p.y);
[
round(xs.clone().fold(f64::MAX, f64::min)),
round(ys.clone().fold(f64::MAX, f64::min)),
round(xs.fold(f64::MIN, f64::max)),
round(ys.fold(f64::MIN, f64::max)),
]
}
EntityKind::Circle(c) => [round(c.center.x), round(c.center.y), round(c.radius), 0.0],
EntityKind::Line(l) => [round(l.a.x), round(l.a.y), round(l.b.x), round(l.b.y)],
k => panic!("unexpected {k:?}"),
})
.collect()
}
#[test]
fn reads_the_scale_actions_base_and_connections() {
let (d, _) = reference("Grow");
let m = dynamic_block(&d, "Grow").unwrap();
let a = m.actions.iter().find(|a| matches!(a.kind, ActionKind::Scale { .. })).unwrap();
let ActionKind::Scale { base } = a.kind else { unreachable!() };
assert!(base.dependent);
let names: Vec<&str> = a.connections.iter().map(|(_, c)| c.as_str()).collect();
assert_eq!(names, ["UpdatedBaseX", "UpdatedBaseY", "Scale", "XScale", "YScale"]);
let m = dynamic_block(&d, "Pinned").unwrap();
let ActionKind::Scale { base } = m.actions[0].kind else { panic!("a scale action") };
assert!(!base.dependent);
assert_eq!((base.at.x, base.at.y), (2.0, 2.0));
}
#[test]
fn a_distance_scales_its_objects_about_the_base() {
let (mut d, r) = reference("Grow");
set_property(&mut d, r, "Distance1", "4").unwrap();
assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 4.0, 4.0], [2.0, 2.0, 1.0, 0.0]]);
// The point parameter in the selection is scaled with them.
let p = props(&d, r);
assert!(p.contains(&("Position1 X".into(), "4.0000".into())), "{p:?}");
assert!(p.contains(&("Position1 Y".into(), "4.0000".into())), "{p:?}");
// From there, by the ratio of the new distance to the one it has now.
set_property(&mut d, r, "Distance1", "1").unwrap();
assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 1.0, 1.0], [0.5, 0.5, 0.25, 0.0]]);
}
#[test]
fn a_fixed_base_point_stays() {
let (mut d, r) = reference("Pinned");
set_property(&mut d, r, "Distance1", "4").unwrap();
assert_eq!(shapes(&d, r), vec![[-2.0, -2.0, 2.0, 2.0]]);
}
#[test]
fn an_xy_parameter_scales_by_its_diagonal() {
let (mut d, r) = reference("Sheet");
// From (2, 2) to (4, 2): the diagonal grows from √8 to √20.
set_property(&mut d, r, "X Distance1", "4").unwrap();
let s = (20.0f64 / 8.0).sqrt() * 2.0;
let round = |v: f64| (v * 1000.0).round() / 1000.0;
assert_eq!(shapes(&d, r), vec![[0.0, 0.0, round(s), round(s)]]);
// A distance of 0 along one axis still leaves a diagonal: 4 long, twice the square's √8 / 2.
set_property(&mut d, r, "Y Distance1", "0").unwrap();
assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 2.828, 2.828]]);
}
#[test]
fn scaled_objects_and_values_survive_a_save() {
let (mut d, r) = reference("Grow");
set_property(&mut d, r, "Distance1", "3").unwrap();
let mut back = read_dxf(write_dxf(&d).as_bytes()).unwrap();
assert_eq!(props(&back, r), props(&d, r));
assert_eq!(shapes(&back, r), shapes(&d, r));
set_property(&mut back, r, "Distance1", "6").unwrap();
assert_eq!(shapes(&back, r), vec![[0.0, 0.0, 6.0, 6.0], [3.0, 3.0, 1.5, 0.0]]);
}
#[test]
fn hostile_scales_are_refused_and_change_nothing() {
let (mut d, r) = reference("Grow");
for v in ["0", "-3", "NaN", "inf", "1e-300", "1e200"] {
assert!(set_property(&mut d, r, "Distance1", v).is_err(), "{v}");
}
assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 2.0, 2.0], [1.0, 1.0, 0.5, 0.0]]);
// A large factor within the limit is a large block.
set_property(&mut d, r, "Distance1", "2e6").unwrap();
assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 2e6, 2e6], [1e6, 1e6, 5e5, 0.0]]);
// Both XY distances 0 would scale the objects to nothing; from there no ratio is known.
let (mut d, r) = reference("Sheet");
set_property(&mut d, r, "X Distance1", "0").unwrap();
assert!(set_property(&mut d, r, "Y Distance1", "0").is_err());
assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 1.414, 1.414]]);
}
#[test]
fn reads_the_polar_stretch_action() {
let (d, _) = reference("Tag");
let m = dynamic_block(&d, "Tag").unwrap();
let ActionKind::PolarStretch { frame, vertices, rotate_only, multiplier, .. } = &m.actions[0].kind else { panic!("a polar stretch") };
assert_eq!(frame.len(), 2);
assert_eq!(vertices, &vec![(Handle(0xB0), vec![1])]);
assert_eq!(rotate_only, &vec![Handle(0xB2)]);
assert_eq!(*multiplier, 1.0);
assert_eq!(m.actions[0].connections.len(), 6);
}
#[test]
fn a_polar_distance_stretches_the_frame_along_it() {
let (mut d, r) = reference("Tag");
set_property(&mut d, r, "Distance1", "6").unwrap();
// The line's end and the head follow the end; the rotate-only circle stays.
assert_eq!(shapes(&d, r), vec![[1.0, 0.0, 6.0, 0.0], [6.0, 0.0, 0.25, 0.0], [2.0, 2.0, 0.5, 0.0]]);
let p = props(&d, r);
assert!(p.contains(&("Position1 X".into(), "6.0000".into())), "{p:?}");
}
#[test]
fn a_polar_angle_turns_everything_about_the_base() {
let (mut d, r) = reference("Tag");
set_property(&mut d, r, "Angle1", "90").unwrap();
assert_eq!(shapes(&d, r), vec![[0.0, 1.0, 0.0, 4.0], [0.0, 4.0, 0.25, 0.0], [-2.0, 2.0, 0.5, 0.0]]);
let p = props(&d, r);
assert!(p.contains(&("Position1 X".into(), "-1.0000".into())) && p.contains(&("Position1 Y".into(), "4.0000".into())), "{p:?}");
// Then a distance along the new direction, and back to the start.
set_property(&mut d, r, "Distance1", "6").unwrap();
assert_eq!(shapes(&d, r), vec![[0.0, 1.0, 0.0, 6.0], [0.0, 6.0, 0.25, 0.0], [-2.0, 2.0, 0.5, 0.0]]);
set_property(&mut d, r, "Angle1", "0").unwrap();
set_property(&mut d, r, "Distance1", "4").unwrap();
assert_eq!(shapes(&d, r), vec![[1.0, 0.0, 4.0, 0.0], [4.0, 0.0, 0.25, 0.0], [2.0, 2.0, 0.5, 0.0]]);
}
#[test]
fn polar_stretched_objects_survive_a_save() {
let (mut d, r) = reference("Tag");
set_property(&mut d, r, "Angle1", "90").unwrap();
let mut back = read_dxf(write_dxf(&d).as_bytes()).unwrap();
assert_eq!(props(&back, r), props(&d, r));
assert_eq!(shapes(&back, r), shapes(&d, r));
set_property(&mut back, r, "Distance1", "2").unwrap();
assert_eq!(shapes(&back, r), vec![[0.0, 1.0, 0.0, 2.0], [0.0, 2.0, 0.25, 0.0], [-2.0, 2.0, 0.5, 0.0]]);
}
#[test]
fn hostile_polar_values_are_refused() {
let (mut d, r) = reference("Tag");
for (n, v) in [("Distance1", "0"), ("Distance1", "NaN"), ("Distance1", "-inf"), ("Angle1", "nan"), ("Angle1", "1e400")] {
assert!(set_property(&mut d, r, n, v).is_err(), "{n} {v}");
}
assert_eq!(shapes(&d, r), vec![[1.0, 0.0, 4.0, 0.0], [4.0, 0.0, 0.25, 0.0], [2.0, 2.0, 0.5, 0.0]]);
}
-4
View File
@@ -25,11 +25,7 @@ mod dwg_layout_owner;
mod dwg_roundtrip_losses;
mod dwt_template;
mod dxf_versions;
mod dynblock_array;
mod dynblock_params;
mod dynblock_read;
mod dynblock_rotate_flip;
mod dynblock_scale_polar;
mod entity_props_roundtrip;
mod exhausted_handseed;
mod followups_626;
-44
View File
@@ -19,19 +19,6 @@ pub(super) fn dynamic_input(app: &mut CadApp, p: &egui::Painter, hover: Pos2, fi
// DYNPROMPT = 0: no prompt beside the cursor (the value boxes stay).
let show_prompt = app.session.settings.dynprompt;
let options = show_prompt && !prompt.keywords.is_empty();
// An angle about the base (a rotation grip): one angle box, as AutoCAD shows it.
if !fields
&& prompt.angle
&& crate::cmdline::dyn_frame(app).is_some()
&& let Some(c) = app.canvas.cursor
{
let message = if show_prompt { crate::i18n::t(&prompt.message) } else { "" };
let typed = !app.cmd.buffer.is_empty();
let value = if typed { app.cmd.buffer.clone() } else { app.session.live_value(c).unwrap_or_default() };
let r = angle_box(p, at, message, &value, typed, options);
options_menu(app, p, r, hover);
return;
}
if !fields
&& let Some(f) = crate::cmdline::dyn_frame(app)
&& let Some(e) = crate::dyninput::parse(&app.cmd.buffer, &f)
@@ -132,37 +119,6 @@ fn tooltip_frame(p: &egui::Painter, at: Pos2, size: egui::Vec2) -> Rect {
r
}
/// The Dynamic Input tooltip for an angle: the prompt and one box, holding what was typed (full
/// text colour, with the caret) or the live value (dimmed).
fn angle_box(p: &egui::Painter, at: Pos2, message: &str, value: &str, typed: bool, options: bool) -> Rect {
let t = Tokens::get();
let font = crate::theme::small();
let msg = p.layout_no_wrap(message.to_owned(), font.clone(), t.text_dim);
let val = p.layout_no_wrap(value.to_owned(), font, if typed { t.text } else { t.text_faint });
let (pad, gap) = (6.0, 6.0);
let box_h = msg.size().y + 6.0;
let bw = (val.size().x + 10.0).max(48.0);
let hint = if options { OPTIONS_HINT_W } else { 0.0 };
let r = tooltip_frame(p, at, vec2(pad + msg.size().x + gap + bw + pad + hint, box_h + 2.0 * pad - 2.0));
if options {
options_hint(p, r);
}
let cy = r.center().y;
let x = r.left() + pad;
let msg_w = msg.size().x;
p.galley(pos2(x, cy - msg.size().y / 2.0), msg, t.text_dim);
let b = Rect::from_min_size(pos2(x + msg_w + gap, cy - box_h / 2.0), vec2(bw, box_h));
p.rect_filled(b, 2.0, t.chrome_dark);
p.rect_stroke(b, 2.0, Stroke::new(1.5, t.accent), egui::StrokeKind::Inside);
let vw = val.size().x;
p.galley(pos2(b.left() + 5.0, cy - val.size().y / 2.0), val, t.text);
if typed {
let cx = b.left() + 6.0 + vw;
p.line_segment([pos2(cx, b.top() + 3.0), pos2(cx, b.bottom() - 3.0)], Stroke::new(1.0, t.text));
}
r
}
/// The Dynamic Input value boxes: X and Y, or distance and angle. Typed values show in full
/// text colour, a locked value (a separator typed after it) gets a lock, the active box gets the
/// accent outline, and open boxes show the cursor's live value, dimmed. Values measured from the
+3 -63
View File
@@ -1,9 +1,7 @@
//! Dynamic block grips on the canvas, as AutoCAD shows them on a selected dynamic block
//! reference: an arrow at a distance's end (drag it to change the distance), a square at a
//! position (drag it to move it), a circle at an angle's end (drag it to turn), an arrow across a
//! reflection line (click it to flip), a down-pointing triangle for a list (click it for the
//! visibility states or lookup values) and a pentagon at an alignment's base point (drag it next to
//! an object to align the reference with it). Dragging runs the engine's dynamic grip edit
//! position (drag it to move it) and a down-pointing triangle for a list (click it for the
//! visibility states or lookup values). Dragging runs the engine's dynamic grip edit
//! ([`cadcraft_engine::Session::start_dyn_grip`]); a list choice runs `blocks.reference.set`.
use std::sync::Arc;
@@ -66,37 +64,6 @@ fn outline(xf: &Xf, g: &DynGrip, gs: f32) -> Vec<Pos2> {
let w = gs * 1.3;
vec![c + vec2(-w, -w * 0.6), c + vec2(w, -w * 0.6), c + vec2(0.0, w * 0.9)]
}
GripShape::Rotation => (0..16)
.map(|i| {
let a = std::f32::consts::TAU * i as f32 / 16.0;
c + vec2(a.cos(), a.sin()) * (gs * 1.1)
})
.collect(),
// An arrow pointing across the reflection line, the way it flips.
GripShape::Flip => {
let ahead = xf.to_screen(g.at + g.dir) - c;
let u = if ahead.length() > 1e-6 { ahead / ahead.length() } else { vec2(0.0, -1.0) };
let n = vec2(-u.y, u.x);
// A block arrow, as AutoCAD draws it: a short shaft and a head about as wide as a
// square grip. Tail, shaft's end and head's back on one side, the tip, then back.
let (tail, neck, tip, shaft, head) = (gs * 1.4, gs * 0.2, gs * 1.4, gs * 0.5, gs * 1.4);
vec![
c - u * tail + n * shaft,
c - u * neck + n * shaft,
c - u * neck + n * head,
c + u * tip,
c - u * neck - n * head,
c - u * neck - n * shaft,
c - u * tail - n * shaft,
]
}
// A square with a point on the side the grip points to (across the alignment direction).
GripShape::Alignment => {
let ahead = xf.to_screen(g.at + g.dir) - c;
let u = if ahead.length() > 1e-6 { ahead / ahead.length() } else { vec2(0.0, -1.0) };
let n = vec2(-u.y, u.x);
vec![c - u * gs - n * gs, c + u * (gs * 0.2) - n * gs, c + u * (gs * 1.4), c + u * (gs * 0.2) + n * gs, c - u * gs + n * gs]
}
}
}
@@ -126,18 +93,7 @@ pub(crate) fn draw(app: &mut CadApp, painter: &Painter, xf: &Xf, rect: Rect, hov
} else {
t.grip_dyn
};
let stroke = Stroke::new(1.0, Color32::from_rgb(0x10, 0x30, 0x80));
match (g.shape, pts.as_slice()) {
// The flip arrow isn't convex: its shaft and head are filled apart, then outlined.
(GripShape::Flip, [t0, n0, h0, tip, h1, n1, t1]) => {
painter.add(Shape::convex_polygon(vec![*t0, *n0, *n1, *t1], fill, Stroke::NONE));
painter.add(Shape::convex_polygon(vec![*h0, *tip, *h1], fill, Stroke::NONE));
painter.add(Shape::closed_line(pts.clone(), stroke));
}
_ => {
painter.add(Shape::convex_polygon(pts, fill, stroke));
}
}
painter.add(Shape::convex_polygon(pts, fill, Stroke::new(1.0, Color32::from_rgb(0x10, 0x30, 0x80))));
}
}
@@ -150,22 +106,6 @@ pub(crate) fn at(app: &mut CadApp, xf: &Xf, hover: Option<Pos2>) -> Option<(Hand
/// A click on dynamic grip `g` of reference `h`: drag it, or open its list.
pub(crate) fn click(app: &mut CadApp, (h, g): (Handle, DynGrip)) {
// A flip grip flips at once: the state that isn't the current one.
if g.shape == GripShape::Flip {
let current = app
.session
.state()
.ok()
.and_then(|st| cadcraft_engine::doc::dynblock::custom_properties(&st.doc, h))
.and_then(|(_, ps)| ps.into_iter().find(|p| p.name.eq_ignore_ascii_case(&g.property)))
.map(|p| p.value)
.unwrap_or_default();
let Some(next) = g.choices.iter().find(|c| !c.eq_ignore_ascii_case(&current)).cloned() else { return };
if let Err(e) = app.run("blocks.reference.set", json!({ "handle": h.hex(), "name": g.property, "value": next })) {
app.session.echo(e);
}
return;
}
if g.shape == GripShape::List {
app.canvas.dyn_menu = Some((h, g));
app.canvas.dyn_menu_fresh = true;
+8 -8
View File
@@ -406,7 +406,7 @@
Grip Option خيار المقبض
Grip Rotate تدوير بالمقبض
Grip Scale تحجيم بالمقبض
Grip Stretch تمديد بالمقبض
Grip Stretch تمطيط بالمقبض
Grip size حجم المقبض
Group تجميع
Group Edit تحرير المجموعة
@@ -703,7 +703,7 @@
Plotter Manager مدير الطابعات
Plotter Manager... مدير الطابعات...
Plus/minus زائد/ناقص
Point تأشير
Point نقطة
Point Filters مرشحات النقطة
Point Style... نمط النقطة...
Polar (distance < angle) قطبي (المسافة < الزاوية)
@@ -872,15 +872,15 @@
Select object حدد كائناً
Select object to dimension حدد كائناً لتأشيره
Select object to divide حدد كائناً لتقسيمه
Select object to extend or shift-select to trim حدد كائناً لتمديده أو حدد مع Shift للقص
Select object to extend or shift-select to trim حدد كائناً لتمديده أو حدد مع Shift للتشذيب
Select object to measure حدد كائناً لقياسه
Select object to offset حدد كائناً لإزاحته
Select object to trim or shift-select to extend حدد كائناً لقصه أو حدد مع Shift للتمديد
Select object to trim or shift-select to extend حدد كائناً لتشذيبه أو حدد مع Shift للتمديد
Select objects حدد كائنات
Select objects (crossing window first corner) حدد كائنات (الزاوية الأولى لنافذة التقاطع)
Select objects first, then choose a command حدد الكائنات أولاً ثم اختر أمراً
Select objects to array. حدد كائنات لتكوين مصفوفة.
Select objects to stretch by crossing-window or crossing-polygon... حدد كائنات لتمديدها بنافذة التقاطع أو مضلع التقاطع...
Select objects to stretch by crossing-window or crossing-polygon... حدد كائنات لتمطيطها بنافذة التقاطع أو مضلع التقاطع...
Select objects: حدد كائنات:
Select one polyline (Multiple is available through the JSON form). حدد متعدد خطوط واحداً (يتوفر الوضع المتعدد عبر نموذج JSON).
Select path curve حدد منحنى المسار
@@ -1084,8 +1084,8 @@
Start, End, Radius بداية، نهاية، نصف قطر
Status الحالة
Status Bar شريط الحالة
Stretch تمديد
Stretch Vertex تمديد رأس
Stretch تمطيط
Stretch Vertex تمطيط رأس
Style: Standard النمط: Standard
Subtract طرح
Sweep كنس
@@ -1134,7 +1134,7 @@
Track orthogonally only تعقب متعامد فقط
Track using all polar angle settings تعقب باستخدام كل إعدادات الزوايا القطبية
Transparency شفافية
Trim حدود التشذيب
Trim تشذيب
True Color لون حقيقي
Turn All Layers On تشغيل كل الطبقات
Turn Off Layer إيقاف طبقة
1 # CADCraft Arabic interface catalog — original translations.
406
407
408
409
410
411
412
703
704
705
706
707
708
709
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
1084
1085
1086
1087
1088
1089
1090
1091
1134
1135
1136
1137
1138
1139
1140
+101 -101
View File
@@ -1,4 +1,4 @@
# CADCraft French interface catalog — original translations by @pechnikov2026-star.
# CADCraft French interface catalog — original translations by @pechnikov2026-star; terminology review by @YannFR81.
# License: MIT OR Apache-2.0 (the repository LICENSE-MIT and LICENSE-APACHE).
# Written from CADCraft's English strings; no proprietary translations were copied.
# UTF-8: context<TAB>English source<TAB>French translation.
@@ -160,7 +160,7 @@
Delete Supprimer
Delete Column Supprimer la colonne
Delete Constraints Supprimer les contraintes
Delete Dimension Style Supprimer le style de cotation
Delete Dimension Style Supprimer le style de cote
Delete Duplicate Objects Supprimer les objets en double
Delete Layer Supprimer le calque
Delete Layer State Supprimer l'état des calques
@@ -172,17 +172,17 @@
Description Description
Deselect All Désélectionner tout
Diameter Diamètre
Dim style Style de cotation
Dim style Style de cote
Dimension Cotation
Dimension Space Espace entre cotations
Dimension Style Override Substitution de style de cotation
Dimension Style... Style de cotation...
Dimension Text Edit Modifier le texte de cotation
Dimension style Style de cotation
Dimension Space Espacer les cotes
Dimension Style Override Remplacement de style de cote
Dimension Style... Style de cote...
Dimension Text Edit Modifier le texte de cote
Dimension style Style de cote
Dimensional Constraint Contrainte dimensionnelle
Dimensional Constraint Parameters Paramètres de contraintes dimensionnelles
Dimensional Constraints Contraintes dimensionnelles
Disassociate Dimensions Dissocier les cotations
Disassociate Dimensions Dissocier les cotes
Display name Nom d'affichage
Distance Distance
Divide Diviser
@@ -200,7 +200,7 @@
Drawing Limits Limites du dessin
Drawing Utilities Utilitaires de dessin
Drawings (DWG, DXF) Dessins (DWG, DXF)
Dynamic Dimensions Cotations dynamiques
Dynamic Dimensions Cotes dynamiques
Dynamic Input Saisie dynamique
Dynamic Input (F12) Saisie dynamique (F12)
E Est
@@ -233,9 +233,9 @@
Enter degree of spline Entrez le degré de la spline
Enter delta angle Entrez l'écart d'angle
Enter delta length Entrez l'écart de longueur
Enter dimension text Entrez le texte de cotation
Enter dimension text (<> = measurement) Entrez le texte de cotation (<> = mesure)
Enter dimension value or [name=expression] Entrez la valeur de cotation ou [name=expression]
Enter dimension text Entrez le texte de cote
Enter dimension text (<> = measurement) Entrez le texte de cote (<> = mesure)
Enter dimension value or [name=expression] Entrez la valeur de cote ou [name=expression]
Enter dimension variable name to override Entrez le nom de la variable de cotation à substituer
Enter justification type Entrez le type de justification
Enter leader text Entrez le texte du repère
@@ -254,10 +254,10 @@
Enter rectangle length Entrez la longueur du rectangle
Enter rectangle width Entrez la largeur du rectangle
Enter scale factor Entrez le facteur d'échelle
Enter text Entrer le texte
Enter text (use \P for new paragraphs) Entrer le texte (utilisez \P pour les nouveaux paragraphes)
Enter the number of segments Entrer le nombre de segments
Enter twist direction of helix Entrer le sens de vrillage de l'hélice
Enter text Entrez le texte
Enter text (use \P for new paragraphs) Entrez le texte (utilisez \P pour les nouveaux paragraphes)
Enter the number of segments Entrez le nombre de segments
Enter twist direction of helix Entrez le sens de vrillage de l'hélice
Entire drawing Tout le dessin
Equal Égalité
Erase Effacer
@@ -482,8 +482,8 @@
Object Snap Accrochage aux objets
Object Snap (F3) Accrochage aux objets (F3)
Object Snap On (F3) Activer l'accrochage aux objets (F3)
Object Snap Tracking Suivi de l'accrochage aux objets
Object Snap Tracking (F11) Suivi de l'accrochage aux objets (F11)
Object Snap Tracking Repérage d'accrochage aux objets
Object Snap Tracking (F11) Repérage d'accrochage aux objets (F11)
Object type: Type d'objet :
Off Désactivé
Offset Décalage
@@ -539,7 +539,7 @@
New STB Nouvelle STB
New style Nouveau style
Reset Panel Layout Réinitialiser la disposition des panneaux
Use for this layout Utiliser pour cet espace
Use for this layout Utiliser pour cette présentation
Display plot styles Afficher les styles de tracé
No plot style tables. Aucune table de styles de tracé.
A built-in table: editing it keeps an edited copy in the drawing. Table intégrée : sa modification conserve une copie modifiée dans le dessin.
@@ -560,9 +560,9 @@
Point Filters Filtres de points
Point Style... Style de point...
Polar Array Réseau polaire
Polar Tracking Recherche polaire
Polar Tracking (F10) Recherche polaire (F10)
Polar Tracking On (F10) Activer la recherche polaire (F10)
Polar Tracking Repérage polaire
Polar Tracking (F10) Repérage polaire (F10)
Polar Tracking On (F10) Activer le repérage polaire (F10)
Polar: {distance} < {angle}° Polaire : {distance} < {angle}°
Polygon Polygone
Polygonal Polygonal
@@ -645,77 +645,77 @@
Search for parameter Rechercher un paramètre
Second and next points: Deuxième point et points suivants :
Select Sélectionner
Select 2D polyline Sélectionner une polyligne 2D
Select 2D polyline Sélectionnez une polyligne 2D
Select All Sélectionner tout
Select Objects Sélectionner les objets
Select a 2D polyline. Sélectionner une polyligne 2D.
Select a block reference. Sélectionner une référence de bloc.
Select a circle or arc. Sélectionner un cercle ou un arc.
Select a closed polyline Sélectionner une polyligne fermée
Select a closed polyline, circle, ellipse or closed spline. Sélectionner une polyligne fermée, un cercle, une ellipse ou une spline fermée.
Select a closed polyline. Sélectionner une polyligne fermée.
Select a curve as the path. Sélectionner une courbe comme trajectoire.
Select a dimension constraint type Sélectionner un type de contrainte dimensionnelle
Select a line object Sélectionner une ligne
Select a line object. Sélectionner une ligne.
Select a line or an arc. Sélectionner une ligne ou un arc.
Select a line or polyline segment Sélectionner une ligne ou un segment de polyligne
Select a line, arc or open polyline. Sélectionner une ligne, un arc ou une polyligne ouverte.
Select a line, arc, circle, polyline, ellipse or spline as the path. Sélectionner une ligne, un arc, un cercle, une polyligne, une ellipse ou une spline comme trajectoire.
Select a line, circle, arc or polyline segment. Sélectionner une ligne, un cercle, un arc ou un segment de polyligne.
Select a line. Sélectionner une ligne.
Select a 2D polyline. Sélectionnez une polyligne 2D.
Select a block reference. Sélectionnez une référence de bloc.
Select a circle or arc. Sélectionnez un cercle ou un arc.
Select a closed polyline Sélectionnez une polyligne fermée
Select a closed polyline, circle, ellipse or closed spline. Sélectionnez une polyligne fermée, un cercle, une ellipse ou une spline fermée.
Select a closed polyline. Sélectionnez une polyligne fermée.
Select a curve as the path. Sélectionnez une courbe comme trajectoire.
Select a dimension constraint type Sélectionnez un type de contrainte dimensionnelle
Select a line object Sélectionnez une ligne
Select a line object. Sélectionnez une ligne.
Select a line or an arc. Sélectionnez une ligne ou un arc.
Select a line or polyline segment Sélectionnez une ligne ou un segment de polyligne
Select a line, arc or open polyline. Sélectionnez une ligne, un arc ou une polyligne ouverte.
Select a line, arc, circle, polyline, ellipse or spline as the path. Sélectionnez une ligne, un arc, un cercle, une polyligne, une ellipse ou une spline comme trajectoire.
Select a line, circle, arc or polyline segment. Sélectionnez une ligne, un cercle, un arc ou un segment de polyligne.
Select a line. Sélectionnez une ligne.
Add to Working Set Ajouter au jeu de travail
Edit Reference In-Place Modifier la référence sur place
Save Reference Edits Enregistrer les modifications de la référence
Working Set Jeu de travail
Xref and Block In-place Editing Édition sur place des xrefs et des blocs
Select a polyline. Sélectionner une polyligne.
Select a text, mtext, attribute definition or dimension. Sélectionner un texte, un texte multiligne, une définition d'attribut ou une cote.
Select an annotation object Sélectionner un objet d'annotation
Select an arc or circle Sélectionner un arc ou un cercle
Select an arc. Sélectionner un arc.
Select an object Sélectionner un objet
Select an object to change Sélectionner un objet à modifier
Select an object to measure Sélectionner un objet à mesurer
Select an object. Sélectionner un objet.
Select an open curve. Sélectionner une courbe ouverte.
Select an open line, arc, polyline, ellipse arc or spline. Sélectionner une ligne, un arc, une polyligne, un arc elliptique ou une spline ouverts.
Select arc or circle Sélectionner un arc ou un cercle
Select arc or polyline arc segment Sélectionner un arc ou un segment d'arc de polyligne
Select arc style Sélectionner un style d'arc
Select arc, circle, line Sélectionner un arc, un cercle, une ligne
Select at least two objects to join. Sélectionner au moins deux objets à joindre.
Select circle or arc to add center mark Sélectionner un cercle ou un arc pour ajouter une marque de centre
Select closed objects (regions, closed polylines, circles). Sélectionner des objets fermés (régions, polylignes fermées, cercles).
Select first line Sélectionner la première ligne
Select first line or arc Sélectionner la première ligne ou le premier arc
Select first object Sélectionner le premier objet
Select first point Sélectionner le premier point
Select nested objects to copy Sélectionner des objets imbriqués à copier
Select object Sélectionner un objet
Select object to dimension Sélectionner un objet à coter
Select object to divide Sélectionner un objet à diviser
Select object to extend or shift-select to trim Sélectionner un objet à prolonger ou sélectionner avec Maj pour rogner
Select object to measure Sélectionner un objet à mesurer
Select object to offset Sélectionner un objet à décaler
Select object to trim or shift-select to extend Sélectionner un objet à rogner ou sélectionner avec Maj pour prolonger
Select objects Sélectionner les objets
Select objects (crossing window first corner) Sélectionner les objets (premier coin de la fenêtre de capture)
Select objects to array. Sélectionner les objets à répartir en réseau.
Select objects to stretch by crossing-window or crossing-polygon... Sélectionner les objets à étirer par fenêtre de capture ou polygone de capture...
Select objects: Sélectionner les objets :
Select one polyline (Multiple is available through the JSON form). Sélectionner une polyligne (l'option Multiple est disponible via le formulaire JSON).
Select path curve Sélectionner la courbe de trajectoire
Select point or object Sélectionner un point ou un objet
Select polyline Sélectionner une polyligne
Select second line Sélectionner la deuxième ligne
Select second line or shift-select to apply corner Sélectionner la deuxième ligne ou sélectionner avec Maj pour former le coin
Select second object Sélectionner le deuxième objet
Select second object or shift-select to apply corner Sélectionner le deuxième objet ou sélectionner avec Maj pour former le coin
Select second point Sélectionner le deuxième point
Select spline Sélectionner une spline
Select symmetry line Sélectionner l'axe de symétrie
Select two points Sélectionner deux points
Select a polyline. Sélectionnez une polyligne.
Select a text, mtext, attribute definition or dimension. Sélectionnez un texte, un texte multiligne, une définition d'attribut ou une cote.
Select an annotation object Sélectionnez un objet d'annotation
Select an arc or circle Sélectionnez un arc ou un cercle
Select an arc. Sélectionnez un arc.
Select an object Sélectionnez un objet
Select an object to change Sélectionnez un objet à modifier
Select an object to measure Sélectionnez un objet à mesurer
Select an object. Sélectionnez un objet.
Select an open curve. Sélectionnez une courbe ouverte.
Select an open line, arc, polyline, ellipse arc or spline. Sélectionnez une ligne, un arc, une polyligne, un arc elliptique ou une spline ouverts.
Select arc or circle Sélectionnez un arc ou un cercle
Select arc or polyline arc segment Sélectionnez un arc ou un segment d'arc de polyligne
Select arc style Sélectionnez un style d'arc
Select arc, circle, line Sélectionnez un arc, un cercle, une ligne
Select at least two objects to join. Sélectionnez au moins deux objets à joindre.
Select circle or arc to add center mark Sélectionnez un cercle ou un arc pour ajouter une marque de centre
Select closed objects (regions, closed polylines, circles). Sélectionnez des objets fermés (régions, polylignes fermées, cercles).
Select first line Sélectionnez la première ligne
Select first line or arc Sélectionnez la première ligne ou le premier arc
Select first object Sélectionnez le premier objet
Select first point Sélectionnez le premier point
Select nested objects to copy Sélectionnez des objets imbriqués à copier
Select object Sélectionnez un objet
Select object to dimension Sélectionnez un objet à coter
Select object to divide Sélectionnez un objet à diviser
Select object to extend or shift-select to trim Sélectionnez un objet à prolonger ou sélectionnez avec Maj pour rogner
Select object to measure Sélectionnez un objet à mesurer
Select object to offset Sélectionnez un objet à décaler
Select object to trim or shift-select to extend Sélectionnez un objet à rogner ou sélectionnez avec Maj pour prolonger
Select objects Sélectionnez les objets
Select objects (crossing window first corner) Sélectionnez les objets (premier coin de la fenêtre de capture)
Select objects to array. Sélectionnez les objets à répartir en réseau.
Select objects to stretch by crossing-window or crossing-polygon... Sélectionnez les objets à étirer par fenêtre de capture ou polygone de capture...
Select objects: Sélectionnez les objets :
Select one polyline (Multiple is available through the JSON form). Sélectionnez une polyligne (l'option Multiple est disponible via le formulaire JSON).
Select path curve Sélectionnez la courbe de trajectoire
Select point or object Sélectionnez un point ou un objet
Select polyline Sélectionnez une polyligne
Select second line Sélectionnez la deuxième ligne
Select second line or shift-select to apply corner Sélectionnez la deuxième ligne ou sélectionnez avec Maj pour former le coin
Select second object Sélectionnez le deuxième objet
Select second object or shift-select to apply corner Sélectionnez le deuxième objet ou sélectionnez avec Maj pour former le coin
Select second point Sélectionnez le deuxième point
Select spline Sélectionnez une spline
Select symmetry line Sélectionnez l'axe de symétrie
Select two points Sélectionnez deux points
Selection Cycling Cycle de sélection
Send to Back Envoyer à l'arrière-plan
Set Current Définir comme courant
@@ -747,18 +747,18 @@
Snap and Grid Accrochage et grille
Solid Solide
Sort Trier
Specify a point Spécifier un point
Specify a scale for the hatch pattern Spécifier une échelle pour le motif de hachures
Specify a second extension line origin Spécifier l'origine de la deuxième ligne d'attache
Specify an angle for the hatch pattern Spécifier un angle pour le motif de hachures
Specify angle end point Spécifier le point final de l'angle
Specify angle of dimension line Spécifier l'angle de la ligne de cote
Specify angle of dimension text Spécifier l'angle du texte de cote
Specify angle start point Spécifier le point de départ de l'angle
Specify angle vertex Spécifier le sommet de l'angle
Specify angle vertex point Spécifier le point du sommet de l'angle
Specify arc length dimension location Spécifier l'emplacement de la cote de longueur d'arc
Specify axis endpoint of ellipse Spécifier l'extrémité de l'axe de l'ellipse
Specify a point Spécifiez un point
Specify a scale for the hatch pattern Spécifiez une échelle pour le motif de hachures
Specify a second extension line origin Spécifiez l'origine de la deuxième ligne d'attache
Specify an angle for the hatch pattern Spécifiez un angle pour le motif de hachures
Specify angle end point Spécifiez le point final de l'angle
Specify angle of dimension line Spécifiez l'angle de la ligne de cote
Specify angle of dimension text Spécifiez l'angle du texte de cote
Specify angle start point Spécifiez le point de départ de l'angle
Specify angle vertex Spécifiez le sommet de l'angle
Specify angle vertex point Spécifiez le point du sommet de l'angle
Specify arc length dimension location Spécifiez l'emplacement de la cote de longueur d'arc
Specify axis endpoint of ellipse Spécifiez l'extrémité de l'axe de l'ellipse
Specify base diameter Spécifiez le diamètre de la base
Specify base point Spécifiez le point de base
Specify base point or displacement (drag with the middle mouse button for realtime pan) Spécifiez le point de base ou le déplacement (faites glisser avec le bouton central de la souris pour un panoramique en temps réel)
@@ -768,7 +768,7 @@
Specify center of polygon Spécifiez le centre du polygone
Specify center point for circle Spécifiez le point central du cercle
Specify center point of arc Spécifiez le point central de l'arc
Specify center point of array Spécifiez le point central de la matrice
Specify center point of array Spécifiez le point central du réseau
Specify center point of base Spécifiez le point central de la base
Specify corner of viewport Spécifiez le coin de la fenêtre
Specify corner of window, enter a scale factor (nX or nXP) Spécifiez le coin de la fenêtre, entrez un facteur d'échelle (nX ou nXP)
@@ -894,7 +894,7 @@
Sweep Balayage
Switch Drawing Changer de dessin
Switch Layout Changer de présentation
Switch between model space in a viewport and paper space Basculer entre l'espace modèle dans une fenêtre et l'espace papier
Switch between model space in a viewport and paper space Basculer entre l'espace objet dans une fenêtre et l'espace papier
Symmetric Symétrie
Synchronize Attributes Synchroniser les attributs
Toggle PICKADD (off: each pick replaces the selection) Basculer PICKADD (désactivé : chaque sélection remplace la sélection existante)
1 # CADCraft French interface catalog — original translations by @pechnikov2026-star. # CADCraft French interface catalog — original translations by @pechnikov2026-star; terminology review by @YannFR81.
2 # License: MIT OR Apache-2.0 (the repository LICENSE-MIT and LICENSE-APACHE).
3 # Written from CADCraft's English strings; no proprietary translations were copied.
4 # UTF-8: context<TAB>English source<TAB>French translation.
160
161
162
163
164
165
166
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
200
201
202
203
204
205
206
233
234
235
236
237
238
239
240
241
254
255
256
257
258
259
260
261
262
263
482
483
484
485
486
487
488
489
539
540
541
542
543
544
545
560
561
562
563
564
565
566
567
568
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
768
769
770
771
772
773
774
894
895
896
897
898
899
900
+59 -4
View File
@@ -340,7 +340,7 @@
Exclude from new selection set ახალი მონიშნულიდან გამორიცხვა
Explode დაშლა
Explode Attributes to Text ატრიბუტების ტექსტად დაშლა
Export ექსპორტი
Export ექსპორტირება
Export Table ცხრილის ექსპორტი
Export to PDF... PDF-ად ექსპორტი...
Express Tools Express Tools
@@ -707,8 +707,8 @@
Previous Change წინა ცვლილება
Previous Layer წინა შრე
Primitives პრიმიტივები
Print დაბეჭდვა
Print... დაბეჭდვა...
Print ბეჭდვა
Print... ბეჭდვა...
Properties თვისებები
Properties Inspector თვისებების ინსპექტორი
Properties: თვისებები:
@@ -1242,7 +1242,7 @@
Animation effects ანიმაციის ეფექტები
Interface scale ინტერფეისის მასშტაბი
Import... იმპორტი...
Export... ექსპორტი...
Export... ექსპორტირება...
Batch Publish... პაკეტური გამოქვეყნება...
Scale List... მასშტაბების სია...
Annotative Object Scale ანოტაციური ობიექტის მასშტაბი
@@ -1472,6 +1472,26 @@ menu View ხედი
Text to find მოსაძებნი ტექსტი
Whole words მთლიანი სიტყვები
Nothing found ვერაფერი მოიძებნა
Multiple Insert მრავალჯერადი ჩასმა
Ctrl+Enter to apply გამოსაყენებლად: Ctrl+Enter
Edit Text ტექსტის რედაქტირება
The drawing changed. Close the window and open it again. ნახაზი შეიცვალა. დახურეთ ფანჯარა და ხელახლა გახსენით.
DView დინამიკური ხედი
Raster Image Reference... რასტრული გამოსახულების მიმართვა...
Raster Images რასტრული გამოსახულებები
Clip Xref გარე მიმართვის მოჭრა
Xref გარე მიმართვა
Xref Clip Frame გარე მიმართვის მოჭრის ჩარჩო
Backup copies are off, so the current file will be replaced. სარეზერვო ასლები გამორთულია, ამიტომ მიმდინარე ფაილი ჩანაცვლდება.
DXF 2010 and earlier keep them. Use Save As to keep them in the drawing. DXF 2010 და უფრო ძველი ვერსიები მათ ინახავს. ნახაზში მათ შესანარჩუნებლად გამოიყენეთ „შენახვა როგორც“.
DXF keeps them. Use Save As to keep them in the drawing. DXF მათ ინახავს. ნახაზში მათ შესანარჩუნებლად გამოიყენეთ „შენახვა როგორც“.
Save Anyway მაინც შენახვა
Save cancelled: {path} was not changed. შენახვა გაუქმდა: {path} არ შეცვლილა.
Saving {name} will remove content ფაილში {name} შენახვისას შიგთავსის ნაწილი წაიშლება
The current file doesn't look whole, so {name} stays as it is and the current file will be replaced. მიმდინარე ფაილი არასრული ჩანს, ამიტომ {name} უცვლელი რჩება, მიმდინარე ფაილი კი ჩანაცვლდება.
The current file is kept as {name} until the next save. მიმდინარე ფაილი შემდეგ შენახვამდე შენარჩუნდება სახელით {name}.
This format can't keep these objects yet: {objects}. ეს ფორმატი ამ ობიექტებს ჯერ ვერ ინახავს: {objects}.
{count} more types კიდევ {count} ტიპი
Add a drawing file as a block library ნახაზის ფაილის დამატება ბლოკების ბიბლიოთეკად
Add a folder of drawings or a drawing file to use its blocks. დაამატეთ ნახაზების საქაღალდე ან ნახაზის ფაილი მისი ბლოკების გამოსაყენებლად.
Block Libraries ბლოკების ბიბლიოთეკები
@@ -1502,3 +1522,38 @@ menu View ხედი
# ArtCraft feature naming
Additional Tools დამატებითი ხელსაწყოები
# Keyboard Shortcuts, Right-Click Customization, alias import
Keyboard Shortcuts... კლავიატურის მალსახმობები...
Keyboard Shortcuts კლავიატურის მალსახმობები
Replaces the shortcut of {commands} ჩაანაცვლებს ამ ბრძანებების მალსახმობს: {commands}
Needs Ctrl, Alt or a function key საჭიროა Ctrl, Alt ან ფუნქციური კლავიში
Press the keys დააჭირეთ კლავიშებს
Back to CADCraft's shortcut CADCraft-ის მალსახმობზე დაბრუნება
A shortcut you give wins over CADCraft's own. Changes apply at once and are kept for next time. თქვენ მიერ მინიჭებულ მალსახმობს უპირატესობა აქვს CADCraft-ის საკუთარზე. ცვლილებები მაშინვე მოქმედებს და შემდეგი ჯერისთვისაც ინახება.
Turned off, a right-click while a command runs does what Right-Click Customization sets for Command mode. გამორთვისას ბრძანების შესრულების დროს მარჯვენა დაწკაპება იმას აკეთებს, რაც „მარჯვენა დაწკაპების მორგებაში“ ბრძანების რეჟიმისთვის არის არჩეული.
Right-Click Customization... მარჯვენა დაწკაპების მორგება...
Right-Click Customization მარჯვენა დაწკაპების მორგება
Turn on time-sensitive right-click დროზე დამოკიდებული მარჯვენა დაწკაპების ჩართვა
Longer click duration: გრძელი დაწკაპების ხანგრძლივობა:
milliseconds მილიწამი
While a command runs, a quick click is Enter and a longer click opens the shortcut menu. ბრძანების შესრულების დროს მოკლე დაწკაპება Enter-ია, გრძელი დაწკაპება კი კონტექსტურ მენიუს ხსნის.
Default Mode ნაგულისხმევი რეჟიმი
No objects selected and no command running: არაფერია მონიშნული და არცერთი ბრძანება არ სრულდება:
Edit Mode რედაქტირების რეჟიმი
Objects selected and no command running: ობიექტები მონიშნულია და არცერთი ბრძანება არ სრულდება:
Repeat last command ბოლო ბრძანების გამეორება
Shortcut Menu კონტექსტური მენიუ
Command Mode ბრძანების რეჟიმი
While a command runs: ბრძანების შესრულების დროს:
ENTER ENTER
Shortcut Menu: always enabled კონტექსტური მენიუ: ყოველთვის ჩართული
Shortcut Menu: enabled when command options are present კონტექსტური მენიუ: ჩართული, როცა ბრძანებას ვარიანტები აქვს
Import: there is no file dialog here; run ALIASEDIT with the file's contents using its text parameter. იმპორტი: აქ ფაილის არჩევის დიალოგი არ არის; გაუშვით ALIASEDIT და ფაილის შიგთავსი გადაეცით მის text პარამეტრს.
Aliases are saved in your CADCraft profile and survive restarts. ფსევდონიმები თქვენს CADCraft-ის პროფილში ინახება და გადატვირთვის შემდეგაც რჩება.
Import… იმპორტი…
Run ALIASEDIT with the file's contents using its text parameter. გაუშვით ALIASEDIT და ფაილის შიგთავსი გადაეცით მის text პარამეტრს.
Importing a file replaces your {n} aliases, and any changes not applied yet. ფაილის იმპორტი ჩაანაცვლებს თქვენს ფსევდონიმებს ({n}) და ჯერ გამოუყენებელ ცვლილებებს.
Import and replace იმპორტი და ჩანაცვლება
Keep my aliases ჩემი ფსევდონიმების შენარჩუნება
{n} more warnings; see the command line. კიდევ {n} გაფრთხილება; იხილეთ ბრძანების სტრიქონი.
Can't render this file because it contains an unexpected character in line 10 and column 14.
+705
View File
@@ -1511,6 +1511,711 @@ menu Modify Ändra
Ctrl+Enter to apply Ctrl+Enter to apply
Edit Text Edit Text
The drawing changed. Close the window and open it again. Ritningen har ändrats. Stäng fönstret och öppna det igen.
DView DView
Keyboard Shortcuts... Kortkommandon...
Multiple Insert Infoga flera
Raster Image Reference... Rasterbildsreferens...
Raster Images Rasterbilder
Clip Xref Beskär xref
Xref Xref
Xref Clip Frame Beskärningsram för xref
A shortcut you give wins over CADCraft's own. Changes apply at once and are kept for next time. Ett kortkommando du anger går före CADCrafts eget. Ändringar gäller direkt och sparas till nästa gång.
Alias files (PGP) Aliasfiler (PGP)
Aliases are saved in your CADCraft profile and survive restarts. Alias sparas i din CADCraft-profil och finns kvar efter omstart.
Back to CADCraft's shortcut Tillbaka till CADCrafts kortkommando
Command Mode Kommandoläge
Default Mode Standardläge
Edit Mode Redigeringsläge
ENTER ENTER
Import and replace Importera och ersätt
Import: there is no file dialog here; run ALIASEDIT with the file's contents using its text parameter. Importera: det finns ingen fildialogruta här; kör ALIASEDIT med filens innehåll i dess textparameter.
Importing a file replaces your {n} aliases, and any changes not applied yet. Om du importerar en fil ersätts dina {n} alias och alla ändringar du inte har använt än.
Import… Importera…
Keep my aliases Behåll mina alias
Keyboard Shortcuts Kortkommandon
Longer click duration: Längd för längre klick:
milliseconds millisekunder
Needs Ctrl, Alt or a function key Kräver Ctrl, Alt eller en funktionstangent
No objects selected and no command running: Inga objekt markerade och inget kommando körs:
Objects selected and no command running: Objekt markerade och inget kommando körs:
Press the keys Tryck på tangenterna
Repeat last command Upprepa senaste kommandot
Replaces the shortcut of {commands} Ersätter kortkommandot för {commands}
Right-Click Customization Anpassning av högerklick
Right-Click Customization... Anpassning av högerklick...
Run ALIASEDIT with the file's contents using its text parameter. Kör ALIASEDIT med filens innehåll i dess textparameter.
Shortcut Menu Snabbmeny
Shortcut Menu: always enabled Snabbmeny: alltid aktiverad
Shortcut Menu: enabled when command options are present Snabbmeny: aktiverad när det finns kommandoalternativ
Turn on time-sensitive right-click Slå på tidskänsligt högerklick
Turned off, a right-click while a command runs does what Right-Click Customization sets for Command mode. När det är avstängt gör ett högerklick under ett pågående kommando det som Anpassning av högerklick anger för kommandoläget.
While a command runs, a quick click is Enter and a longer click opens the shortcut menu. Medan ett kommando körs är ett snabbt klick Enter och ett längre klick öppnar snabbmenyn.
While a command runs: Medan ett kommando körs:
{n} more warnings; see the command line. {n} varningar till; se kommandoraden.
# ArtCraft feature naming
Additional Tools Ytterligare verktyg
Grid Rutnät
Ortho Orto
Workspace Arbetslayout
Settings Inställningar
Preferences Inställningar
Current: Aktuell:
Continuous Kontinuerlig
Displayed layers Visade lager
Black Svart
Gray Grå
Grey Grå
Orange Orange
Purple Lila
Brown Brun
Pink Rosa
Rename Byt namn
Select Color Välj färg
Layer filters Lagerfilter
Dashed Streckad
Dotted Prickad
Dashdot Streckprickad
Hidden Dold
Phantom Fantom
Clear selection Rensa markering
Model Space Modellrymd
Plot Settings Plottinställningar
Perimeter Omkrets
Polar Polär
Lineweight Display Visning av linjetjocklek
Annotation Anteckning
Annotative Annotativ
Insertion point Insättningspunkt
Base point Baspunkt
Scale factor Skalfaktor
Rotation angle Rotationsvinkel
X coordinate X-koordinat
Y coordinate Y-koordinat
Z coordinate Z-koordinat
Cancel operation Avbryt åtgärden
Reset Återställ
Update Fields Uppdatera fält
Edit Xref in Place Redigera xref på plats
New UCS Nytt UCS
World Världen
Face Yta
Origin Origo
LwPolyline LwPolyline
New Sheet Set... Ny ritningsuppsättning...
Open Sheet Set... Öppna ritningsuppsättning...
Clear Menu Rensa meny
Attach... Koppla...
Export Layout to Model... Exportera layout till modell...
Package Drawing... Paketera ritning...
DWG Compare... DWG-jämförelse...
Markup Import... Importera kommentarer...
Share... Dela...
Undo Group of commands Ångra kommandogrupp
Constrained Orbit Begränsad kretsning
Free Orbit Fri kretsning
Camera Kamera
Adjust Distance Justera avstånd
Swivel Svängning
3D Views 3D-vyer
Viewpoint Vypunkt
Plan View Planvy
Current UCS Aktuellt UCS
World UCS Världs-UCS
Named UCS Namngivna UCS
Bottom Nederkant
Front Framifrån
Back Tillbaka
SW Isometric SV-isometrisk
SE Isometric Isometrisk SO
NE Isometric Isometrisk NO
NW Isometric Isometrisk NV
Hide Dölj
Visual Styles Visuella stilar
2D Wireframe 2D-trådram
Wireframe Trådram
Realistic Realistisk
Conceptual Konceptuell
Shaded Skuggad
Shaded with Edges Skuggad med kanter
Shades of Gray Gråtoner
Sketchy Skissartad
X-Ray Genomskinlig
Render Rendera
New Point Light Nytt punktljus
New Spotlight Ny strålkastare
New Distant Light Nytt avlägset ljus
Light Glyphs Ljusglyfer
Materials Browser Materialbläddrare
Enter Full Screen Visa i helskärm
PDF Underlay... PDF-underlägg...
Field... Fält...
Layout from Template... Layout från mall...
ACIS File... ACIS-fil...
Drawing Exchange Binary... Drawing Exchange Binary...
Spelling Stavning
Linetype Manager Linjetypshanterare
Color Selector Färgväljare
Object Properties Objektegenskaper
Width Bredd
Position Position
Object Snap Settings Inställningar för objektfäste
Polar Tracking Settings Inställningar för polär spårning
Explode Block Lös upp block
Block Name Blocknamn
Coordinate Koordinat
Coordinates Koordinater
Properties Palette Egenskapspalett
Save Changes Spara ändringar
Discard Changes Ignorera ändringar
Are you sure? Är du säker?
Create Skapa
Fit Anpassa
Specify center point Ange centrumpunkt
Align block with object? Justera blocket mot objektet?
Guide crosshairs along cloud path Led hårkorset längs molnets bana
Erase polyline? Radera polylinje?
Calculate rectangle dimensions based on Beräkna rektangelns mått utifrån
Erase source objects? Radera källobjekt?
Object selected is not a polyline. Do you want to turn it into one? Det markerade objektet är inte en polylinje. Vill du göra om det till en?
Scale objects based on alignment points? Skala objekt utifrån justeringspunkter?
Specify radius Ange radie
Specify diameter Ange diameter
Specify opposite corner point Ange motsatt hörnpunkt
Pick internal point Välj inre punkt
{n} commit {n} commit
{n} contributor {n} bidragsgivare
(1, 2, 4, 8, 16, 32, 64, 128, or 256) (1, 2, 4, 8, 16, 32, 64, 128 eller 256)
<Offset> <Förskjutning>
>> Expression >> Uttryck
Associate the hatch with the new boundary? Associera skrafferingen med den nya gränsen?
Associative dimension priority Prioritet för associativa mått
Breakline extension distance Förlängningsavstånd för brytlinje
Breakline symbol size Symbolstorlek för brytlinje
Choose mode for selected object conversion Välj läge för konvertering av markerade objekt
Combine collinear objects that meet end to end Kombinera kolinjära objekt som möts ände mot ände
Combine collinear objects that partially overlap Kombinera kolinjära objekt som delvis överlappar
Combine identical rows? Kombinera identiska rader?
Combine layer property changes into one undo step? Kombinera ändringar av lageregenskaper till ett ångringssteg?
Combine text into a single MTEXT? Kombinera text till en enda MTEXT?
Combine zooms and pans into one undo step? Kombinera zoomningar och panoreringar till ett ångringssteg?
Constant? Konstant?
Convert Lines and Arcs to polylines Konvertera linjer och bågar till polylinjer
Create associative array Skapa associativ array
Delete old boundary(s)? Ta bort gamla gräns(er)?
Drafting mode? Ritläge?
Edit attributes one at a time? Redigera attributen ett i taget?
Edit only attributes visible on screen? Redigera endast attribut som syns på skärmen?
Edit path for which xref(s) Redigera sökväg för vilka xref:ar
Enter Trim mode option Ange alternativ för trimningsläge
Enter UNDO Auto mode Ange UNDO Auto-läge
Enter X scale factor, specify opposite corner Ange X-skalfaktor, ange motsatt hörn
Enter a boundary loop number to remove (starting at 1) Ange numret på gränsloopen som ska tas bort (börjar på 1)
Enter a configuration option Ange ett konfigurationsalternativ
Enter a default viewport visibility option Ange ett alternativ för standardsynlighet i vyfönster
Enter a group description Ange en gruppbeskrivning
Enter a group name Ange ett gruppnamn
Enter a group option Ange ett gruppalternativ
Enter a hatch option Ange ett skrafferingsalternativ
Enter a loaded linetype name Ange namnet på en inläst linjetyp
Enter a name for the new plotter Ange ett namn på den nya plottern
Enter a new name for the group Ange ett nytt namn på gruppen
Enter a plotter option Ange ett plotteralternativ
Enter a plotting preference Ange en plottningsinställning
Enter a projection option Ange ett projektionsalternativ
Enter a property to turn on or off Ange en egenskap att slå på eller av
Enter a scale factor (nX or nXP) Ange en skalfaktor (nX eller nXP)
Enter a text edit mode option Ange ett alternativ för textredigeringsläge
Enter an UNDO control option Ange ett alternativ för UNDO-kontroll
Enter an annotation option Ange ett anteckningsalternativ
Enter an implied edge extension mode Ange ett läge för underförstådd kantförlängning
Enter an option [Add/Remove] <Add> Ange ett alternativ [Add/Remove] <Add>
Enter an option to change Ange ett alternativ att ändra
Enter array type Ange arraytyp
Enter attribute tag Ange attributtagg
Enter attribute tag specification Ange specifikation för attributtagg
Enter attribute value specification Ange specifikation för attributvärde
Enter attribute visibility setting Ange inställning för attributsynlighet
Enter block name or select a block reference Ange blocknamn eller markera en blockreferens
Enter block name or select a block reference [?] Ange blocknamn eller markera en blockreferens [?]
Enter block name specification Ange specifikation för blocknamn
Enter block(s) to list Ange block att lista
Enter choice, 1 to 5 Ange val, 1 till 5
Enter clipping option Ange klippningsalternativ
Enter color name or number (1-255) Ange färgnamn eller -nummer (1-255)
Enter column type Ange kolumntyp
Enter decimal places of accuracy (0 to 16) Ange noggrannhet i antal decimaler (0 till 16)
Enter distance between rows or specify unit cell (---) Ange avstånd mellan rader eller ange enhetscell (---)
Enter file name Ange filnamn
Enter first angle constraint Ange första vinkelvillkor
Enter first line of annotation text or Ange första raden av kommentarstexten eller
Enter first tolerance value Ange första toleransvärde
Enter fit tolerance Ange anpassningstolerans
Enter fuzz distance Ange fuzz-avstånd
Enter group description Ange gruppbeskrivning
Enter group name Ange gruppnamn
Enter group name(s) to list Ange gruppnamn att lista
Enter inspection rate Ange granskningshastighet
Enter inspection shape Ange granskningsform
Enter justification Ange justering
Enter knot parameterization Ange knutparametrisering
Enter label (press ENTER for none) Ange etikett (tryck på ENTER för ingen)
Enter layer description Ange lagerbeskrivning
Enter layer name Ange lagernamn
Enter layer name to make current Ange namnet på lagret som ska bli aktuellt
Enter layer name(s) to change default viewport visibility Ange lagernamn för att ändra standardsynlighet i vyfönster
Enter layer name(s) to list Ange lagernamn att lista
Enter layer option for offset objects Ange lageralternativ för förskjutna objekt
Enter layout name for copy Ange layoutnamn för kopian
Enter layout name(s) to list Ange layoutnamn att lista
Enter layout option Ange layoutalternativ
Enter layout to make current Ange layout som ska bli aktuell
Enter layout to rename Ange layout att byta namn på
Enter layout to save to template Ange layout att spara som mall
Enter leader format option Ange formatalternativ för hänvisningslinje
Enter line spacing factor or distance Ange radavståndsfaktor eller avstånd
Enter line spacing type Ange typ av radavstånd
Enter linetype(s) to load Ange linjetyp(er) att läsa in
Enter lineweight (0.0mm - 2.11mm) Ange linjetjocklek (0,0 mm - 2,11 mm)
Enter magnification or height Ange förstoring eller höjd
Enter maximum part height Ange maximal delhöjd
Enter mline editing option Ange redigeringsalternativ för multilinje
Enter mline style name or [?] Ange namn på multilinjestil eller [?]
Enter name for new layer (becomes the current layer) Ange namn på nytt lager (blir aktuellt lager)
Enter name for new scale Ange namn på ny skala
Enter name for new viewport configuration Ange namn på ny vyfönsterkonfiguration
Enter name list for new layer(s) Ange namnlista för nya lager
Enter name of block to manage Ange namn på block att hantera
Enter name of block to sync Ange namn på block att synkronisera
Enter name of breakline symbol block (. for the built-in symbol) Ange namn på block för brytlinjesymbol (. för den inbyggda symbolen)
Enter name of drawing file to recover Ange namn på ritningsfil att återställa
Enter name of existing block Ange namn på befintligt block
Enter name of layout to copy Ange namn på layout att kopiera
Enter name of layout to delete Ange namn på layout att ta bort
Enter name of linetype file Ange namn på linjetypsfil
Enter name of new layout Ange namn på ny layout
Enter name of output file Ange namn på utdatafil
Enter name of scale to delete Ange namn på skala att ta bort
Enter name of script file Ange namn på skriptfil
Enter name of viewport configuration to restore Ange namn på vyfönsterkonfiguration att återställa
Enter name(s) of new layers frozen in all viewports Ange namn på nya lager som är frusna i alla vyfönster
Enter name(s) of viewport configurations to delete Ange namn på vyfönsterkonfigurationer att ta bort
Enter name(s) of viewport configurations to list Ange namn på vyfönsterkonfigurationer att lista
Enter name(s) to purge Ange namn att rensa
Enter named scale to add Ange namngiven skala att lägga till
Enter named scale to delete Ange namngiven skala att ta bort
Enter new color Ange ny färg
Enter new default value Ange nytt standardvärde
Enter new group name Ange nytt gruppnamn
Enter new layer name Ange nytt lagernamn
Enter new layout name Ange nytt layoutnamn
Enter new linetype name Ange nytt linjetypsnamn
Enter new linetype scale factor Ange ny linjetypsskalfaktor
Enter new lineweight Ange ny linjetjocklek
Enter new order Ange ny ordning
Enter new prompt Ange ny ledtext
Enter new string Ange ny sträng
Enter new tag Ange ny tagg
Enter new text style Ange ny textstil
Enter new value for CONSTRAINTINFER Ange nytt värde för CONSTRAINTINFER
Enter new value for PICKSTYLE Ange nytt värde för PICKSTYLE
Enter new value for THICKNESS Ange nytt värde för THICKNESS
Enter new value for XCLIPFRAME Ange nytt värde för XCLIPFRAME
Enter next line of annotation text Ange nästa rad med kommentarstext
Enter next line of text (empty line to finish) Ange nästa textrad (tom rad för att slutföra)
Enter number of actions Ange antal åtgärder
Enter number of columns (|||) Ange antal kolumner (|||)
Enter number of digits to right of decimal point (0 to 8) Ange antal siffror till höger om decimaltecknet (0 till 8)
Enter number of fractional places for display of angles (0 to 8) Ange antal decimaler för visning av vinklar (0 till 8)
Enter number of items in array Ange antal objekt i arrayen
Enter number of rows (---) Ange antal rader (---)
Enter object ordering option Ange alternativ för objektordning
Enter object type to rename Ange objekttyp att byta namn på
Enter obliquing angle (press ENTER for none) Ange lutningsvinkel (tryck på ENTER för ingen)
Enter old group name Ange gammalt gruppnamn
Enter old layer name Ange gammalt lagernamn
Enter option Ange alternativ
Enter option [Save/Discard reference changes] <Save> Ange alternativ [Spara/Släng referensändringar] <Spara>
Enter properties to match (SELECTSIMILARMODE bit code) Ange egenskaper att matcha (bitkod för SELECTSIMILARMODE)
Enter property to change Ange egenskap att ändra
Enter scale ratio (paper units:drawing units) Ange skalkvot (pappersenheter:ritningsenheter)
Enter second angle constraint Ange andra vinkelvillkoret
Enter second tolerance value Ange andra toleransvärdet
Enter spline creation method Ange metod för att skapa spline
Enter string to change Ange sträng att ändra
Enter style name Ange stilnamn
Enter symbol type to bind Ange symboltyp att bädda in
Enter target layer name Ange namn på mållager
Enter template file name Ange namn på mallfil
Enter the distance between rows or specify unit cell (---) Ange avståndet mellan rader eller ange enhetscell (---)
Enter the drawing to compare with (an open drawing's name or a file path) Ange ritningen att jämföra med (namnet på en öppen ritning eller en sökväg)
Enter the maximum points for leader line Ange största antal punkter för hänvisningslinjen
Enter the name of the block to replace Ange namnet på blocket som ska ersättas
Enter the number of columns (|||) Ange antal kolumner (|||)
Enter the number of items in the array Ange antal objekt i arrayen
Enter the number of levels Ange antal nivåer
Enter the number of operations to undo Ange antal åtgärder att ångra
Enter the number of rows Ange antal rader
Enter the number of rows (---) Ange antal rader (---)
Enter the output Ange utdata
Enter the paper name Ange pappersnamnet
Enter the paper width,height in mm Ange pappersbredd,höjd i mm
Enter the plotter to add a paper size to Ange plottern som en pappersstorlek ska läggas till för
Enter the plotter to delete Ange plottern att ta bort
Enter the type of array Ange typ av array
Enter tolerance location Ange toleransens placering
Enter transparency value Ange genomskinlighetsvärde
Enter transparency value (0-90) Ange genomskinlighetsvärde (0-90)
Enter trim method Ange trimningsmetod
Enter type of dimension editing Ange typ av måttredigering
Enter type of unused objects to purge Ange typ av oanvända objekt att rensa
Enter type of value modification Ange typ av värdeändring
Enter value Ange värde
Enter variable name Ange variabelnamn
Enter view name to restore Ange namn på vy att återställa
Enter view name to save Ange namn på vy att spara
Enter view name(s) to delete Ange namn på vyer att ta bort
Enter view name(s) to list Ange namn på vyer att lista
Enter viewport arrangement Ange vyfönsterarrangemang
Enter viewport configuration name Ange namn på vyfönsterkonfiguration
Enter what to pick Ange vad som ska väljas
Enter xref(s) to list Ange xref att lista
Erase source object after offsetting? Radera källobjektet efter förskjutning?
First point of mid Första punkt för mittpunkt
First tracking point Första spårningspunkt
Fix any errors detected? Åtgärda upptäckta fel?
Get from the drawing or [Point/Distance/Angle/Intersection] Hämta från ritningen eller [Punkt/Avstånd/Vinkel/Skärningspunkt]
Indicate dimension point to add Ange måttpunkt att lägga till
Indicate dimension point to remove Ange måttpunkt att ta bort
Internal error; press Enter to end the command Internt fel; tryck på Enter för att avsluta kommandot
Invisible? Osynlig?
Island detection style Stil för identifiering av öar
Keep associative objects Behåll associativa objekt
Lock the view of viewports? Lås vyn i vyfönster?
Measure angles clockwise? Mäta vinklar medurs?
New color Ny färg
Next point (Press ENTER to end tracking) Nästa punkt (tryck på ENTER för att avsluta spårning)
No mark: undo everything? Inget märke: ångra allt?
Number of objects to move Antal objekt att flytta
Optimize segments within polylines Optimera segment i polylinjer
Pick a table cell Välj en tabellcell
Pick an internal point for the new boundary Välj en inre punkt för den nya gränsen
Red, Green, Blue Röd, grön, blå
Red,Green,Blue Röd,grön,blå
Reset the scale list to the defaults? Återställ skallistan till standardvärdena?
Rotate arrayed items? Rotera objekten i arrayen?
Rotate arrayed objects? Rotera arrayobjekten?
Save changes to array? Spara ändringar i arrayen?
Save layer settings with views? Spara lagerinställningar med vyer?
Second point of mid Andra punkt för mittpunkt
Select a block Markera ett block
Select a content type Välj en innehållstyp
Select a leader type Välj en typ av hänvisningslinje
Select a multileader Markera en multihänvisningslinje
Select a table Markera en tabell
Select a viewport Markera ett vyfönster
Select an item in array to replace Markera ett objekt i arrayen som ska ersättas
Select an object to copy Markera ett objekt att kopiera
Select array Markera array
Select attributes Markera attribut
Select base dimension Markera basmått
Select base point of replacement objects Markera baspunkt för ersättningsobjekten
Select boundary objects (Enter finds them) Markera gränsobjekt (Enter hittar dem)
Select clipping object Markera beskärningsobjekt
Select closed boundary objects to add Markera slutna gränsobjekt att lägga till
Select destination object(s) Markera målobjekt
Select dimension Markera mått
Select dimension to add jog Markera mått att lägga till knäck på
Select dimension to add/remove break Markera mått för att lägga till/ta bort brytning
Select dimensions to space Markera mått att fördela
Select grip to edit array Markera grepp för att redigera arrayen
Select group Markera grupp
Select hatch object Markera skrafferingsobjekt
Select item in array Markera objekt i arrayen
Select jog to remove Markera knäck att ta bort
Select mline Markera multilinje
Select multileader to align to or [Options] Markera multihänvisningslinje att justera mot eller [Alternativ]
Select new datum point Markera ny referenspunkt
Select object on target layer Markera objekt på mållagret
Select object to break dimension Markera objekt som ska bryta måttet
Select object to clip viewport Markera objekt att beskära vyfönstret med
Select object to count or [List/Spaces] Markera objekt att räkna eller [Lista/Blanksteg]
Select objects to add to the group Markera objekt att lägga till i gruppen
Select objects to erase or Markera objekt att radera eller
Select objects to remove from the group Markera objekt att ta bort från gruppen
Select reference objects Markera referensobjekt
Select replacement objects Markera ersättningsobjekt
Select source object Markera källobjekt
Select viewport to clip Markera vyfönster att beskära
Select viewports Markera vyfönster
Sort text top-down? Sortera text uppifrån och ned?
Specify Z scale factor or Ange skalfaktor för Z eller
Specify a fit tolerance Ange en anpassningstolerans
Specify a point on the spline <exit> Ange en punkt på splinen <avsluta>
Specify a precision Ange en precision
Specify base point of objects Ange objektens baspunkt
Specify block attachment Ange blockets anslutning
Specify center location override Ange åsidosatt placering för centrum
Specify center of isocircle Ange isocirkelns centrum
Specify center of view box Ange vyrutans centrum
Specify chamfer angle from the first line Ange fasvinkel från första linjen
Specify chamfer length on the first line Ange faslängd på första linjen
Specify change point Ange ändringspunkt
Specify clipping boundary or select invert option Ange beskärningsgräns eller välj alternativet Invertera
Specify collected multileader location or [Vertical/Horizontal/Wrap] Ange placering för samlad multihänvisningslinje eller [Lodrät/Vågrät/Radbryt]
Specify column height Ange kolumnhöjd
Specify control point <exit> Ange styrpunkt <avsluta>
Specify direction Ange riktning
Specify direction (first point) Ange riktning (första punkten)
Specify direction (second point) Ange riktning (andra punkten)
Specify direction of chord for arc Ange kordans riktning för bågen
Specify direction of vertex tangent Ange riktning för hörnpunktens tangent
Specify displacement Ange förskjutning
Specify displacement base point Ange baspunkt för förskjutning
Specify distance between columns (|||) Ange avstånd mellan kolumner (|||)
Specify end tangent Ange sluttangent
Specify existing fit point <exit> Ange befintlig anpassningspunkt <avsluta>
Specify first break point Ange första brytpunkten
Specify first corner of the unit cell Ange enhetscellens första hörn
Specify first fence point Ange första staketpunkten
Specify first point for arc length dimension Ange första punkten för båglängdsmått
Specify first point for breakline Ange första punkten för brytlinje
Specify first point or [Options] Ange första punkten eller [Alternativ]
Specify fourth point or Ange fjärde punkten eller
Specify gutter width Ange bredd på spaltmellanrum
Specify included angle for arc Ange medelpunktsvinkel för bågen
Specify insertion point of the table Ange tabellens insättningspunkt
Specify jog location Ange placering för knäcken
Specify jog location (or press ENTER) Ange placering för knäcken (eller tryck på ENTER)
Specify leader arrowhead location or [Remove leaders] Ange placering för hänvisningslinjens pilspets eller [Ta bort hänvisningslinjer]
Specify leader start point Ange hänvisningslinjens startpunkt
Specify leaders to remove Ange hänvisningslinjer att ta bort
Specify leaders to remove or [Add leaders] Ange hänvisningslinjer att ta bort eller [Lägg till hänvisningslinjer]
Specify length of line Ange linjens längd
Specify linetype name Ange linjetypens namn
Specify location for break symbol Ange placering för brytsymbol
Specify location of the text Ange textens placering
Specify new angle Ange ny vinkel
Specify new block insertion point Ange blockets nya insättningspunkt
Specify new block rotation angle Ange blockets nya rotationsvinkel
Specify new circle radius Ange cirkelns nya radie
Specify new elevation Ange nytt höjdläge
Specify new fit point <exit> Ange ny anpassningspunkt <avsluta>
Specify new height Ange ny höjd
Specify new length Ange ny längd
Specify new linetype scale Ange ny linjetypsskala
Specify new location Ange ny placering
Specify new location for dimension text Ange ny placering för måttal
Specify new point on spline <exit> Ange ny punkt på splinen <avsluta>
Specify new text insertion point Ange textens nya insättningspunkt
Specify new thickness Ange ny tjocklek
Specify next fence point Ange nästa staketpunkt
Specify number of columns Ange antal kolumner
Specify other corner Ange andra hörnet
Specify quadrant Ange kvadrant
Specify reference angle Ange referensvinkel
Specify reference length Ange referenslängd
Specify rotation around major axis Ange rotation kring storaxeln
Specify scale factor for XYZ axes Ange skalfaktor för XYZ-axlarna
Specify second point for arc length dimension Ange andra punkten för båglängdsmått
Specify second point for breakline Ange andra punkten för brytlinje
Specify size of view box Ange vyrutans storlek
Specify spacing Ange avstånd
Specify temporary OTRACK point Ange tillfällig OTRACK-punkt
Specify text height Ange texthöjd
Specify the angle between items Ange vinkeln mellan objekten
Specify the angle to fill (+=ccw, -=cw) Ange vinkel att fylla (+=moturs, -=medurs)
Specify the distance between columns (|||) Ange avståndet mellan kolumner (|||)
Specify the incrementing elevation between rows Ange höjdökningen mellan rader
Specify the new angle Ange den nya vinkeln
Specify the pattern origin Ange mönstrets origo
Specify the reference angle Ange referensvinkeln
Specify third point Ange tredje punkten
Specify tolerance Ange tolerans
Specify view twist angle Ange vyns vridningsvinkel
Specify width Ange bredd
Specify zoom scale factor Ange skalfaktor för zoom
Type of boundary object Typ av gränsobjekt
Type something to find Skriv något att söka efter
Use landing Använd anslutningslinje
Verify each name to be purged? Bekräfta varje namn som ska rensas?
Where should the data go? Var ska data hamna?
Word-wrap text? Radbryt text?
Remove objects Ta bort objekt
Select geometry to dimension Markera geometri att måttsätta
Select annotative objects Markera annotativa objekt
Specify total width Ange total bredd
Specify column width Ange kolumnbredd
Specify control point Ange styrpunkt
<style overrides> <lokala stiländringar>
A dimension style with this name already exists. Det finns redan en måttstil med det här namnet.
Above Ovanför
Above text Ovanför text
All properties of {style} Alla egenskaper för {style}
All styles Alla stilar
Alt enabled Alt. enheter aktiverade
Alt format Alt. format
Alt precision Alt. precision
Alt prefix Alt. prefix
Alt prefix and suffix Alt. prefix och suffix
Alt round Alt. avrundning
Alt scale factor Alt. skalfaktor
Alt suffix Alt. suffix
Alt zero suppression Alt. nollundertryckning
Alternate Units Alternativa enheter
Angle format Vinkelformat
Angle precision Vinkelprecision
Angular zero suppression Nollundertryckning för vinkelmått
Arc length symbol Båglängdssymbol
Architectural stacked Arkitektonisk, staplad
Architectural tick Arkitektoniskt snedstreck
Arrow 1 Pil 1
Arrow 2 Pil 2
Arrowheads Pilspetsar
Arrows Pilar
At Ext Line 1 Vid måttgränslinje 1
At Ext Line 2 Vid måttgränslinje 2
At least Minst
Baseline spacing Baslinjeavstånd
Before text Före text
Below Nedanför
Best fit Bästa anpassning
Bottom center Nere i mitten
Box blank Låda, tom
Box filled Låda, fylld
Center mark size Centrummarkeringens storlek
Closed blank Sluten, tom
Closed filled Sluten, fylld
Columns Kolumner
Comma Komma
Compare Jämför
Compare Dimension Styles Jämför måttstilar
Compare... Jämför...
Create New Dimension Style Skapa ny måttstil
Current dimension style: {style} Aktuell måttstil: {style}
Datum triangle Referenstriangel
Datum triangle filled Referenstriangel, fylld
Decimal separator Decimalavgränsare
Degrees Minutes Seconds Grader minuter sekunder
Diagonal stacking Diagonal stapling
Dim line color Måttlinjens färg
Dim line ext Måttlinjens förlängning
Dim line forced Tvingad måttlinje
Dim line linetype Måttlinjens linjetyp
Dim line lineweight Måttlinjens linjetjocklek
Dim prefix Måttprefix
Dim roundoff Måttavrundning
Dim scale linear Linjär måttskala
Dim suffix Måttsuffix
Dim units Måttenheter
Dimension Style Måttstil
Dimension Style Manager Hantera måttstilar
Dimension Style Overrides Lokala ändringar av måttstil
Dot Punkt
Dot blank Punkt, tom
Dot small Punkt, liten
Exactly Exakt
Ext line 1 linetype Linjetyp för måttgränslinje 1
Ext line 2 linetype Linjetyp för måttgränslinje 2
Ext line color Måttgränslinjens färg
Ext line ext Måttgränslinjens förlängning
Ext line fixed Fast längd på måttgränslinje
Ext line length Måttgränslinjens längd
Ext line lineweight Måttgränslinjens linjetjocklek
Ext line offset Måttgränslinjens förskjutning
Fraction format Bråkformat
Fractional stacked Bråk, staplat
Gradians Gon
Hide dim line 1 Dölj måttlinje 1
Hide dim line 2 Dölj måttlinje 2
Hide ext line 1 Dölj måttgränslinje 1
Hide ext line 2 Dölj måttgränslinje 2
Horizontal stacking Vågrät stapling
Integral Integral
JIS JIS
Jog angle Brytvinkel
Justification Justering
Keep dim line with text Håll ihop måttlinje och text
Leader arrow Hänvisningspil
Leading Inledande
Line space distance Radavståndsvärde
Line space factor Radavståndsfaktor
Line space style Radavståndsstil
Lines Linjer
Lines & Arrows Linjer och pilar
Lower tolerance Nedre tolerans
Measurement Mätning
Middle I mitten
Middle center I mitten, centrerat
Middle left I mitten till vänster
Middle right I mitten till höger
Misc Övrigt
Modify Dimension Style: {style} Ändra måttstil: {style}
Modify... Ändra...
Move text, add leader Flytta text, lägg till hänvisningslinje
Move text, no leader Flytta text, ingen hänvisningslinje
New Dimension Style: {style} Ny måttstil: {style}
New style name Namn på ny stil
New... Ny...
Not stacked Inte staplat
Obliquing Snedställning
Open 30 Öppen 30
Open arrow Öppen pil
Origin indicator Origoindikator
Origin indicator 2 Origoindikator 2
Outside Utanför
Over Ext Line 1 Över måttgränslinje 1
Over Ext Line 2 Över måttgränslinje 2
Override Current Style: {style} Åsidosätt aktuell stil: {style}
Override... Åsidosätt...
Overrides the dimension style. Right-click to use the style's value. Åsidosätter måttstilen. Högerklicka för att använda stilens värde.
Period Punkt
Prefix and suffix Prefix och suffix
Preview of: {style} Förhandsvisning av: {style}
Preview of: {style} (overrides) Förhandsvisning av: {style} (lokala ändringar)
Primary Units Primära enheter
Remove Style Overrides Ta bort lokala ändringar av stilen
Right angle Rät vinkel
Save as New Style... Spara som ny stil...
Save to current style Spara i aktuell stil
Set by text style "{style}", which has a fixed height. Give the style a height of 0 to use the dimension text height. Styrs av textstilen "{style}", som har fast höjd. Ge stilen höjden 0 för att använda måttalets höjd.
Small Liten
Some of these dimensions take their text height from a fixed-height text style. Några av dessa mått får sin texthöjd från en textstil med fast höjd.
Space Space
Start with Börja med
Style Stil
Styles Stilar
Styles in use Stilar som används
Suppress arrows Utelämna pilar
Symbols and Arrows Symboler och pilar
Text alignment X Textjustering X
Text alignment Y Textjustering Y
Text and arrows Text och pilar
Text inside Text inuti
Text inside align Justering av text inuti
Text movement Textförflyttning
Text offset Textförskjutning
Text outside align Justering av text utanför
Text pos hor Textpos. vågr.
Text pos vert Textpos. lodr.
Text position X Textposition X
Text position Y Textposition Y
Text rotation Textrotation
Text vertical position Lodrät textposition
Tick size Storlek på snedstreck
Tolerance height Toleranshöjd
Tolerance pos vert Tolerans pos. lodr.
Tolerance precision Toleransprecision
Tolerance zero suppression Nollundertryckning för tolerans
Tolerances Toleranser
Top Ovan
Top center Uppe i mitten
Trailing Avslutande
Upper tolerance Övre tolerans
Use the style's value Använd stilens värde
Variable Variabel
Windows desktop Windows-skrivbord
With Med
Zero suppression Nollundertryckning
{count} differences {count} skillnader
{property}: that value can't be used here. {property}: det värdet kan inte användas här.
Can't render this file because it contains an unexpected character in line 1500 and column 24.
+21
View File
@@ -732,3 +732,24 @@ fn polish_plural_forms() {
assert_eq!(plural_pl(n), expected, "n={n}");
}
}
/// Arabic gives Stretch, Trim and Point words of their own: Stretch read «تمديد» like Extend,
/// Trim's prompts said «قص» like Cut, and Point read «تأشير», the catalog's word for dimensioning.
#[test]
fn arabic_tells_stretch_trim_and_point_from_their_neighbours() {
// The words themselves: a pair that merely differs also differs when a row is missing and both
// fall back to English, and Point and Dimension already differed before.
for (key, word) in [("Stretch", "تمطيط"), ("Trim", "تشذيب"), ("Point", "نقطة")] {
assert_eq!(tr("ar", key), word, "{key}");
}
for (a, b) in [("Stretch", "Extend"), ("Trim", "Cut"), ("Point", "Dimension")] {
assert_ne!(tr("ar", a), tr("ar", b), "{a} and {b} share a word");
}
for (prompt, verb) in [
("Select object to trim or shift-select to extend", "تشذيب"),
("Select object to extend or shift-select to trim", "تشذيب"),
("Select objects to stretch by crossing-window or crossing-polygon...", "تمطيط"),
] {
assert!(tr("ar", prompt).contains(verb), "{prompt}");
}
}
+25 -1
View File
@@ -775,7 +775,8 @@ impl CadApp {
/// Open the drawing at `path`. Natively the file is read on a worker thread while an
/// "Opening ..." card shows ([`opening`]); [`Self::finish_opening`] adds it when ready. On the
/// web it opens at once.
/// web it opens at once. An already open drawing is selected without re-reading it, retaining
/// its unsaved edits and view; window drops and Open Recent use this same entry point.
pub fn open_path(&mut self, path: &Path) {
// A LISP file (dropped on the window): loaded as APPLOAD loads it.
if is_lisp_file(path) {
@@ -785,6 +786,9 @@ impl CadApp {
}
return;
}
if self.select_open_drawing(path) {
return;
}
#[cfg(not(target_arch = "wasm32"))]
{
self.opening.start(path);
@@ -815,6 +819,10 @@ impl CadApp {
/// OPEN is reported. Called every frame.
pub fn finish_opening(&mut self) {
for (path, outcome) in self.opening.poll() {
// A drawing may have been opened or saved at this path while the read was pending.
if self.select_open_drawing(&path) {
continue;
}
// A recent file that is gone can never be opened again: drop it from the list. A path
// whose existence can't be checked (a folder that denies access) stays.
if outcome.is_err() && matches!(path.try_exists(), Ok(false)) {
@@ -832,6 +840,22 @@ impl CadApp {
}
}
/// Reuse the existing document through the normal tab-switch command, including symlink paths.
fn select_open_drawing(&mut self, path: &Path) -> bool {
let existing = self.session.docs.iter().position(|d| d.path.as_deref().is_some_and(|p| opening::same_path(Path::new(p), path)));
let Some(index) = existing else { return false };
match self.run("document.switch", json!({"index": index})) {
Ok(_) => {
self.ui.start_tab = false;
if let Some(path) = self.session.docs.get(index).and_then(|d| d.path.clone()) {
self.remember_recent(path);
}
}
Err(error) => self.open_failed(error),
}
true
}
/// Load a LISP file: its routine runs and may wait for the user (APPLOAD typed or from the
/// menu runs this way too).
fn load_lisp(&mut self, name: &str, text: &str) {
+20
View File
@@ -13,6 +13,22 @@ use crate::theme::Tokens;
type Outcome = Result<ReadFile, String>;
/// Compare file paths without requiring the file to still exist. Native aliases are resolved so
/// a symlink and its target share a drawing; web paths can only be compared directly.
pub(crate) fn same_path(a: &Path, b: &Path) -> bool {
if a == b {
return true;
}
#[cfg(not(target_arch = "wasm32"))]
{
a.canonicalize().ok().zip(b.canonicalize().ok()).is_some_and(|(a, b)| a == b)
}
#[cfg(target_arch = "wasm32")]
{
false
}
}
struct Job {
path: PathBuf,
started: Instant,
@@ -28,6 +44,10 @@ pub struct Opening {
impl Opening {
/// Start reading `path` on a worker thread.
pub fn start(&mut self, path: &Path) {
// Repeated events can arrive before the first background read completes.
if self.jobs.iter().any(|j| same_path(&j.path, path)) {
return;
}
let (tx, rx) = channel();
let p = path.to_path_buf();
let spawned = std::thread::Builder::new().name("cadcraft-open".into()).spawn(move || {
+2 -2
View File
@@ -70,11 +70,11 @@ fn opened_drawings_are_listed_newest_first_and_survive_a_restart() {
let labels: Vec<_> = items.iter().map(|(l, _)| l.as_str()).collect();
assert_eq!(labels, ["plan.dxf", "section.dwg", "Clear Recent Files"]);
// Choosing an item opens that file and moves it to the top.
// Choosing an already open item selects its tab and moves it to the top.
let before = app.session.docs.len();
menus::activate(&mut app, &items[1].1);
settle(&mut app);
assert_eq!(app.session.docs.len(), before + 1);
assert_eq!(app.session.docs.len(), before);
assert_eq!(app.session.state().ok().and_then(|s| s.path.clone()), Some(section.clone()));
assert_eq!(app.ui.recent_files, [section.clone(), plan.clone()]);
+153
View File
@@ -0,0 +1,153 @@
//! Reopening a path selects the existing drawing, preserving edits, even across Finder events.
#![cfg(not(target_arch = "wasm32"))]
use cadcraft_engine::Session;
use cadcraft_engine::cmd::file::{IoHooks, set_io};
use cadcraft_engine::doc::Drawing;
use cadcraft_ui_egui::{CadApp, Services};
use serde_json::json;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
struct Files(PathBuf);
impl Files {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = std::env::temp_dir().join(format!("cadcraft-reopen-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
std::fs::create_dir(&root).unwrap();
set_io(IoHooks { read: |_, _| Ok(Drawing::new_metric()), write: |_, _| Ok(Vec::new()), plot: None });
Self(root)
}
fn drawing(&self, name: &str) -> PathBuf {
let path = self.0.join(name);
// Synthetic input: the test reader returns an empty drawing for any bytes.
std::fs::write(&path, b"0\nEOF\n").unwrap();
path
}
}
impl Drop for Files {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn app() -> CadApp {
CadApp::new(Session::empty(), Services::default())
}
fn open(app: &mut CadApp, path: &Path) {
app.open_path(path);
}
fn settle(app: &mut CadApp) {
let deadline = Instant::now() + Duration::from_secs(10);
while app.opening.busy() {
app.finish_opening();
assert!(Instant::now() < deadline, "background OPEN did not finish");
std::thread::sleep(Duration::from_millis(1));
}
}
#[test]
fn reopening_dwg_and_dxf_preserves_edits_view_and_recent_files() {
let files = Files::new();
for name in ["检查井 成果.dwg", "管网 检测.dxf"] {
let path = files.drawing(name);
let mut app = app();
open(&mut app, &path);
settle(&mut app);
app.run("circle", json!({"center": [1, 2], "radius": 3})).unwrap();
let before = app.session.state().unwrap().clone();
app.run("new", json!({})).unwrap();
let count = app.session.docs.len();
app.ui.start_tab = true;
open(&mut app, &path);
assert!(!app.opening.busy(), "an existing drawing must not be re-read");
let after = app.session.state().unwrap();
assert_eq!(after.uid, before.uid);
assert_eq!(after.doc, before.doc);
assert_eq!(after.view(), before.view());
assert_eq!(after.undo.len(), before.undo.len());
assert!(after.is_dirty());
assert_eq!(app.session.docs.len(), count);
assert!(!app.ui.start_tab);
assert_eq!(app.ui.recent_files.first().map(String::as_str), path.to_str());
}
}
#[test]
fn reopening_a_deleted_file_keeps_the_unsaved_drawing() {
let files = Files::new();
let path = files.drawing("deleted.dxf");
let mut app = app();
open(&mut app, &path);
settle(&mut app);
app.run("circle", json!({"center": [1, 2], "radius": 3})).unwrap();
let uid = app.session.state().unwrap().uid;
std::fs::remove_file(&path).unwrap();
app.run("new", json!({})).unwrap();
open(&mut app, &path);
assert!(!app.opening.busy());
assert_eq!(app.session.state().unwrap().uid, uid);
assert!(app.session.state().unwrap().is_dirty());
}
#[test]
fn repeated_requests_while_loading_add_one_tab_per_file() {
let files = Files::new();
let first = files.drawing("first.dxf");
let second = files.drawing("second.dwg");
let mut app = app();
open(&mut app, &first);
open(&mut app, &first);
open(&mut app, &second);
open(&mut app, &first);
settle(&mut app);
assert_eq!(app.session.docs.len(), 2);
assert!(app.session.docs.iter().any(|d| d.path.as_deref() == first.to_str()));
assert!(app.session.docs.iter().any(|d| d.path.as_deref() == second.to_str()));
}
#[cfg(unix)]
#[test]
fn symlinks_share_both_pending_reads_and_existing_dirty_tabs() {
let files = Files::new();
let path = files.drawing("drawing.dxf");
let alias = files.0.join("alias.dxf");
std::os::unix::fs::symlink(&path, &alias).unwrap();
let mut app = app();
open(&mut app, &path);
open(&mut app, &alias);
settle(&mut app);
assert_eq!(app.session.docs.len(), 1);
app.run("circle", json!({"center": [1, 2], "radius": 3})).unwrap();
let uid = app.session.state().unwrap().uid;
app.run("new", json!({})).unwrap();
open(&mut app, &alias);
assert!(!app.opening.busy());
assert_eq!(app.session.docs.len(), 2);
assert_eq!(app.session.state().unwrap().uid, uid);
assert!(app.session.state().unwrap().is_dirty());
}
#[test]
fn a_read_finishing_after_the_path_is_opened_keeps_existing_edits() {
let files = Files::new();
let path = files.drawing("pending.dxf");
let mut app = app();
open(&mut app, &path);
// Simulate another OPEN/Save As assigning this path before the UI polls the background read.
app.run("new", json!({})).unwrap();
app.session.state_mut().unwrap().path = path.to_str().map(str::to_string);
app.run("circle", json!({"center": [1, 2], "radius": 3})).unwrap();
let uid = app.session.state().unwrap().uid;
settle(&mut app);
assert_eq!(app.session.docs.len(), 1);
assert_eq!(app.session.state().unwrap().uid, uid);
assert!(app.session.state().unwrap().is_dirty());
assert_eq!(app.session.doc().unwrap().entity_count(), 1);
}