diff --git a/docs/ui/audit_counts.sh b/docs/ui/audit_counts.sh
index 11738fdf73..6f793f0162 100755
--- a/docs/ui/audit_counts.sh
+++ b/docs/ui/audit_counts.sh
@@ -27,6 +27,7 @@ src/ui/window/authoring_palettes.rs
src/ui/window/tool_palettes.rs
src/ui/window/parameters_manager.rs
src/ui/window/count_palette.rs
+src/ui/window/bricscad_visibility.rs
src/ui/window/layer_walk.rs
src/ui/window/quick_calc/view.rs
src/ui/window/quick_calc/variables_view.rs
diff --git a/docs/ui/audit_counts.txt b/docs/ui/audit_counts.txt
index 80f55accc5..bc3f77c2fc 100644
--- a/docs/ui/audit_counts.txt
+++ b/docs/ui/audit_counts.txt
@@ -9,6 +9,7 @@ src/ui/window/authoring_palettes.rs 0 0
src/ui/window/tool_palettes.rs 0 0
src/ui/window/parameters_manager.rs 0 0
src/ui/window/count_palette.rs 0 17
+src/ui/window/bricscad_visibility.rs 0 0
src/ui/window/layer_walk.rs 0 0
src/ui/window/quick_calc/view.rs 3 44
src/ui/window/quick_calc/variables_view.rs 0 32
diff --git a/docs/wiki/commands/VISIBILITYSTATES.md b/docs/wiki/commands/VISIBILITYSTATES.md
new file mode 100644
index 0000000000..6c9890d339
--- /dev/null
+++ b/docs/wiki/commands/VISIBILITYSTATES.md
@@ -0,0 +1,31 @@
+---
+summary: Creates and edits the visibility states of a BricsCAD parametric block in model space of the block's own drawing, stored the way BricsCAD stores them.
+related: VISIBILITYSTATESPANELOPEN, BVSTATE, BVSHOW, BVHIDE
+web: Not available in the web app.
+---
+
+## Usage
+1. Open the drawing of a BricsCAD parametric block (the block is the drawing's model space), or any drawing to make its model space one, and work in model space.
+2. Type `VISIBILITYSTATES`.
+3. At "Enter a new parameter or [...]", type the name of a visibility parameter. A name not in the list makes a new parameter.
+4. At "Enter a new state for ... or [...]", type the name of a state. A name not in the list makes a new state, in which every object the parameter rules starts hidden.
+5. Pick an action (see below), or press Enter for **Add objects**.
+6. For every action but **Select state**, select the objects and press Enter. Objects you selected before starting the command are used without asking.
+
+## Actions
+| Action | What it does |
+|---|---|
+| **Add objects** (`A`) | The parameter rules the objects: they show in this state only. Objects it already rules do not change. |
+| **Remove objects** (`R`) | The parameter no longer rules the objects, so its states no longer show or hide them. |
+| **make objects Visible** (`V`) | The objects show in this state. Objects the parameter did not rule yet show in this state only. |
+| **make objects Invisible** (`I`) | The objects are hidden in this state. Objects the parameter did not rule yet show in every other state. |
+| **Select state** (`S`) | Makes the state current, showing and hiding the objects the parameters rule. |
+
+## Notes
+- This is BricsCAD's own command for its parametric blocks. A drawing saved as DWG keeps the states where BricsCAD finds them: BricsCAD lists and switches them, and can go on editing them with its own `VISIBILITYSTATES`. Where BricsCAD inserted the block into another drawing, a reference to it lists the states in Properties, where you pick one.
+- An object ruled by several parameters shows only when every one of them shows it.
+- New suppression and object names follow the names the drawing already uses; in a drawing without any they follow the interface language (English or German names).
+- The command works in model space only. In the Block Editor it does nothing, because the copies of the block that its references show would keep the old states; edit the block's own drawing instead.
+- The drawing must be DWG 2010 or later. Dynamic blocks made in OCS or AutoCAD use [`BVSTATE`](BVSTATE-Command) instead.
+- Each run of the command is one undo step.
+- The [Visibility States palette](VISIBILITYSTATESPANELOPEN-Command) does the same with the mouse, and also orders the states.
diff --git a/docs/wiki/commands/VISIBILITYSTATESPANELCLOSE.md b/docs/wiki/commands/VISIBILITYSTATESPANELCLOSE.md
new file mode 100644
index 0000000000..5fbc37dba0
--- /dev/null
+++ b/docs/wiki/commands/VISIBILITYSTATESPANELCLOSE.md
@@ -0,0 +1,8 @@
+---
+summary: Closes the Visibility States palette.
+related: VISIBILITYSTATESPANELOPEN, VISIBILITYSTATES
+web: Not available in the web app.
+---
+
+## Usage
+Type `VISIBILITYSTATESPANELCLOSE`. The Visibility States palette closes; [`VISIBILITYSTATESPANELOPEN`](VISIBILITYSTATESPANELOPEN-Command) opens it again.
diff --git a/docs/wiki/commands/VISIBILITYSTATESPANELOPEN.md b/docs/wiki/commands/VISIBILITYSTATESPANELOPEN.md
new file mode 100644
index 0000000000..33eb55dff3
--- /dev/null
+++ b/docs/wiki/commands/VISIBILITYSTATESPANELOPEN.md
@@ -0,0 +1,40 @@
+---
+summary: Opens the Visibility States palette, where the visibility states of a BricsCAD parametric block are shown, switched, ordered and edited in model space of the block's own drawing.
+related: VISIBILITYSTATES, VISIBILITYSTATESPANELCLOSE, BVSTATE
+ribbon: Parametric tab › Manage panel › Visibility States
+web: Not available in the web app.
+---
+
+## Usage
+1. Open the drawing of a BricsCAD parametric block (the block is the drawing's model space), or any drawing to make its model space one.
+2. Run `VISIBILITYSTATESPANELOPEN`, or click **Visibility States** on the Parametric tab. `VISIBILITYSTATESPANELCLOSE` closes the palette.
+
+## The parameters
+Each visibility parameter is listed with the number of objects it rules and its states. The state shown is marked.
+
+| Control | What it does |
+|---|---|
+| A state | Shows that state. |
+| ▲ / ▼ | Moves the state up or down. Properties lists the states of a block reference in this order. |
+| ▸ (or double-click) | Opens the state's page. |
+| **Add state** | Adds a state with every object of the parameter hidden, shows it and opens its page. |
+| **+** at the top | Adds a parameter: type its name and its first state, then select the objects it starts with. |
+
+## A state's page
+Every object the parameter rules is listed with its type, the layer it is on when shown, and its handle.
+
+| Control | What it does |
+|---|---|
+| Eye | Shows or hides the object in this state. |
+| ✕ | Removes the object from the parameter: its states no longer show or hide it. |
+| A row | Selects the object in the drawing. |
+| Select objects button | Adds objects: they show in this state only. |
+| **Show** | Shows this state. |
+| ◂ | Back to the parameters. |
+
+A warning sign marks an object that shows the same in every state of the parameter.
+
+## Notes
+- Each change is one undo step, and is stored the way BricsCAD stores it (see [`VISIBILITYSTATES`](VISIBILITYSTATES-Command), which does the same from the command line).
+- The palette works in model space only. In the Block Editor or a layout it says so.
+- States are not renamed or deleted here yet.
diff --git a/docs/wiki/pages/Blocks-and-Attributes.md b/docs/wiki/pages/Blocks-and-Attributes.md
index e4b4305737..a57bf02380 100644
--- a/docs/wiki/pages/Blocks-and-Attributes.md
+++ b/docs/wiki/pages/Blocks-and-Attributes.md
@@ -83,6 +83,8 @@ Dynamic blocks change shape through grips on each reference: a door that sets it
**Visibility states.** `BVSTATE` creates and switches visibility states; `BVSHOW` and `BVHIDE` choose which objects show in the current state. Each reference then has a list to pick its state.
+**BricsCAD parametric blocks.** A reference to a block made parametric in BricsCAD lists the states of its visibility parameters in Properties; the state you pick shows the way BricsCAD shows it. [`VISIBILITYSTATES`](VISIBILITYSTATES-Command) creates and edits those states in model space of the block's own drawing, stored where BricsCAD reads them; the [Visibility States palette](VISIBILITYSTATESPANELOPEN-Command) does it with the mouse and orders the states.
+
**Block properties table.** `BTABLE` defines combinations of parameter values in a table, so each reference picks a row.
`BTESTBLOCK` opens a test window to try the block's grips before you save it. `BCONSTRUCTION` marks objects as construction geometry that does not show in the references. Geometric and dimensional constraints work inside blocks too; see [Parametric Constraints](Parametric-Constraints).
diff --git a/docs/wiki/since.json b/docs/wiki/since.json
index 69e578a0f5..996aa3679a 100644
--- a/docs/wiki/since.json
+++ b/docs/wiki/since.json
@@ -905,6 +905,9 @@
"VCONSTRAINT": "2026.37",
"VERTICAL": "0.1.4",
"VIEW": "0.1.3",
+"VISIBILITYSTATES": "2026.47",
+"VISIBILITYSTATESPANELCLOSE": "2026.47",
+"VISIBILITYSTATESPANELOPEN": "2026.47",
"VISRETAIN": "0.7.0",
"VISUALSTYLES": "0.7.0",
"VPCLIP": "2026.39",
diff --git a/locales/ar-SA/opencadstudio.ftl b/locales/ar-SA/opencadstudio.ftl
index 7698fbbc97..d6770c0482 100644
--- a/locales/ar-SA/opencadstudio.ftl
+++ b/locales/ar-SA/opencadstudio.ftl
@@ -3602,6 +3602,42 @@ modify =
.bvstate-exists = حالة الرؤية "__ocs_fmt_0__" موجودة بالفعل.
.bvstate-last = لا يمكن حذف حالة الرؤية الوحيدة.
.bvstate-needs-bedit = __ocs_fmt_0__: افتح الكتلة أولاً في محرر الكتل (BEDIT).
+ .visibilitystates-parameter = VISIBILITYSTATES أدخل معلمة جديدة:
+ .visibilitystates-parameter-or = VISIBILITYSTATES أدخل معلمة جديدة أو [__ocs_fmt_0__]:
+ .visibilitystates-state = VISIBILITYSTATES أدخل حالة جديدة لـ __ocs_fmt_0__:
+ .visibilitystates-state-or = VISIBILITYSTATES أدخل حالة جديدة لـ __ocs_fmt_0__ أو [__ocs_fmt_1__]:
+ .visibilitystates-action = VISIBILITYSTATES حدد إجراءً [إضافة/إزالة/إظهار/إخفاء/تحديد الحالة] <إضافة>:
+ .visibilitystates-add-objects = إضافة كائنات
+ .visibilitystates-remove-objects = إزالة كائنات
+ .visibilitystates-make-visible = إظهار الكائنات
+ .visibilitystates-make-invisible = إخفاء الكائنات
+ .visibilitystates-select-state = تحديد الحالة
+ .visibilitystates-model-space = يعمل VISIBILITYSTATES في فضاء النموذج: افتح رسم كتلة BricsCAD.
+ .visibilitystates-unsupported = لا يمكن تحرير حالات الرؤية هنا.
+ .visibilitystates-old-format = تتطلب حالات الرؤية رسمًا بتنسيق DWG 2010 أو أحدث.
+ .visibilitystates-no-parameter = لا توجد معلمة رؤية بهذا الاسم.
+ .visibilitystates-no-state = لا توجد حالة رؤية بهذا الاسم.
+ .visibilitystates-state-exists = حالة الرؤية هذه موجودة بالفعل.
+ .visibilitystates-cannot-move = لا يمكن نقل حالة الرؤية أكثر من ذلك.
+ .visibilitystates-bad-name = أدخل اسمًا من أحرف وأرقام وشرطات سفلية.
+ .visibilitystates-name-taken = هذا الاسم يستخدمه متغير آخر.
+ .visibilitystates-no-objects = حدد كائنات من الفضاء الجاري تحريره.
+ .visibilitystates-panel-elsewhere = تُحرَّر حالات الرؤية في فضاء النموذج لرسم الكتلة نفسها.
+ .visibilitystates-panel-unsupported = لا يمكن تحرير حالات الرؤية في هذا الرسم هنا.
+ .visibilitystates-first-state = الحالة الأولى
+ .visibilitystates-panel-empty = لا توجد حالات رؤية في هذا الرسم. انقر + لإضافة معلمة.
+ .visibilitystates-parameter-objects = __ocs_fmt_0__ (الكائنات: __ocs_fmt_1__)
+ .visibilitystates-move-up = نقل لأعلى
+ .visibilitystates-move-down = نقل لأسفل
+ .visibilitystates-state-objects = كائنات هذه الحالة
+ .visibilitystates-new-state = حالة جديدة
+ .visibilitystates-add-state = إضافة حالة
+ .visibilitystates-back = العودة إلى المعلمات
+ .visibilitystates-add-to-state = إضافة كائنات إلى هذه الحالة
+ .visibilitystates-no-objects-yet = لا تتحكم المعلمة في أي كائنات بعد. أضف كائنات إلى هذه الحالة.
+ .visibilitystates-remove-from-parameter = إزالة من المعلمة
+ .visibilitystates-same-everywhere = يظهر بالشكل نفسه في كل حالات المعلمة
+ .visibilitystates-same-everywhere-note = يظهر كائن واحد أو أكثر بالشكل نفسه في كل حالات هذه المعلمة.
.bvstate-current = حالة الرؤية الحالية: __ocs_fmt_0__
.bvhide-select = حدد الكائنات المراد إخفاؤها:
.bvshow-select = حدد الكائنات المراد إظهارها:
diff --git a/locales/bg-BG/opencadstudio.ftl b/locales/bg-BG/opencadstudio.ftl
index a764783c87..217bfd5ebf 100644
--- a/locales/bg-BG/opencadstudio.ftl
+++ b/locales/bg-BG/opencadstudio.ftl
@@ -3589,6 +3589,42 @@ modify =
.bvstate-exists = Състоянието на видимост "__ocs_fmt_0__" вече съществува.
.bvstate-last = Единственото състояние на видимост не може да бъде изтрито.
.bvstate-needs-bedit = __ocs_fmt_0__: първо отворете блока в редактора на блокове (BEDIT).
+ .visibilitystates-parameter = VISIBILITYSTATES Въведете нов параметър:
+ .visibilitystates-parameter-or = VISIBILITYSTATES Въведете нов параметър или [__ocs_fmt_0__]:
+ .visibilitystates-state = VISIBILITYSTATES Въведете ново състояние за __ocs_fmt_0__:
+ .visibilitystates-state-or = VISIBILITYSTATES Въведете ново състояние за __ocs_fmt_0__ или [__ocs_fmt_1__]:
+ .visibilitystates-action = VISIBILITYSTATES Изберете действие [Добави/Отстрани/Покажи/Скрий/Избери състояние] <Добави>:
+ .visibilitystates-add-objects = Добави обекти
+ .visibilitystates-remove-objects = Отстрани обекти
+ .visibilitystates-make-visible = Направи обектите видими
+ .visibilitystates-make-invisible = Направи обектите невидими
+ .visibilitystates-select-state = Избери състояние
+ .visibilitystates-model-space = VISIBILITYSTATES работи в пространството на модела: отворете чертежа на блока на BricsCAD.
+ .visibilitystates-unsupported = Състоянията на видимост тук не могат да се редактират.
+ .visibilitystates-old-format = Състоянията на видимост изискват чертеж във формат DWG 2010 или по-нов.
+ .visibilitystates-no-parameter = Няма параметър на видимост с това име.
+ .visibilitystates-no-state = Няма състояние на видимост с това име.
+ .visibilitystates-state-exists = Това състояние на видимост вече съществува.
+ .visibilitystates-cannot-move = Състоянието на видимост не може да се премести повече.
+ .visibilitystates-bad-name = Въведете име от букви, цифри и долни черти.
+ .visibilitystates-name-taken = Това име се използва от друга променлива.
+ .visibilitystates-no-objects = Изберете обекти от редактираното пространство.
+ .visibilitystates-panel-elsewhere = Състоянията на видимост се редактират в пространството на модела на собствения чертеж на блока.
+ .visibilitystates-panel-unsupported = Състоянията на видимост на този чертеж не могат да се редактират тук.
+ .visibilitystates-first-state = Първо състояние
+ .visibilitystates-panel-empty = В този чертеж няма състояния на видимост. Щракнете върху +, за да добавите параметър.
+ .visibilitystates-parameter-objects = __ocs_fmt_0__ (обекти: __ocs_fmt_1__)
+ .visibilitystates-move-up = Премести нагоре
+ .visibilitystates-move-down = Премести надолу
+ .visibilitystates-state-objects = Обекти на това състояние
+ .visibilitystates-new-state = Ново състояние
+ .visibilitystates-add-state = Добави състояние
+ .visibilitystates-back = Обратно към параметрите
+ .visibilitystates-add-to-state = Добави обекти към това състояние
+ .visibilitystates-no-objects-yet = Параметърът все още не управлява обекти. Добавете обекти към това състояние.
+ .visibilitystates-remove-from-parameter = Премахни от параметъра
+ .visibilitystates-same-everywhere = Еднакво във всички състояния на параметъра
+ .visibilitystates-same-everywhere-note = Един или повече обекти изглеждат еднакво във всички състояния на този параметър.
.bvstate-current = Текущо състояние на видимост: __ocs_fmt_0__
.bvhide-select = Изберете обекти за скриване:
.bvshow-select = Изберете обекти за показване:
diff --git a/locales/cs-CZ/opencadstudio.ftl b/locales/cs-CZ/opencadstudio.ftl
index 5f2bcbab53..1b4575642d 100644
--- a/locales/cs-CZ/opencadstudio.ftl
+++ b/locales/cs-CZ/opencadstudio.ftl
@@ -3594,6 +3594,42 @@ modify =
.bvstate-exists = Stav viditelnosti „__ocs_fmt_0__“ již existuje.
.bvstate-last = Jediný stav viditelnosti nelze odstranit.
.bvstate-needs-bedit = __ocs_fmt_0__: nejprve otevřete blok v editoru bloků (BEDIT).
+ .visibilitystates-parameter = VISIBILITYSTATES Zadejte nový parametr:
+ .visibilitystates-parameter-or = VISIBILITYSTATES Zadejte nový parametr nebo [__ocs_fmt_0__]:
+ .visibilitystates-state = VISIBILITYSTATES Zadejte nový stav pro __ocs_fmt_0__:
+ .visibilitystates-state-or = VISIBILITYSTATES Zadejte nový stav pro __ocs_fmt_0__ nebo [__ocs_fmt_1__]:
+ .visibilitystates-action = VISIBILITYSTATES Vyberte akci [Přidat/Odebrat/Zobrazit/Skrýt/Vybrat stav]
:
+ .visibilitystates-add-objects = Přidat objekty
+ .visibilitystates-remove-objects = Odebrat objekty
+ .visibilitystates-make-visible = Zobrazit objekty
+ .visibilitystates-make-invisible = Skrýt objekty
+ .visibilitystates-select-state = Vybrat stav
+ .visibilitystates-model-space = VISIBILITYSTATES pracuje v modelovém prostoru: otevřete výkres bloku BricsCAD.
+ .visibilitystates-unsupported = Stavy viditelnosti zde nelze upravovat.
+ .visibilitystates-old-format = Stavy viditelnosti vyžadují výkres ve formátu DWG 2010 nebo novějším.
+ .visibilitystates-no-parameter = Parametr viditelnosti s tímto názvem neexistuje.
+ .visibilitystates-no-state = Stav viditelnosti s tímto názvem neexistuje.
+ .visibilitystates-state-exists = Tento stav viditelnosti již existuje.
+ .visibilitystates-cannot-move = Stav viditelnosti nelze dále přesunout.
+ .visibilitystates-bad-name = Zadejte název z písmen, číslic a podtržítek.
+ .visibilitystates-name-taken = Tento název používá jiná proměnná.
+ .visibilitystates-no-objects = Vyberte objekty z upravovaného prostoru.
+ .visibilitystates-panel-elsewhere = Stavy viditelnosti se upravují v modelovém prostoru vlastního výkresu bloku.
+ .visibilitystates-panel-unsupported = Stavy viditelnosti tohoto výkresu zde nelze upravovat.
+ .visibilitystates-first-state = První stav
+ .visibilitystates-panel-empty = V tomto výkresu nejsou žádné stavy viditelnosti. Klikněte na + a přidejte parametr.
+ .visibilitystates-parameter-objects = __ocs_fmt_0__ (objektů: __ocs_fmt_1__)
+ .visibilitystates-move-up = Posunout nahoru
+ .visibilitystates-move-down = Posunout dolů
+ .visibilitystates-state-objects = Objekty tohoto stavu
+ .visibilitystates-new-state = Nový stav
+ .visibilitystates-add-state = Přidat stav
+ .visibilitystates-back = Zpět na parametry
+ .visibilitystates-add-to-state = Přidat objekty do tohoto stavu
+ .visibilitystates-no-objects-yet = Parametr zatím neřídí žádné objekty. Přidejte do tohoto stavu objekty.
+ .visibilitystates-remove-from-parameter = Odebrat z parametru
+ .visibilitystates-same-everywhere = Ve všech stavech parametru stejné
+ .visibilitystates-same-everywhere-note = Jeden nebo více objektů se ve všech stavech tohoto parametru zobrazuje stejně.
.bvstate-current = Aktuální stav viditelnosti: __ocs_fmt_0__
.bvhide-select = Vyberte objekty ke skrytí:
.bvshow-select = Vyberte objekty k zobrazení:
diff --git a/locales/de-DE/opencadstudio.ftl b/locales/de-DE/opencadstudio.ftl
index 4147fb0fd8..d3b963c379 100644
--- a/locales/de-DE/opencadstudio.ftl
+++ b/locales/de-DE/opencadstudio.ftl
@@ -3590,6 +3590,42 @@ modify =
.bvstate-exists = Sichtbarkeitsstatus "__ocs_fmt_0__" existiert bereits.
.bvstate-last = Der einzige Sichtbarkeitsstatus kann nicht gelöscht werden.
.bvstate-needs-bedit = __ocs_fmt_0__: Öffnen Sie den Block zuerst im Blockeditor (BEDIT).
+ .visibilitystates-parameter = VISIBILITYSTATES Neuen Parameter eingeben:
+ .visibilitystates-parameter-or = VISIBILITYSTATES Neuen Parameter eingeben oder [__ocs_fmt_0__]:
+ .visibilitystates-state = VISIBILITYSTATES Neuen Status eingeben für __ocs_fmt_0__:
+ .visibilitystates-state-or = VISIBILITYSTATES Neuen Status eingeben für __ocs_fmt_0__ oder [__ocs_fmt_1__]:
+ .visibilitystates-action = VISIBILITYSTATES Aktion auswählen [Hinzufügen/Entfernen/SIchtbar machen/Unsichtbar machen/STatus auswählen] :
+ .visibilitystates-add-objects = Objekte hinzufügen
+ .visibilitystates-remove-objects = Objekte entfernen
+ .visibilitystates-make-visible = Objekte sichtbar machen
+ .visibilitystates-make-invisible = Objekte unsichtbar machen
+ .visibilitystates-select-state = Status auswählen
+ .visibilitystates-model-space = VISIBILITYSTATES arbeitet im Modellbereich: Öffnen Sie die Zeichnung des BricsCAD-Blocks.
+ .visibilitystates-unsupported = Die Sichtbarkeitsstatus hier können nicht bearbeitet werden.
+ .visibilitystates-old-format = Sichtbarkeitsstatus brauchen eine Zeichnung im Format DWG 2010 oder neuer.
+ .visibilitystates-no-parameter = Kein Sichtbarkeitsparameter mit diesem Namen.
+ .visibilitystates-no-state = Kein Sichtbarkeitsstatus mit diesem Namen.
+ .visibilitystates-state-exists = Dieser Sichtbarkeitsstatus ist bereits vorhanden.
+ .visibilitystates-cannot-move = Der Sichtbarkeitsstatus kann nicht weiter verschoben werden.
+ .visibilitystates-bad-name = Geben Sie einen Namen aus Buchstaben, Ziffern und Unterstrichen ein.
+ .visibilitystates-name-taken = Dieser Name wird von einer anderen Variablen verwendet.
+ .visibilitystates-no-objects = Wählen Sie Objekte des bearbeiteten Bereichs.
+ .visibilitystates-panel-elsewhere = Sichtbarkeitsstatus werden im Modellbereich der Zeichnung des Blocks bearbeitet.
+ .visibilitystates-panel-unsupported = Die Sichtbarkeitsstatus dieser Zeichnung können hier nicht bearbeitet werden.
+ .visibilitystates-first-state = Erster Status
+ .visibilitystates-panel-empty = In dieser Zeichnung gibt es keine Sichtbarkeitsstatus. Klicken Sie auf +, um einen Parameter hinzuzufügen.
+ .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ Objekte)
+ .visibilitystates-move-up = Nach oben
+ .visibilitystates-move-down = Nach unten
+ .visibilitystates-state-objects = Objekte dieses Status
+ .visibilitystates-new-state = Neuer Status
+ .visibilitystates-add-state = Status hinzufügen
+ .visibilitystates-back = Zurück zu den Parametern
+ .visibilitystates-add-to-state = Objekte zu diesem Status hinzufügen
+ .visibilitystates-no-objects-yet = Der Parameter steuert noch keine Objekte. Fügen Sie diesem Status Objekte hinzu.
+ .visibilitystates-remove-from-parameter = Aus Parameter entfernen
+ .visibilitystates-same-everywhere = In allen Status des Parameters gleich
+ .visibilitystates-same-everywhere-note = Ein oder mehrere Objekte sind in allen Status dieses Parameters gleich (un)sichtbar.
.bvstate-current = Aktueller Sichtbarkeitsstatus: __ocs_fmt_0__
.bvhide-select = Auszublendende Objekte wählen:
.bvshow-select = Einzublendende Objekte wählen:
diff --git a/locales/el-GR/opencadstudio.ftl b/locales/el-GR/opencadstudio.ftl
index 989fc721f2..dd7ee0d1f2 100644
--- a/locales/el-GR/opencadstudio.ftl
+++ b/locales/el-GR/opencadstudio.ftl
@@ -3590,6 +3590,42 @@ modify =
.bvstate-exists = Η κατάσταση ορατότητας "__ocs_fmt_0__" υπάρχει ήδη.
.bvstate-last = Η μοναδική κατάσταση ορατότητας δεν μπορεί να διαγραφεί.
.bvstate-needs-bedit = __ocs_fmt_0__: ανοίξτε πρώτα το μπλοκ στον επεξεργαστή μπλοκ (BEDIT).
+ .visibilitystates-parameter = VISIBILITYSTATES Δώστε νέα παράμετρο:
+ .visibilitystates-parameter-or = VISIBILITYSTATES Δώστε νέα παράμετρο ή [__ocs_fmt_0__]:
+ .visibilitystates-state = VISIBILITYSTATES Δώστε νέα κατάσταση για __ocs_fmt_0__:
+ .visibilitystates-state-or = VISIBILITYSTATES Δώστε νέα κατάσταση για __ocs_fmt_0__ ή [__ocs_fmt_1__]:
+ .visibilitystates-action = VISIBILITYSTATES Επιλέξτε ενέργεια [Προσθήκη/Αφαίρεση/Εμφάνιση/Απόκρυψη/Επιλογή κατάστασης] <Προσθήκη>:
+ .visibilitystates-add-objects = Προσθήκη αντικειμένων
+ .visibilitystates-remove-objects = Αφαίρεση αντικειμένων
+ .visibilitystates-make-visible = Εμφάνιση αντικειμένων
+ .visibilitystates-make-invisible = Απόκρυψη αντικειμένων
+ .visibilitystates-select-state = Επιλογή κατάστασης
+ .visibilitystates-model-space = Η VISIBILITYSTATES λειτουργεί στον χώρο μοντέλου: ανοίξτε το σχέδιο του μπλοκ BricsCAD.
+ .visibilitystates-unsupported = Οι καταστάσεις ορατότητας εδώ δεν μπορούν να επεξεργαστούν.
+ .visibilitystates-old-format = Οι καταστάσεις ορατότητας απαιτούν σχέδιο σε μορφή DWG 2010 ή νεότερη.
+ .visibilitystates-no-parameter = Δεν υπάρχει παράμετρος ορατότητας με αυτό το όνομα.
+ .visibilitystates-no-state = Δεν υπάρχει κατάσταση ορατότητας με αυτό το όνομα.
+ .visibilitystates-state-exists = Αυτή η κατάσταση ορατότητας υπάρχει ήδη.
+ .visibilitystates-cannot-move = Η κατάσταση ορατότητας δεν μπορεί να μετακινηθεί άλλο.
+ .visibilitystates-bad-name = Δώστε όνομα από γράμματα, ψηφία και κάτω παύλες.
+ .visibilitystates-name-taken = Αυτό το όνομα χρησιμοποιείται από άλλη μεταβλητή.
+ .visibilitystates-no-objects = Επιλέξτε αντικείμενα του χώρου που επεξεργάζεστε.
+ .visibilitystates-panel-elsewhere = Οι καταστάσεις ορατότητας επεξεργάζονται στον χώρο μοντέλου του σχεδίου του ίδιου του μπλοκ.
+ .visibilitystates-panel-unsupported = Οι καταστάσεις ορατότητας αυτού του σχεδίου δεν μπορούν να επεξεργαστούν εδώ.
+ .visibilitystates-first-state = Πρώτη κατάσταση
+ .visibilitystates-panel-empty = Δεν υπάρχουν καταστάσεις ορατότητας σε αυτό το σχέδιο. Κάντε κλικ στο + για να προσθέσετε παράμετρο.
+ .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ αντικείμενα)
+ .visibilitystates-move-up = Μετακίνηση πάνω
+ .visibilitystates-move-down = Μετακίνηση κάτω
+ .visibilitystates-state-objects = Αντικείμενα αυτής της κατάστασης
+ .visibilitystates-new-state = Νέα κατάσταση
+ .visibilitystates-add-state = Προσθήκη κατάστασης
+ .visibilitystates-back = Επιστροφή στις παραμέτρους
+ .visibilitystates-add-to-state = Προσθήκη αντικειμένων σε αυτή την κατάσταση
+ .visibilitystates-no-objects-yet = Η παράμετρος δεν ελέγχει ακόμη αντικείμενα. Προσθέστε αντικείμενα σε αυτή την κατάσταση.
+ .visibilitystates-remove-from-parameter = Αφαίρεση από την παράμετρο
+ .visibilitystates-same-everywhere = Ίδια εμφάνιση σε όλες τις καταστάσεις της παραμέτρου
+ .visibilitystates-same-everywhere-note = Ένα ή περισσότερα αντικείμενα εμφανίζονται ίδια σε όλες τις καταστάσεις αυτής της παραμέτρου.
.bvstate-current = Τρέχουσα κατάσταση ορατότητας: __ocs_fmt_0__
.bvhide-select = Επιλέξτε αντικείμενα για απόκρυψη:
.bvshow-select = Επιλέξτε αντικείμενα για εμφάνιση:
diff --git a/locales/en-US/opencadstudio.ftl b/locales/en-US/opencadstudio.ftl
index adb4a30937..1025816ed6 100644
--- a/locales/en-US/opencadstudio.ftl
+++ b/locales/en-US/opencadstudio.ftl
@@ -3591,6 +3591,42 @@ modify =
.bvstate-exists = Visibility state "__ocs_fmt_0__" already exists.
.bvstate-last = The only visibility state cannot be deleted.
.bvstate-needs-bedit = __ocs_fmt_0__: open the block in the Block Editor first (BEDIT).
+ .visibilitystates-parameter = VISIBILITYSTATES Enter a new parameter:
+ .visibilitystates-parameter-or = VISIBILITYSTATES Enter a new parameter or [__ocs_fmt_0__]:
+ .visibilitystates-state = VISIBILITYSTATES Enter a new state for __ocs_fmt_0__:
+ .visibilitystates-state-or = VISIBILITYSTATES Enter a new state for __ocs_fmt_0__ or [__ocs_fmt_1__]:
+ .visibilitystates-action = VISIBILITYSTATES Select action [Add objects/Remove objects/make objects Visible/make objects Invisible/Select state] :
+ .visibilitystates-add-objects = Add objects
+ .visibilitystates-remove-objects = Remove objects
+ .visibilitystates-make-visible = make objects Visible
+ .visibilitystates-make-invisible = make objects Invisible
+ .visibilitystates-select-state = Select state
+ .visibilitystates-model-space = VISIBILITYSTATES works in model space: open the drawing of the BricsCAD block.
+ .visibilitystates-unsupported = The visibility states here cannot be edited.
+ .visibilitystates-old-format = Visibility states need a drawing in DWG 2010 format or later.
+ .visibilitystates-no-parameter = No visibility parameter of that name.
+ .visibilitystates-no-state = No visibility state of that name.
+ .visibilitystates-state-exists = That visibility state exists already.
+ .visibilitystates-cannot-move = The visibility state cannot move further.
+ .visibilitystates-bad-name = Enter a name of letters, digits and underscores.
+ .visibilitystates-name-taken = That name is used by another variable.
+ .visibilitystates-no-objects = Select objects of the space being edited.
+ .visibilitystates-panel-elsewhere = Visibility states are edited in model space of the block's own drawing.
+ .visibilitystates-panel-unsupported = The visibility states of this drawing cannot be edited here.
+ .visibilitystates-first-state = First state
+ .visibilitystates-panel-empty = There are no visibility states in this drawing. Click + to add a parameter.
+ .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ objects)
+ .visibilitystates-move-up = Move up
+ .visibilitystates-move-down = Move down
+ .visibilitystates-state-objects = Objects of this state
+ .visibilitystates-new-state = New state
+ .visibilitystates-add-state = Add state
+ .visibilitystates-back = Back to the parameters
+ .visibilitystates-add-to-state = Add objects to this state
+ .visibilitystates-no-objects-yet = The parameter rules no objects yet. Add objects to this state.
+ .visibilitystates-remove-from-parameter = Remove from parameter
+ .visibilitystates-same-everywhere = Shown the same in every state of the parameter
+ .visibilitystates-same-everywhere-note = One or more objects show the same in every state of this parameter.
.bvstate-current = Current visibility state: __ocs_fmt_0__
.bvhide-select = Select objects to hide:
.bvshow-select = Select objects to make visible:
diff --git a/locales/es-ES/opencadstudio.ftl b/locales/es-ES/opencadstudio.ftl
index 7d23d3eda9..01926c72fe 100644
--- a/locales/es-ES/opencadstudio.ftl
+++ b/locales/es-ES/opencadstudio.ftl
@@ -3590,6 +3590,42 @@ modify =
.bvstate-exists = El estado de visibilidad "__ocs_fmt_0__" ya existe.
.bvstate-last = No se puede suprimir el único estado de visibilidad.
.bvstate-needs-bedit = __ocs_fmt_0__: abra primero el bloque en el Editor de bloques (BEDIT).
+ .visibilitystates-parameter = VISIBILITYSTATES Indique un nuevo parámetro:
+ .visibilitystates-parameter-or = VISIBILITYSTATES Indique un nuevo parámetro o [__ocs_fmt_0__]:
+ .visibilitystates-state = VISIBILITYSTATES Indique un nuevo estado para __ocs_fmt_0__:
+ .visibilitystates-state-or = VISIBILITYSTATES Indique un nuevo estado para __ocs_fmt_0__ o [__ocs_fmt_1__]:
+ .visibilitystates-action = VISIBILITYSTATES Seleccione una acción [Añadir/Quitar/Mostrar/Ocultar/Seleccionar estado] :
+ .visibilitystates-add-objects = Añadir objetos
+ .visibilitystates-remove-objects = Quitar objetos
+ .visibilitystates-make-visible = Mostrar objetos
+ .visibilitystates-make-invisible = Ocultar objetos
+ .visibilitystates-select-state = Seleccionar estado
+ .visibilitystates-model-space = VISIBILITYSTATES funciona en el espacio modelo: abra el dibujo del bloque de BricsCAD.
+ .visibilitystates-unsupported = Aquí no se pueden editar los estados de visibilidad.
+ .visibilitystates-old-format = Los estados de visibilidad requieren un dibujo en formato DWG 2010 o posterior.
+ .visibilitystates-no-parameter = No hay ningún parámetro de visibilidad con ese nombre.
+ .visibilitystates-no-state = No hay ningún estado de visibilidad con ese nombre.
+ .visibilitystates-state-exists = Ese estado de visibilidad ya existe.
+ .visibilitystates-cannot-move = El estado de visibilidad no se puede desplazar más.
+ .visibilitystates-bad-name = Indique un nombre con letras, dígitos y guiones bajos.
+ .visibilitystates-name-taken = Ese nombre lo usa otra variable.
+ .visibilitystates-no-objects = Seleccione objetos del espacio que se está editando.
+ .visibilitystates-panel-elsewhere = Los estados de visibilidad se editan en el espacio modelo del propio dibujo del bloque.
+ .visibilitystates-panel-unsupported = Los estados de visibilidad de este dibujo no se pueden editar aquí.
+ .visibilitystates-first-state = Primer estado
+ .visibilitystates-panel-empty = No hay estados de visibilidad en este dibujo. Haga clic en + para añadir un parámetro.
+ .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ objetos)
+ .visibilitystates-move-up = Subir
+ .visibilitystates-move-down = Bajar
+ .visibilitystates-state-objects = Objetos de este estado
+ .visibilitystates-new-state = Nuevo estado
+ .visibilitystates-add-state = Añadir estado
+ .visibilitystates-back = Volver a los parámetros
+ .visibilitystates-add-to-state = Añadir objetos a este estado
+ .visibilitystates-no-objects-yet = El parámetro aún no controla ningún objeto. Añada objetos a este estado.
+ .visibilitystates-remove-from-parameter = Quitar del parámetro
+ .visibilitystates-same-everywhere = Igual en todos los estados del parámetro
+ .visibilitystates-same-everywhere-note = Uno o varios objetos se muestran igual en todos los estados de este parámetro.
.bvstate-current = Estado de visibilidad actual: __ocs_fmt_0__
.bvhide-select = Seleccione los objetos que se ocultarán:
.bvshow-select = Seleccione los objetos que se harán visibles:
diff --git a/locales/fi-FI/opencadstudio.ftl b/locales/fi-FI/opencadstudio.ftl
index 4ea8c93e21..df92ac0110 100644
--- a/locales/fi-FI/opencadstudio.ftl
+++ b/locales/fi-FI/opencadstudio.ftl
@@ -3589,6 +3589,42 @@ modify =
.bvstate-exists = Näkyvyystila "__ocs_fmt_0__" on jo olemassa.
.bvstate-last = Ainoaa näkyvyystilaa ei voi poistaa.
.bvstate-needs-bedit = __ocs_fmt_0__: avaa lohko ensin lohkoeditorissa (BEDIT).
+ .visibilitystates-parameter = VISIBILITYSTATES Anna uusi parametri:
+ .visibilitystates-parameter-or = VISIBILITYSTATES Anna uusi parametri tai [__ocs_fmt_0__]:
+ .visibilitystates-state = VISIBILITYSTATES Anna uusi tila parametrille __ocs_fmt_0__:
+ .visibilitystates-state-or = VISIBILITYSTATES Anna uusi tila parametrille __ocs_fmt_0__ tai [__ocs_fmt_1__]:
+ .visibilitystates-action = VISIBILITYSTATES Valitse toiminto [Lisää/Poista/Näytä/Piilota/Valitse tila] :
+ .visibilitystates-add-objects = Lisää objekteja
+ .visibilitystates-remove-objects = Poista objekteja
+ .visibilitystates-make-visible = Näytä objektit
+ .visibilitystates-make-invisible = Piilota objektit
+ .visibilitystates-select-state = Valitse tila
+ .visibilitystates-model-space = VISIBILITYSTATES toimii mallitilassa: avaa BricsCAD-lohkon piirustus.
+ .visibilitystates-unsupported = Näkyvyystiloja ei voi muokata tässä.
+ .visibilitystates-old-format = Näkyvyystilat edellyttävät DWG 2010 -muotoista tai uudempaa piirustusta.
+ .visibilitystates-no-parameter = Tämännimistä näkyvyysparametria ei ole.
+ .visibilitystates-no-state = Tämännimistä näkyvyystilaa ei ole.
+ .visibilitystates-state-exists = Näkyvyystila on jo olemassa.
+ .visibilitystates-cannot-move = Näkyvyystilaa ei voi siirtää pidemmälle.
+ .visibilitystates-bad-name = Anna nimi, jossa on vain kirjaimia, numeroita ja alaviivoja.
+ .visibilitystates-name-taken = Nimi on toisen muuttujan käytössä.
+ .visibilitystates-no-objects = Valitse objekteja muokattavasta tilasta.
+ .visibilitystates-panel-elsewhere = Näkyvyystiloja muokataan lohkon oman piirustuksen mallitilassa.
+ .visibilitystates-panel-unsupported = Tämän piirustuksen näkyvyystiloja ei voi muokata tässä.
+ .visibilitystates-first-state = Ensimmäinen tila
+ .visibilitystates-panel-empty = Tässä piirustuksessa ei ole näkyvyystiloja. Lisää parametri napsauttamalla +.
+ .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ objektia)
+ .visibilitystates-move-up = Siirrä ylös
+ .visibilitystates-move-down = Siirrä alas
+ .visibilitystates-state-objects = Tämän tilan objektit
+ .visibilitystates-new-state = Uusi tila
+ .visibilitystates-add-state = Lisää tila
+ .visibilitystates-back = Takaisin parametreihin
+ .visibilitystates-add-to-state = Lisää objekteja tähän tilaan
+ .visibilitystates-no-objects-yet = Parametri ei vielä ohjaa objekteja. Lisää objekteja tähän tilaan.
+ .visibilitystates-remove-from-parameter = Poista parametrista
+ .visibilitystates-same-everywhere = Sama kaikissa parametrin tiloissa
+ .visibilitystates-same-everywhere-note = Yksi tai useampi objekti näkyy samoin kaikissa tämän parametrin tiloissa.
.bvstate-current = Nykyinen näkyvyystila: __ocs_fmt_0__
.bvhide-select = Valitse piilotettavat objektit:
.bvshow-select = Valitse näytettävät objektit:
diff --git a/locales/fr-FR/opencadstudio.ftl b/locales/fr-FR/opencadstudio.ftl
index f14d31d04f..6aef2f892b 100644
--- a/locales/fr-FR/opencadstudio.ftl
+++ b/locales/fr-FR/opencadstudio.ftl
@@ -3590,6 +3590,42 @@ modify =
.bvstate-exists = L'état de visibilité "__ocs_fmt_0__" existe déjà.
.bvstate-last = Le seul état de visibilité ne peut pas être supprimé.
.bvstate-needs-bedit = __ocs_fmt_0__ : ouvrez d'abord le bloc dans l'éditeur de blocs (BEDIT).
+ .visibilitystates-parameter = VISIBILITYSTATES Entrez un nouveau paramètre :
+ .visibilitystates-parameter-or = VISIBILITYSTATES Entrez un nouveau paramètre ou [__ocs_fmt_0__] :
+ .visibilitystates-state = VISIBILITYSTATES Entrez un nouvel état pour __ocs_fmt_0__ :
+ .visibilitystates-state-or = VISIBILITYSTATES Entrez un nouvel état pour __ocs_fmt_0__ ou [__ocs_fmt_1__] :
+ .visibilitystates-action = VISIBILITYSTATES Choisissez une action [Ajouter/Retirer/Montrer/Cacher/Sélectionner l'état] :
+ .visibilitystates-add-objects = Ajouter des objets
+ .visibilitystates-remove-objects = Retirer des objets
+ .visibilitystates-make-visible = Rendre les objets visibles
+ .visibilitystates-make-invisible = Rendre les objets invisibles
+ .visibilitystates-select-state = Sélectionner l'état
+ .visibilitystates-model-space = VISIBILITYSTATES fonctionne dans l'espace objet : ouvrez le dessin du bloc BricsCAD.
+ .visibilitystates-unsupported = Les états de visibilité ne sont pas modifiables ici.
+ .visibilitystates-old-format = Les états de visibilité nécessitent un dessin au format DWG 2010 ou ultérieur.
+ .visibilitystates-no-parameter = Aucun paramètre de visibilité de ce nom.
+ .visibilitystates-no-state = Aucun état de visibilité de ce nom.
+ .visibilitystates-state-exists = Cet état de visibilité existe déjà.
+ .visibilitystates-cannot-move = L'état de visibilité ne peut pas être déplacé davantage.
+ .visibilitystates-bad-name = Entrez un nom composé de lettres, de chiffres et de traits de soulignement.
+ .visibilitystates-name-taken = Ce nom est utilisé par une autre variable.
+ .visibilitystates-no-objects = Sélectionnez des objets de l'espace en cours de modification.
+ .visibilitystates-panel-elsewhere = Les états de visibilité se modifient dans l'espace objet du dessin propre au bloc.
+ .visibilitystates-panel-unsupported = Les états de visibilité de ce dessin ne sont pas modifiables ici.
+ .visibilitystates-first-state = Premier état
+ .visibilitystates-panel-empty = Ce dessin ne contient aucun état de visibilité. Cliquez sur + pour ajouter un paramètre.
+ .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ objets)
+ .visibilitystates-move-up = Monter
+ .visibilitystates-move-down = Descendre
+ .visibilitystates-state-objects = Objets de cet état
+ .visibilitystates-new-state = Nouvel état
+ .visibilitystates-add-state = Ajouter un état
+ .visibilitystates-back = Retour aux paramètres
+ .visibilitystates-add-to-state = Ajouter des objets à cet état
+ .visibilitystates-no-objects-yet = Le paramètre ne pilote encore aucun objet. Ajoutez des objets à cet état.
+ .visibilitystates-remove-from-parameter = Retirer du paramètre
+ .visibilitystates-same-everywhere = Identique dans tous les états du paramètre
+ .visibilitystates-same-everywhere-note = Un ou plusieurs objets s'affichent de la même façon dans tous les états de ce paramètre.
.bvstate-current = État de visibilité courant : __ocs_fmt_0__
.bvhide-select = Sélectionnez les objets à masquer :
.bvshow-select = Sélectionnez les objets à rendre visibles :
diff --git a/locales/hi-IN/opencadstudio.ftl b/locales/hi-IN/opencadstudio.ftl
index b59595fe61..6ed6cc118b 100644
--- a/locales/hi-IN/opencadstudio.ftl
+++ b/locales/hi-IN/opencadstudio.ftl
@@ -3578,6 +3578,42 @@ modify =
.bvstate-exists = दृश्यता स्थिति "__ocs_fmt_0__" पहले से मौजूद है।
.bvstate-last = एकमात्र दृश्यता स्थिति हटाई नहीं जा सकती।
.bvstate-needs-bedit = __ocs_fmt_0__: पहले ब्लॉक को ब्लॉक एडिटर में खोलें (BEDIT)।
+ .visibilitystates-parameter = VISIBILITYSTATES नया पैरामीटर दर्ज करें:
+ .visibilitystates-parameter-or = VISIBILITYSTATES नया पैरामीटर दर्ज करें या [__ocs_fmt_0__]:
+ .visibilitystates-state = VISIBILITYSTATES __ocs_fmt_0__ के लिए नई स्थिति दर्ज करें:
+ .visibilitystates-state-or = VISIBILITYSTATES __ocs_fmt_0__ के लिए नई स्थिति दर्ज करें या [__ocs_fmt_1__]:
+ .visibilitystates-action = VISIBILITYSTATES क्रिया चुनें [जोड़ें/हटाएँ/दिखाएँ/छिपाएँ/स्थिति चुनें] <जोड़ें>:
+ .visibilitystates-add-objects = ऑब्जेक्ट जोड़ें
+ .visibilitystates-remove-objects = ऑब्जेक्ट हटाएँ
+ .visibilitystates-make-visible = ऑब्जेक्ट दिखाएँ
+ .visibilitystates-make-invisible = ऑब्जेक्ट छिपाएँ
+ .visibilitystates-select-state = स्थिति चुनें
+ .visibilitystates-model-space = VISIBILITYSTATES मॉडल स्पेस में काम करता है: BricsCAD ब्लॉक की ड्रॉइंग खोलें।
+ .visibilitystates-unsupported = यहाँ दृश्यता स्थितियाँ संपादित नहीं की जा सकतीं।
+ .visibilitystates-old-format = दृश्यता स्थितियों के लिए DWG 2010 या बाद के फ़ॉर्मैट की ड्रॉइंग आवश्यक है।
+ .visibilitystates-no-parameter = इस नाम का कोई दृश्यता पैरामीटर नहीं है।
+ .visibilitystates-no-state = इस नाम की कोई दृश्यता स्थिति नहीं है।
+ .visibilitystates-state-exists = यह दृश्यता स्थिति पहले से मौजूद है।
+ .visibilitystates-cannot-move = दृश्यता स्थिति को और आगे नहीं ले जाया जा सकता।
+ .visibilitystates-bad-name = अक्षरों, अंकों और अंडरस्कोर से बना नाम दर्ज करें।
+ .visibilitystates-name-taken = यह नाम किसी अन्य वेरिएबल द्वारा उपयोग किया जा रहा है।
+ .visibilitystates-no-objects = संपादित हो रहे स्पेस के ऑब्जेक्ट चुनें।
+ .visibilitystates-panel-elsewhere = दृश्यता स्थितियाँ ब्लॉक की अपनी ड्रॉइंग के मॉडल स्पेस में संपादित की जाती हैं।
+ .visibilitystates-panel-unsupported = इस ड्रॉइंग की दृश्यता स्थितियाँ यहाँ संपादित नहीं की जा सकतीं।
+ .visibilitystates-first-state = पहली स्थिति
+ .visibilitystates-panel-empty = इस ड्रॉइंग में कोई दृश्यता स्थिति नहीं है। पैरामीटर जोड़ने के लिए + पर क्लिक करें।
+ .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ ऑब्जेक्ट)
+ .visibilitystates-move-up = ऊपर ले जाएँ
+ .visibilitystates-move-down = नीचे ले जाएँ
+ .visibilitystates-state-objects = इस स्थिति के ऑब्जेक्ट
+ .visibilitystates-new-state = नई स्थिति
+ .visibilitystates-add-state = स्थिति जोड़ें
+ .visibilitystates-back = पैरामीटर पर वापस जाएँ
+ .visibilitystates-add-to-state = इस स्थिति में ऑब्जेक्ट जोड़ें
+ .visibilitystates-no-objects-yet = पैरामीटर अभी किसी ऑब्जेक्ट को नियंत्रित नहीं करता। इस स्थिति में ऑब्जेक्ट जोड़ें।
+ .visibilitystates-remove-from-parameter = पैरामीटर से हटाएँ
+ .visibilitystates-same-everywhere = पैरामीटर की हर स्थिति में एक जैसा
+ .visibilitystates-same-everywhere-note = एक या अधिक ऑब्जेक्ट इस पैरामीटर की हर स्थिति में एक जैसे दिखते हैं।
.bvstate-current = वर्तमान दृश्यता स्थिति: __ocs_fmt_0__
.bvhide-select = छिपाने के लिए ऑब्जेक्ट चुनें:
.bvshow-select = दिखाने के लिए ऑब्जेक्ट चुनें:
diff --git a/locales/hu-HU/opencadstudio.ftl b/locales/hu-HU/opencadstudio.ftl
index 9e8ae9db60..adb14f00ae 100644
--- a/locales/hu-HU/opencadstudio.ftl
+++ b/locales/hu-HU/opencadstudio.ftl
@@ -3586,6 +3586,42 @@ modify =
.bvstate-exists = A(z) „__ocs_fmt_0__” láthatósági állapot már létezik.
.bvstate-last = Az egyetlen láthatósági állapot nem törölhető.
.bvstate-needs-bedit = __ocs_fmt_0__: előbb nyissa meg a blokkot a blokkszerkesztőben (BEDIT).
+ .visibilitystates-parameter = VISIBILITYSTATES Adjon meg új paramétert:
+ .visibilitystates-parameter-or = VISIBILITYSTATES Adjon meg új paramétert vagy [__ocs_fmt_0__]:
+ .visibilitystates-state = VISIBILITYSTATES Adjon meg új állapotot a(z) __ocs_fmt_0__ paraméterhez:
+ .visibilitystates-state-or = VISIBILITYSTATES Adjon meg új állapotot a(z) __ocs_fmt_0__ paraméterhez vagy [__ocs_fmt_1__]:
+ .visibilitystates-action = VISIBILITYSTATES Válasszon műveletet [Hozzáadás/Eltávolítás/Megjelenítés/Rejtés/Állapot kiválasztása] :
+ .visibilitystates-add-objects = Objektumok hozzáadása
+ .visibilitystates-remove-objects = Objektumok eltávolítása
+ .visibilitystates-make-visible = Objektumok megjelenítése
+ .visibilitystates-make-invisible = Objektumok elrejtése
+ .visibilitystates-select-state = Állapot kiválasztása
+ .visibilitystates-model-space = A VISIBILITYSTATES modelltérben működik: nyissa meg a BricsCAD-blokk rajzát.
+ .visibilitystates-unsupported = Az itteni láthatósági állapotok nem szerkeszthetők.
+ .visibilitystates-old-format = A láthatósági állapotokhoz DWG 2010 vagy újabb formátumú rajz szükséges.
+ .visibilitystates-no-parameter = Nincs ilyen nevű láthatósági paraméter.
+ .visibilitystates-no-state = Nincs ilyen nevű láthatósági állapot.
+ .visibilitystates-state-exists = Ez a láthatósági állapot már létezik.
+ .visibilitystates-cannot-move = A láthatósági állapot nem mozgatható tovább.
+ .visibilitystates-bad-name = Betűkből, számjegyekből és aláhúzásjelekből álló nevet adjon meg.
+ .visibilitystates-name-taken = Ezt a nevet egy másik változó használja.
+ .visibilitystates-no-objects = A szerkesztett tér objektumait válassza ki.
+ .visibilitystates-panel-elsewhere = A láthatósági állapotok a blokk saját rajzának modellterében szerkeszthetők.
+ .visibilitystates-panel-unsupported = Ennek a rajznak a láthatósági állapotai itt nem szerkeszthetők.
+ .visibilitystates-first-state = Első állapot
+ .visibilitystates-panel-empty = Ebben a rajzban nincsenek láthatósági állapotok. Paraméter hozzáadásához kattintson a + gombra.
+ .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ objektum)
+ .visibilitystates-move-up = Feljebb
+ .visibilitystates-move-down = Lejjebb
+ .visibilitystates-state-objects = Az állapot objektumai
+ .visibilitystates-new-state = Új állapot
+ .visibilitystates-add-state = Állapot hozzáadása
+ .visibilitystates-back = Vissza a paraméterekhez
+ .visibilitystates-add-to-state = Objektumok hozzáadása ehhez az állapothoz
+ .visibilitystates-no-objects-yet = A paraméter még nem vezérel objektumokat. Adjon objektumokat ehhez az állapothoz.
+ .visibilitystates-remove-from-parameter = Eltávolítás a paraméterből
+ .visibilitystates-same-everywhere = A paraméter minden állapotában azonos
+ .visibilitystates-same-everywhere-note = Egy vagy több objektum a paraméter minden állapotában azonosan jelenik meg.
.bvstate-current = Aktuális láthatósági állapot: __ocs_fmt_0__
.bvhide-select = Jelölje ki az elrejtendő objektumokat:
.bvshow-select = Jelölje ki a megjelenítendő objektumokat:
diff --git a/locales/it-IT/opencadstudio.ftl b/locales/it-IT/opencadstudio.ftl
index 699ef16044..66021a85e2 100644
--- a/locales/it-IT/opencadstudio.ftl
+++ b/locales/it-IT/opencadstudio.ftl
@@ -3589,6 +3589,42 @@ modify =
.bvstate-exists = Lo stato di visibilità "__ocs_fmt_0__" esiste già.
.bvstate-last = L'unico stato di visibilità non può essere eliminato.
.bvstate-needs-bedit = __ocs_fmt_0__: aprire prima il blocco nell'Editor blocchi (BEDIT).
+ .visibilitystates-parameter = VISIBILITYSTATES Immettere un nuovo parametro:
+ .visibilitystates-parameter-or = VISIBILITYSTATES Immettere un nuovo parametro o [__ocs_fmt_0__]:
+ .visibilitystates-state = VISIBILITYSTATES Immettere un nuovo stato per __ocs_fmt_0__:
+ .visibilitystates-state-or = VISIBILITYSTATES Immettere un nuovo stato per __ocs_fmt_0__ o [__ocs_fmt_1__]:
+ .visibilitystates-action = VISIBILITYSTATES Selezionare un'azione [Aggiungi/Rimuovi/Mostra/Nascondi/Seleziona stato] :
+ .visibilitystates-add-objects = Aggiungi oggetti
+ .visibilitystates-remove-objects = Rimuovi oggetti
+ .visibilitystates-make-visible = Rendi visibili gli oggetti
+ .visibilitystates-make-invisible = Rendi invisibili gli oggetti
+ .visibilitystates-select-state = Seleziona stato
+ .visibilitystates-model-space = VISIBILITYSTATES funziona nello spazio modello: aprire il disegno del blocco BricsCAD.
+ .visibilitystates-unsupported = Gli stati di visibilità qui non sono modificabili.
+ .visibilitystates-old-format = Gli stati di visibilità richiedono un disegno in formato DWG 2010 o successivo.
+ .visibilitystates-no-parameter = Nessun parametro di visibilità con questo nome.
+ .visibilitystates-no-state = Nessuno stato di visibilità con questo nome.
+ .visibilitystates-state-exists = Questo stato di visibilità esiste già.
+ .visibilitystates-cannot-move = Lo stato di visibilità non può essere spostato oltre.
+ .visibilitystates-bad-name = Immettere un nome composto da lettere, cifre e caratteri di sottolineatura.
+ .visibilitystates-name-taken = Questo nome è usato da un'altra variabile.
+ .visibilitystates-no-objects = Selezionare oggetti dello spazio in modifica.
+ .visibilitystates-panel-elsewhere = Gli stati di visibilità si modificano nello spazio modello del disegno del blocco stesso.
+ .visibilitystates-panel-unsupported = Gli stati di visibilità di questo disegno non sono modificabili qui.
+ .visibilitystates-first-state = Primo stato
+ .visibilitystates-panel-empty = In questo disegno non ci sono stati di visibilità. Fare clic su + per aggiungere un parametro.
+ .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ oggetti)
+ .visibilitystates-move-up = Sposta su
+ .visibilitystates-move-down = Sposta giù
+ .visibilitystates-state-objects = Oggetti di questo stato
+ .visibilitystates-new-state = Nuovo stato
+ .visibilitystates-add-state = Aggiungi stato
+ .visibilitystates-back = Torna ai parametri
+ .visibilitystates-add-to-state = Aggiungi oggetti a questo stato
+ .visibilitystates-no-objects-yet = Il parametro non controlla ancora alcun oggetto. Aggiungere oggetti a questo stato.
+ .visibilitystates-remove-from-parameter = Rimuovi dal parametro
+ .visibilitystates-same-everywhere = Uguale in tutti gli stati del parametro
+ .visibilitystates-same-everywhere-note = Uno o più oggetti appaiono uguali in tutti gli stati di questo parametro.
.bvstate-current = Stato di visibilità corrente: __ocs_fmt_0__
.bvhide-select = Selezionare gli oggetti da nascondere:
.bvshow-select = Selezionare gli oggetti da rendere visibili:
diff --git a/locales/ja-JP/opencadstudio.ftl b/locales/ja-JP/opencadstudio.ftl
index 3aadcf6bd3..95601f52ba 100644
--- a/locales/ja-JP/opencadstudio.ftl
+++ b/locales/ja-JP/opencadstudio.ftl
@@ -3580,6 +3580,42 @@ modify =
.bvstate-exists = 可視性状態「__ocs_fmt_0__」は既に存在します。
.bvstate-last = 唯一の可視性状態は削除できません。
.bvstate-needs-bedit = __ocs_fmt_0__: 先にブロック エディタでブロックを開いてください (BEDIT)。
+ .visibilitystates-parameter = VISIBILITYSTATES 新しいパラメーターを入力:
+ .visibilitystates-parameter-or = VISIBILITYSTATES 新しいパラメーターを入力 または [__ocs_fmt_0__]:
+ .visibilitystates-state = VISIBILITYSTATES __ocs_fmt_0__ の新しい状態を入力:
+ .visibilitystates-state-or = VISIBILITYSTATES __ocs_fmt_0__ の新しい状態を入力 または [__ocs_fmt_1__]:
+ .visibilitystates-action = VISIBILITYSTATES 操作を選択 [追加/除外/表示/非表示/状態を選択] <追加>:
+ .visibilitystates-add-objects = オブジェクトを追加
+ .visibilitystates-remove-objects = オブジェクトを除外
+ .visibilitystates-make-visible = オブジェクトを表示
+ .visibilitystates-make-invisible = オブジェクトを非表示
+ .visibilitystates-select-state = 状態を選択
+ .visibilitystates-model-space = VISIBILITYSTATES はモデル空間で動作します: BricsCAD ブロックの図面を開いてください。
+ .visibilitystates-unsupported = ここでは可視性状態を編集できません。
+ .visibilitystates-old-format = 可視性状態には DWG 2010 以降の形式の図面が必要です。
+ .visibilitystates-no-parameter = その名前の可視性パラメーターはありません。
+ .visibilitystates-no-state = その名前の可視性状態はありません。
+ .visibilitystates-state-exists = その可視性状態は既に存在します。
+ .visibilitystates-cannot-move = 可視性状態をこれ以上移動できません。
+ .visibilitystates-bad-name = 文字、数字、アンダースコアで構成される名前を入力してください。
+ .visibilitystates-name-taken = その名前は別の変数で使用されています。
+ .visibilitystates-no-objects = 編集中の空間のオブジェクトを選択してください。
+ .visibilitystates-panel-elsewhere = 可視性状態はブロック自体の図面のモデル空間で編集します。
+ .visibilitystates-panel-unsupported = この図面の可視性状態はここでは編集できません。
+ .visibilitystates-first-state = 最初の状態
+ .visibilitystates-panel-empty = この図面には可視性状態がありません。+ をクリックしてパラメーターを追加してください。
+ .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ 個のオブジェクト)
+ .visibilitystates-move-up = 上へ移動
+ .visibilitystates-move-down = 下へ移動
+ .visibilitystates-state-objects = この状態のオブジェクト
+ .visibilitystates-new-state = 新しい状態
+ .visibilitystates-add-state = 状態を追加
+ .visibilitystates-back = パラメーターに戻る
+ .visibilitystates-add-to-state = この状態にオブジェクトを追加
+ .visibilitystates-no-objects-yet = このパラメーターはまだオブジェクトを制御していません。この状態にオブジェクトを追加してください。
+ .visibilitystates-remove-from-parameter = パラメーターから除外
+ .visibilitystates-same-everywhere = パラメーターのすべての状態で同じ表示
+ .visibilitystates-same-everywhere-note = 1 つ以上のオブジェクトが、このパラメーターのすべての状態で同じように表示されます。
.bvstate-current = 現在の可視性状態: __ocs_fmt_0__
.bvhide-select = 非表示にするオブジェクトを選択:
.bvshow-select = 表示するオブジェクトを選択:
diff --git a/locales/ko-KR/opencadstudio.ftl b/locales/ko-KR/opencadstudio.ftl
index f07d3a936f..d2270baac6 100644
--- a/locales/ko-KR/opencadstudio.ftl
+++ b/locales/ko-KR/opencadstudio.ftl
@@ -3589,6 +3589,42 @@ modify =
.bvstate-exists = 가시성 상태 "__ocs_fmt_0__"이(가) 이미 있습니다.
.bvstate-last = 유일한 가시성 상태는 삭제할 수 없습니다.
.bvstate-needs-bedit = __ocs_fmt_0__: 먼저 블록 편집기에서 블록을 여십시오(BEDIT).
+ .visibilitystates-parameter = VISIBILITYSTATES 새 매개변수 입력:
+ .visibilitystates-parameter-or = VISIBILITYSTATES 새 매개변수 입력 또는 [__ocs_fmt_0__]:
+ .visibilitystates-state = VISIBILITYSTATES __ocs_fmt_0__의 새 상태 입력:
+ .visibilitystates-state-or = VISIBILITYSTATES __ocs_fmt_0__의 새 상태 입력 또는 [__ocs_fmt_1__]:
+ .visibilitystates-action = VISIBILITYSTATES 작업 선택 [추가/제거/표시/숨기기/상태 선택] <추가>:
+ .visibilitystates-add-objects = 객체 추가
+ .visibilitystates-remove-objects = 객체 제거
+ .visibilitystates-make-visible = 객체 표시
+ .visibilitystates-make-invisible = 객체 숨기기
+ .visibilitystates-select-state = 상태 선택
+ .visibilitystates-model-space = VISIBILITYSTATES는 모형 공간에서 작동합니다: BricsCAD 블록의 도면을 여십시오.
+ .visibilitystates-unsupported = 여기서는 가시성 상태를 편집할 수 없습니다.
+ .visibilitystates-old-format = 가시성 상태에는 DWG 2010 이상 형식의 도면이 필요합니다.
+ .visibilitystates-no-parameter = 해당 이름의 가시성 매개변수가 없습니다.
+ .visibilitystates-no-state = 해당 이름의 가시성 상태가 없습니다.
+ .visibilitystates-state-exists = 해당 가시성 상태가 이미 있습니다.
+ .visibilitystates-cannot-move = 가시성 상태를 더 이상 이동할 수 없습니다.
+ .visibilitystates-bad-name = 문자, 숫자, 밑줄로 된 이름을 입력하십시오.
+ .visibilitystates-name-taken = 다른 변수가 이 이름을 사용하고 있습니다.
+ .visibilitystates-no-objects = 편집 중인 공간의 객체를 선택하십시오.
+ .visibilitystates-panel-elsewhere = 가시성 상태는 블록 자체 도면의 모형 공간에서 편집합니다.
+ .visibilitystates-panel-unsupported = 이 도면의 가시성 상태는 여기서 편집할 수 없습니다.
+ .visibilitystates-first-state = 첫 번째 상태
+ .visibilitystates-panel-empty = 이 도면에는 가시성 상태가 없습니다. +를 클릭하여 매개변수를 추가하십시오.
+ .visibilitystates-parameter-objects = __ocs_fmt_0__ (객체 __ocs_fmt_1__개)
+ .visibilitystates-move-up = 위로 이동
+ .visibilitystates-move-down = 아래로 이동
+ .visibilitystates-state-objects = 이 상태의 객체
+ .visibilitystates-new-state = 새 상태
+ .visibilitystates-add-state = 상태 추가
+ .visibilitystates-back = 매개변수로 돌아가기
+ .visibilitystates-add-to-state = 이 상태에 객체 추가
+ .visibilitystates-no-objects-yet = 매개변수가 아직 객체를 제어하지 않습니다. 이 상태에 객체를 추가하십시오.
+ .visibilitystates-remove-from-parameter = 매개변수에서 제거
+ .visibilitystates-same-everywhere = 매개변수의 모든 상태에서 동일하게 표시
+ .visibilitystates-same-everywhere-note = 하나 이상의 객체가 이 매개변수의 모든 상태에서 동일하게 표시됩니다.
.bvstate-current = 현재 가시성 상태: __ocs_fmt_0__
.bvhide-select = 숨길 객체 선택:
.bvshow-select = 표시할 객체 선택:
diff --git a/locales/lo-LA/opencadstudio.ftl b/locales/lo-LA/opencadstudio.ftl
index 691ad84891..ca5302c796 100644
--- a/locales/lo-LA/opencadstudio.ftl
+++ b/locales/lo-LA/opencadstudio.ftl
@@ -3591,6 +3591,42 @@ modify =
.bvstate-exists = ສະຖານະການເບິ່ງເຫັນ "__ocs_fmt_0__" ມີຢູ່ແລ້ວ.
.bvstate-last = ບໍ່ສາມາດລຶບສະຖານະການເບິ່ງເຫັນດຽວໄດ້.
.bvstate-needs-bedit = __ocs_fmt_0__: ເປີດບລັອກໃນຕົວແກ້ໄຂບລັອກກ່ອນ (BEDIT).
+ .visibilitystates-parameter = VISIBILITYSTATES ປ້ອນພາຣາມິເຕີໃໝ່:
+ .visibilitystates-parameter-or = VISIBILITYSTATES ປ້ອນພາຣາມິເຕີໃໝ່ ຫຼື [__ocs_fmt_0__]:
+ .visibilitystates-state = VISIBILITYSTATES ປ້ອນສະຖານະໃໝ່ສຳລັບ __ocs_fmt_0__:
+ .visibilitystates-state-or = VISIBILITYSTATES ປ້ອນສະຖານະໃໝ່ສຳລັບ __ocs_fmt_0__ ຫຼື [__ocs_fmt_1__]:
+ .visibilitystates-action = VISIBILITYSTATES ເລືອກການກະທຳ [ເພີ່ມ/ເອົາອອກ/ສະແດງ/ເຊື່ອງ/ເລືອກສະຖານະ] <ເພີ່ມ>:
+ .visibilitystates-add-objects = ເພີ່ມວັດຖຸ
+ .visibilitystates-remove-objects = ເອົາວັດຖຸອອກ
+ .visibilitystates-make-visible = ສະແດງວັດຖຸ
+ .visibilitystates-make-invisible = ເຊື່ອງວັດຖຸ
+ .visibilitystates-select-state = ເລືອກສະຖານະ
+ .visibilitystates-model-space = VISIBILITYSTATES ເຮັດວຽກໃນພື້ນທີ່ໂມເດວ: ເປີດແບບແຕ້ມຂອງບລັອກ BricsCAD.
+ .visibilitystates-unsupported = ບໍ່ສາມາດແກ້ໄຂສະຖານະການເບິ່ງເຫັນຢູ່ນີ້ໄດ້.
+ .visibilitystates-old-format = ສະຖານະການເບິ່ງເຫັນຕ້ອງການແບບແຕ້ມໃນຮູບແບບ DWG 2010 ຫຼືໃໝ່ກວ່າ.
+ .visibilitystates-no-parameter = ບໍ່ມີພາຣາມິເຕີການເບິ່ງເຫັນທີ່ມີຊື່ນີ້.
+ .visibilitystates-no-state = ບໍ່ມີສະຖານະການເບິ່ງເຫັນທີ່ມີຊື່ນີ້.
+ .visibilitystates-state-exists = ສະຖານະການເບິ່ງເຫັນນີ້ມີຢູ່ແລ້ວ.
+ .visibilitystates-cannot-move = ບໍ່ສາມາດຍ້າຍສະຖານະການເບິ່ງເຫັນໄປຕື່ມໄດ້.
+ .visibilitystates-bad-name = ປ້ອນຊື່ທີ່ປະກອບດ້ວຍຕົວອັກສອນ, ຕົວເລກ ແລະ ຂີດກ້ອງ.
+ .visibilitystates-name-taken = ຊື່ນີ້ຖືກໃຊ້ໂດຍຕົວແປອື່ນແລ້ວ.
+ .visibilitystates-no-objects = ເລືອກວັດຖຸຂອງພື້ນທີ່ທີ່ກຳລັງແກ້ໄຂ.
+ .visibilitystates-panel-elsewhere = ສະຖານະການເບິ່ງເຫັນຖືກແກ້ໄຂໃນພື້ນທີ່ໂມເດວຂອງແບບແຕ້ມຂອງບລັອກເອງ.
+ .visibilitystates-panel-unsupported = ບໍ່ສາມາດແກ້ໄຂສະຖານະການເບິ່ງເຫັນຂອງແບບແຕ້ມນີ້ຢູ່ນີ້ໄດ້.
+ .visibilitystates-first-state = ສະຖານະທຳອິດ
+ .visibilitystates-panel-empty = ບໍ່ມີສະຖານະການເບິ່ງເຫັນໃນແບບແຕ້ມນີ້. ຄລິກ + ເພື່ອເພີ່ມພາຣາມິເຕີ.
+ .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ ວັດຖຸ)
+ .visibilitystates-move-up = ຍ້າຍຂຶ້ນ
+ .visibilitystates-move-down = ຍ້າຍລົງ
+ .visibilitystates-state-objects = ວັດຖຸຂອງສະຖານະນີ້
+ .visibilitystates-new-state = ສະຖານະໃໝ່
+ .visibilitystates-add-state = ເພີ່ມສະຖານະ
+ .visibilitystates-back = ກັບຄືນຫາພາຣາມິເຕີ
+ .visibilitystates-add-to-state = ເພີ່ມວັດຖຸໃສ່ສະຖານະນີ້
+ .visibilitystates-no-objects-yet = ພາຣາມິເຕີຍັງບໍ່ໄດ້ຄວບຄຸມວັດຖຸໃດເທື່ອ. ເພີ່ມວັດຖຸໃສ່ສະຖານະນີ້.
+ .visibilitystates-remove-from-parameter = ເອົາອອກຈາກພາຣາມິເຕີ
+ .visibilitystates-same-everywhere = ສະແດງຄືກັນໃນທຸກສະຖານະຂອງພາຣາມິເຕີ
+ .visibilitystates-same-everywhere-note = ວັດຖຸໜຶ່ງ ຫຼື ຫຼາຍອັນສະແດງຄືກັນໃນທຸກສະຖານະຂອງພາຣາມິເຕີນີ້.
.bvstate-current = ສະຖານະການເບິ່ງເຫັນປັດຈຸບັນ: __ocs_fmt_0__
.bvhide-select = ເລືອກວັດຖຸທີ່ຈະເຊື່ອງ:
.bvshow-select = ເລືອກວັດຖຸທີ່ຈະສະແດງ:
diff --git a/locales/nl-NL/opencadstudio.ftl b/locales/nl-NL/opencadstudio.ftl
index c397e3fb38..26e4e165f3 100644
--- a/locales/nl-NL/opencadstudio.ftl
+++ b/locales/nl-NL/opencadstudio.ftl
@@ -3590,6 +3590,42 @@ modify =
.bvstate-exists = Zichtbaarheidsstatus "__ocs_fmt_0__" bestaat al.
.bvstate-last = De enige zichtbaarheidsstatus kan niet worden verwijderd.
.bvstate-needs-bedit = __ocs_fmt_0__: open het blok eerst in de blokeditor (BEDIT).
+ .visibilitystates-parameter = VISIBILITYSTATES Geef een nieuwe parameter:
+ .visibilitystates-parameter-or = VISIBILITYSTATES Geef een nieuwe parameter of [__ocs_fmt_0__]:
+ .visibilitystates-state = VISIBILITYSTATES Geef een nieuwe status voor __ocs_fmt_0__:
+ .visibilitystates-state-or = VISIBILITYSTATES Geef een nieuwe status voor __ocs_fmt_0__ of [__ocs_fmt_1__]:
+ .visibilitystates-action = VISIBILITYSTATES Kies een actie [Toevoegen/Verwijderen/Zichtbaar maken/Onzichtbaar maken/Status kiezen] :
+ .visibilitystates-add-objects = Objecten toevoegen
+ .visibilitystates-remove-objects = Objecten verwijderen
+ .visibilitystates-make-visible = Objecten zichtbaar maken
+ .visibilitystates-make-invisible = Objecten onzichtbaar maken
+ .visibilitystates-select-state = Status kiezen
+ .visibilitystates-model-space = VISIBILITYSTATES werkt in de modelruimte: open de tekening van het BricsCAD-blok.
+ .visibilitystates-unsupported = De zichtbaarheidsstatussen hier kunnen niet worden bewerkt.
+ .visibilitystates-old-format = Zichtbaarheidsstatussen vereisen een tekening in DWG 2010-indeling of nieuwer.
+ .visibilitystates-no-parameter = Geen zichtbaarheidsparameter met die naam.
+ .visibilitystates-no-state = Geen zichtbaarheidsstatus met die naam.
+ .visibilitystates-state-exists = Die zichtbaarheidsstatus bestaat al.
+ .visibilitystates-cannot-move = De zichtbaarheidsstatus kan niet verder worden verplaatst.
+ .visibilitystates-bad-name = Geef een naam van letters, cijfers en onderstrepingstekens.
+ .visibilitystates-name-taken = Die naam wordt door een andere variabele gebruikt.
+ .visibilitystates-no-objects = Selecteer objecten van de ruimte die wordt bewerkt.
+ .visibilitystates-panel-elsewhere = Zichtbaarheidsstatussen worden bewerkt in de modelruimte van de eigen tekening van het blok.
+ .visibilitystates-panel-unsupported = De zichtbaarheidsstatussen van deze tekening kunnen hier niet worden bewerkt.
+ .visibilitystates-first-state = Eerste status
+ .visibilitystates-panel-empty = Deze tekening bevat geen zichtbaarheidsstatussen. Klik op + om een parameter toe te voegen.
+ .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ objecten)
+ .visibilitystates-move-up = Omhoog
+ .visibilitystates-move-down = Omlaag
+ .visibilitystates-state-objects = Objecten van deze status
+ .visibilitystates-new-state = Nieuwe status
+ .visibilitystates-add-state = Status toevoegen
+ .visibilitystates-back = Terug naar de parameters
+ .visibilitystates-add-to-state = Objecten aan deze status toevoegen
+ .visibilitystates-no-objects-yet = De parameter stuurt nog geen objecten aan. Voeg objecten aan deze status toe.
+ .visibilitystates-remove-from-parameter = Uit parameter verwijderen
+ .visibilitystates-same-everywhere = In elke status van de parameter hetzelfde
+ .visibilitystates-same-everywhere-note = Een of meer objecten worden in elke status van deze parameter hetzelfde weergegeven.
.bvstate-current = Huidige zichtbaarheidsstatus: __ocs_fmt_0__
.bvhide-select = Selecteer te verbergen objecten:
.bvshow-select = Selecteer zichtbaar te maken objecten:
diff --git a/locales/pl-PL/opencadstudio.ftl b/locales/pl-PL/opencadstudio.ftl
index 90dd85a317..7292d90b55 100644
--- a/locales/pl-PL/opencadstudio.ftl
+++ b/locales/pl-PL/opencadstudio.ftl
@@ -3589,6 +3589,42 @@ modify =
.bvstate-exists = Stan widoczności "__ocs_fmt_0__" już istnieje.
.bvstate-last = Nie można usunąć jedynego stanu widoczności.
.bvstate-needs-bedit = __ocs_fmt_0__: najpierw otwórz blok w edytorze bloków (BEDIT).
+ .visibilitystates-parameter = VISIBILITYSTATES Podaj nowy parametr:
+ .visibilitystates-parameter-or = VISIBILITYSTATES Podaj nowy parametr lub [__ocs_fmt_0__]:
+ .visibilitystates-state = VISIBILITYSTATES Podaj nowy stan dla __ocs_fmt_0__:
+ .visibilitystates-state-or = VISIBILITYSTATES Podaj nowy stan dla __ocs_fmt_0__ lub [__ocs_fmt_1__]:
+ .visibilitystates-action = VISIBILITYSTATES Wybierz akcję [Dodaj/Usuń/Pokaż/Ukryj/Wybierz stan] :
+ .visibilitystates-add-objects = Dodaj obiekty
+ .visibilitystates-remove-objects = Usuń obiekty
+ .visibilitystates-make-visible = Pokaż obiekty
+ .visibilitystates-make-invisible = Ukryj obiekty
+ .visibilitystates-select-state = Wybierz stan
+ .visibilitystates-model-space = VISIBILITYSTATES działa w obszarze modelu: otwórz rysunek bloku BricsCAD.
+ .visibilitystates-unsupported = Stanów widoczności nie można tu edytować.
+ .visibilitystates-old-format = Stany widoczności wymagają rysunku w formacie DWG 2010 lub nowszym.
+ .visibilitystates-no-parameter = Brak parametru widoczności o tej nazwie.
+ .visibilitystates-no-state = Brak stanu widoczności o tej nazwie.
+ .visibilitystates-state-exists = Ten stan widoczności już istnieje.
+ .visibilitystates-cannot-move = Stanu widoczności nie można przesunąć dalej.
+ .visibilitystates-bad-name = Podaj nazwę złożoną z liter, cyfr i podkreśleń.
+ .visibilitystates-name-taken = Ta nazwa jest używana przez inną zmienną.
+ .visibilitystates-no-objects = Wybierz obiekty z edytowanego obszaru.
+ .visibilitystates-panel-elsewhere = Stany widoczności edytuje się w obszarze modelu własnego rysunku bloku.
+ .visibilitystates-panel-unsupported = Stanów widoczności tego rysunku nie można tu edytować.
+ .visibilitystates-first-state = Pierwszy stan
+ .visibilitystates-panel-empty = Ten rysunek nie zawiera stanów widoczności. Kliknij +, aby dodać parametr.
+ .visibilitystates-parameter-objects = __ocs_fmt_0__ (obiekty: __ocs_fmt_1__)
+ .visibilitystates-move-up = Przenieś w górę
+ .visibilitystates-move-down = Przenieś w dół
+ .visibilitystates-state-objects = Obiekty tego stanu
+ .visibilitystates-new-state = Nowy stan
+ .visibilitystates-add-state = Dodaj stan
+ .visibilitystates-back = Powrót do parametrów
+ .visibilitystates-add-to-state = Dodaj obiekty do tego stanu
+ .visibilitystates-no-objects-yet = Parametr nie steruje jeszcze żadnymi obiektami. Dodaj obiekty do tego stanu.
+ .visibilitystates-remove-from-parameter = Usuń z parametru
+ .visibilitystates-same-everywhere = Tak samo we wszystkich stanach parametru
+ .visibilitystates-same-everywhere-note = Co najmniej jeden obiekt wygląda tak samo we wszystkich stanach tego parametru.
.bvstate-current = Bieżący stan widoczności: __ocs_fmt_0__
.bvhide-select = Wybierz obiekty do ukrycia:
.bvshow-select = Wybierz obiekty do pokazania:
diff --git a/locales/pt-BR/opencadstudio.ftl b/locales/pt-BR/opencadstudio.ftl
index f2392c79a1..1c5da5dfbe 100644
--- a/locales/pt-BR/opencadstudio.ftl
+++ b/locales/pt-BR/opencadstudio.ftl
@@ -3590,6 +3590,42 @@ modify =
.bvstate-exists = O estado de visibilidade "__ocs_fmt_0__" já existe.
.bvstate-last = O único estado de visibilidade não pode ser excluído.
.bvstate-needs-bedit = __ocs_fmt_0__: abra primeiro o bloco no Editor de blocos (BEDIT).
+ .visibilitystates-parameter = VISIBILITYSTATES Digite um novo parâmetro:
+ .visibilitystates-parameter-or = VISIBILITYSTATES Digite um novo parâmetro ou [__ocs_fmt_0__]:
+ .visibilitystates-state = VISIBILITYSTATES Digite um novo estado para __ocs_fmt_0__:
+ .visibilitystates-state-or = VISIBILITYSTATES Digite um novo estado para __ocs_fmt_0__ ou [__ocs_fmt_1__]:
+ .visibilitystates-action = VISIBILITYSTATES Selecione uma ação [Adicionar/Remover/Mostrar/Ocultar/Selecionar estado] :
+ .visibilitystates-add-objects = Adicionar objetos
+ .visibilitystates-remove-objects = Remover objetos
+ .visibilitystates-make-visible = Tornar objetos visíveis
+ .visibilitystates-make-invisible = Tornar objetos invisíveis
+ .visibilitystates-select-state = Selecionar estado
+ .visibilitystates-model-space = VISIBILITYSTATES funciona no espaço do modelo: abra o desenho do bloco BricsCAD.
+ .visibilitystates-unsupported = Os estados de visibilidade aqui não podem ser editados.
+ .visibilitystates-old-format = Os estados de visibilidade exigem um desenho no formato DWG 2010 ou posterior.
+ .visibilitystates-no-parameter = Nenhum parâmetro de visibilidade com esse nome.
+ .visibilitystates-no-state = Nenhum estado de visibilidade com esse nome.
+ .visibilitystates-state-exists = Esse estado de visibilidade já existe.
+ .visibilitystates-cannot-move = O estado de visibilidade não pode ser movido além disso.
+ .visibilitystates-bad-name = Digite um nome com letras, dígitos e sublinhados.
+ .visibilitystates-name-taken = Esse nome é usado por outra variável.
+ .visibilitystates-no-objects = Selecione objetos do espaço em edição.
+ .visibilitystates-panel-elsewhere = Os estados de visibilidade são editados no espaço do modelo do próprio desenho do bloco.
+ .visibilitystates-panel-unsupported = Os estados de visibilidade deste desenho não podem ser editados aqui.
+ .visibilitystates-first-state = Primeiro estado
+ .visibilitystates-panel-empty = Não há estados de visibilidade neste desenho. Clique em + para adicionar um parâmetro.
+ .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ objetos)
+ .visibilitystates-move-up = Mover para cima
+ .visibilitystates-move-down = Mover para baixo
+ .visibilitystates-state-objects = Objetos deste estado
+ .visibilitystates-new-state = Novo estado
+ .visibilitystates-add-state = Adicionar estado
+ .visibilitystates-back = Voltar aos parâmetros
+ .visibilitystates-add-to-state = Adicionar objetos a este estado
+ .visibilitystates-no-objects-yet = O parâmetro ainda não controla nenhum objeto. Adicione objetos a este estado.
+ .visibilitystates-remove-from-parameter = Remover do parâmetro
+ .visibilitystates-same-everywhere = Igual em todos os estados do parâmetro
+ .visibilitystates-same-everywhere-note = Um ou mais objetos aparecem iguais em todos os estados deste parâmetro.
.bvstate-current = Estado de visibilidade atual: __ocs_fmt_0__
.bvhide-select = Selecione os objetos a ocultar:
.bvshow-select = Selecione os objetos a tornar visíveis:
diff --git a/locales/ru-RU/opencadstudio.ftl b/locales/ru-RU/opencadstudio.ftl
index fd54c89bae..e2578efdb8 100644
--- a/locales/ru-RU/opencadstudio.ftl
+++ b/locales/ru-RU/opencadstudio.ftl
@@ -3593,6 +3593,42 @@ modify =
.bvstate-exists = Состояние видимости "__ocs_fmt_0__" уже существует.
.bvstate-last = Единственное состояние видимости нельзя удалить.
.bvstate-needs-bedit = __ocs_fmt_0__: сначала откройте блок в редакторе блоков (BEDIT).
+ .visibilitystates-parameter = VISIBILITYSTATES Введите новый параметр:
+ .visibilitystates-parameter-or = VISIBILITYSTATES Введите новый параметр или [__ocs_fmt_0__]:
+ .visibilitystates-state = VISIBILITYSTATES Введите новое состояние для __ocs_fmt_0__:
+ .visibilitystates-state-or = VISIBILITYSTATES Введите новое состояние для __ocs_fmt_0__ или [__ocs_fmt_1__]:
+ .visibilitystates-action = VISIBILITYSTATES Выберите действие [Добавить/Убрать/Показать/Скрыть/Выбрать состояние] <Добавить>:
+ .visibilitystates-add-objects = Добавить объекты
+ .visibilitystates-remove-objects = Убрать объекты
+ .visibilitystates-make-visible = Сделать объекты видимыми
+ .visibilitystates-make-invisible = Сделать объекты невидимыми
+ .visibilitystates-select-state = Выбрать состояние
+ .visibilitystates-model-space = VISIBILITYSTATES работает в пространстве модели: откройте чертёж блока BricsCAD.
+ .visibilitystates-unsupported = Здесь нельзя редактировать состояния видимости.
+ .visibilitystates-old-format = Для состояний видимости нужен чертёж в формате DWG 2010 или новее.
+ .visibilitystates-no-parameter = Нет параметра видимости с таким именем.
+ .visibilitystates-no-state = Нет состояния видимости с таким именем.
+ .visibilitystates-state-exists = Такое состояние видимости уже существует.
+ .visibilitystates-cannot-move = Состояние видимости нельзя переместить дальше.
+ .visibilitystates-bad-name = Введите имя из букв, цифр и символов подчёркивания.
+ .visibilitystates-name-taken = Это имя используется другой переменной.
+ .visibilitystates-no-objects = Выберите объекты редактируемого пространства.
+ .visibilitystates-panel-elsewhere = Состояния видимости редактируются в пространстве модели собственного чертежа блока.
+ .visibilitystates-panel-unsupported = Состояния видимости этого чертежа нельзя редактировать здесь.
+ .visibilitystates-first-state = Первое состояние
+ .visibilitystates-panel-empty = В этом чертеже нет состояний видимости. Нажмите +, чтобы добавить параметр.
+ .visibilitystates-parameter-objects = __ocs_fmt_0__ (объектов: __ocs_fmt_1__)
+ .visibilitystates-move-up = Переместить вверх
+ .visibilitystates-move-down = Переместить вниз
+ .visibilitystates-state-objects = Объекты этого состояния
+ .visibilitystates-new-state = Новое состояние
+ .visibilitystates-add-state = Добавить состояние
+ .visibilitystates-back = Назад к параметрам
+ .visibilitystates-add-to-state = Добавить объекты в это состояние
+ .visibilitystates-no-objects-yet = Параметр пока не управляет ни одним объектом. Добавьте объекты в это состояние.
+ .visibilitystates-remove-from-parameter = Убрать из параметра
+ .visibilitystates-same-everywhere = Одинаково во всех состояниях параметра
+ .visibilitystates-same-everywhere-note = Один или несколько объектов выглядят одинаково во всех состояниях этого параметра.
.bvstate-current = Текущее состояние видимости: __ocs_fmt_0__
.bvhide-select = Выберите объекты, которые нужно скрыть:
.bvshow-select = Выберите объекты, которые нужно показать:
diff --git a/locales/tr-TR/opencadstudio.ftl b/locales/tr-TR/opencadstudio.ftl
index 05e045862b..e41393994c 100644
--- a/locales/tr-TR/opencadstudio.ftl
+++ b/locales/tr-TR/opencadstudio.ftl
@@ -3572,6 +3572,42 @@ modify =
.bvstate-exists = "__ocs_fmt_0__" görünürlük durumu zaten var.
.bvstate-last = Tek görünürlük durumu silinemez.
.bvstate-needs-bedit = __ocs_fmt_0__: önce bloğu Blok Düzenleyici'de açın (BEDIT).
+ .visibilitystates-parameter = VISIBILITYSTATES Yeni bir parametre girin:
+ .visibilitystates-parameter-or = VISIBILITYSTATES Yeni bir parametre girin veya [__ocs_fmt_0__]:
+ .visibilitystates-state = VISIBILITYSTATES __ocs_fmt_0__ için yeni bir durum girin:
+ .visibilitystates-state-or = VISIBILITYSTATES __ocs_fmt_0__ için yeni bir durum girin veya [__ocs_fmt_1__]:
+ .visibilitystates-action = VISIBILITYSTATES Bir eylem seçin [Ekle/Çıkar/Göster/Gizle/Durum seç] :
+ .visibilitystates-add-objects = Nesne ekle
+ .visibilitystates-remove-objects = Nesne çıkar
+ .visibilitystates-make-visible = Nesneleri göster
+ .visibilitystates-make-invisible = Nesneleri gizle
+ .visibilitystates-select-state = Durum seç
+ .visibilitystates-model-space = VISIBILITYSTATES model alanında çalışır: BricsCAD bloğunun çizimini açın.
+ .visibilitystates-unsupported = Buradaki görünürlük durumları düzenlenemez.
+ .visibilitystates-old-format = Görünürlük durumları DWG 2010 veya daha yeni biçimde bir çizim gerektirir.
+ .visibilitystates-no-parameter = Bu adda bir görünürlük parametresi yok.
+ .visibilitystates-no-state = Bu adda bir görünürlük durumu yok.
+ .visibilitystates-state-exists = Bu görünürlük durumu zaten var.
+ .visibilitystates-cannot-move = Görünürlük durumu daha fazla taşınamaz.
+ .visibilitystates-bad-name = Harf, rakam ve alt çizgiden oluşan bir ad girin.
+ .visibilitystates-name-taken = Bu ad başka bir değişken tarafından kullanılıyor.
+ .visibilitystates-no-objects = Düzenlenen alanın nesnelerini seçin.
+ .visibilitystates-panel-elsewhere = Görünürlük durumları, bloğun kendi çiziminin model alanında düzenlenir.
+ .visibilitystates-panel-unsupported = Bu çizimin görünürlük durumları burada düzenlenemez.
+ .visibilitystates-first-state = İlk durum
+ .visibilitystates-panel-empty = Bu çizimde görünürlük durumu yok. Parametre eklemek için + düğmesine tıklayın.
+ .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ nesne)
+ .visibilitystates-move-up = Yukarı taşı
+ .visibilitystates-move-down = Aşağı taşı
+ .visibilitystates-state-objects = Bu durumun nesneleri
+ .visibilitystates-new-state = Yeni durum
+ .visibilitystates-add-state = Durum ekle
+ .visibilitystates-back = Parametrelere dön
+ .visibilitystates-add-to-state = Bu duruma nesne ekle
+ .visibilitystates-no-objects-yet = Parametre henüz hiçbir nesneyi denetlemiyor. Bu duruma nesne ekleyin.
+ .visibilitystates-remove-from-parameter = Parametreden çıkar
+ .visibilitystates-same-everywhere = Parametrenin her durumunda aynı
+ .visibilitystates-same-everywhere-note = Bir veya daha fazla nesne bu parametrenin her durumunda aynı görünür.
.bvstate-current = Geçerli görünürlük durumu: __ocs_fmt_0__
.bvhide-select = Gizlenecek nesneleri seçin:
.bvshow-select = Görünür yapılacak nesneleri seçin:
diff --git a/locales/vi-VN/opencadstudio.ftl b/locales/vi-VN/opencadstudio.ftl
index 60565d7aa9..4abbc97638 100644
--- a/locales/vi-VN/opencadstudio.ftl
+++ b/locales/vi-VN/opencadstudio.ftl
@@ -3597,6 +3597,42 @@ modify =
.bvstate-exists = Trạng thái hiển thị "__ocs_fmt_0__" đã tồn tại.
.bvstate-last = Trạng thái hiển thị duy nhất không thể bị xóa.
.bvstate-needs-bedit = __ocs_fmt_0__: mở khối trong Block Editor trước (BEDIT).
+ .visibilitystates-parameter = VISIBILITYSTATES Nhập tham số mới:
+ .visibilitystates-parameter-or = VISIBILITYSTATES Nhập tham số mới hoặc [__ocs_fmt_0__]:
+ .visibilitystates-state = VISIBILITYSTATES Nhập trạng thái mới cho __ocs_fmt_0__:
+ .visibilitystates-state-or = VISIBILITYSTATES Nhập trạng thái mới cho __ocs_fmt_0__ hoặc [__ocs_fmt_1__]:
+ .visibilitystates-action = VISIBILITYSTATES Chọn thao tác [Thêm/Bỏ/Hiện/Ẩn/Chọn trạng thái] :
+ .visibilitystates-add-objects = Thêm đối tượng
+ .visibilitystates-remove-objects = Bỏ đối tượng
+ .visibilitystates-make-visible = Hiện đối tượng
+ .visibilitystates-make-invisible = Ẩn đối tượng
+ .visibilitystates-select-state = Chọn trạng thái
+ .visibilitystates-model-space = VISIBILITYSTATES hoạt động trong không gian mô hình: hãy mở bản vẽ của khối BricsCAD.
+ .visibilitystates-unsupported = Không thể chỉnh sửa các trạng thái hiển thị ở đây.
+ .visibilitystates-old-format = Trạng thái hiển thị cần bản vẽ định dạng DWG 2010 trở lên.
+ .visibilitystates-no-parameter = Không có tham số hiển thị nào có tên này.
+ .visibilitystates-no-state = Không có trạng thái hiển thị nào có tên này.
+ .visibilitystates-state-exists = Trạng thái hiển thị này đã tồn tại.
+ .visibilitystates-cannot-move = Không thể di chuyển trạng thái hiển thị thêm nữa.
+ .visibilitystates-bad-name = Nhập tên gồm chữ cái, chữ số và dấu gạch dưới.
+ .visibilitystates-name-taken = Tên này đang được một biến khác sử dụng.
+ .visibilitystates-no-objects = Chọn đối tượng thuộc không gian đang chỉnh sửa.
+ .visibilitystates-panel-elsewhere = Trạng thái hiển thị được chỉnh sửa trong không gian mô hình của chính bản vẽ khối.
+ .visibilitystates-panel-unsupported = Không thể chỉnh sửa các trạng thái hiển thị của bản vẽ này ở đây.
+ .visibilitystates-first-state = Trạng thái đầu tiên
+ .visibilitystates-panel-empty = Bản vẽ này không có trạng thái hiển thị nào. Nhấp + để thêm tham số.
+ .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ đối tượng)
+ .visibilitystates-move-up = Di chuyển lên
+ .visibilitystates-move-down = Di chuyển xuống
+ .visibilitystates-state-objects = Đối tượng của trạng thái này
+ .visibilitystates-new-state = Trạng thái mới
+ .visibilitystates-add-state = Thêm trạng thái
+ .visibilitystates-back = Quay lại các tham số
+ .visibilitystates-add-to-state = Thêm đối tượng vào trạng thái này
+ .visibilitystates-no-objects-yet = Tham số chưa điều khiển đối tượng nào. Hãy thêm đối tượng vào trạng thái này.
+ .visibilitystates-remove-from-parameter = Bỏ khỏi tham số
+ .visibilitystates-same-everywhere = Giống nhau ở mọi trạng thái của tham số
+ .visibilitystates-same-everywhere-note = Một hoặc nhiều đối tượng hiển thị giống nhau ở mọi trạng thái của tham số này.
.bvstate-current = Trạng thái hiển thị hiện tại: __ocs_fmt_0__
.bvhide-select = Chọn đối tượng cần ẩn:
.bvshow-select = Chọn các đối tượng để hiển thị:
diff --git a/locales/zh-CN/opencadstudio.ftl b/locales/zh-CN/opencadstudio.ftl
index bf7bd07bb2..372a2673b3 100644
--- a/locales/zh-CN/opencadstudio.ftl
+++ b/locales/zh-CN/opencadstudio.ftl
@@ -3577,6 +3577,42 @@ modify =
.bvstate-exists = 可见性状态“__ocs_fmt_0__”已存在。
.bvstate-last = 不能删除唯一的可见性状态。
.bvstate-needs-bedit = __ocs_fmt_0__: 请先在块编辑器中打开该块 (BEDIT)。
+ .visibilitystates-parameter = VISIBILITYSTATES 输入新参数:
+ .visibilitystates-parameter-or = VISIBILITYSTATES 输入新参数或 [__ocs_fmt_0__]:
+ .visibilitystates-state = VISIBILITYSTATES 输入 __ocs_fmt_0__ 的新状态:
+ .visibilitystates-state-or = VISIBILITYSTATES 输入 __ocs_fmt_0__ 的新状态或 [__ocs_fmt_1__]:
+ .visibilitystates-action = VISIBILITYSTATES 选择操作 [添加/移除/显示/隐藏/选择状态] <添加>:
+ .visibilitystates-add-objects = 添加对象
+ .visibilitystates-remove-objects = 移除对象
+ .visibilitystates-make-visible = 显示对象
+ .visibilitystates-make-invisible = 隐藏对象
+ .visibilitystates-select-state = 选择状态
+ .visibilitystates-model-space = VISIBILITYSTATES 在模型空间中工作: 请打开 BricsCAD 块的图形。
+ .visibilitystates-unsupported = 此处的可见性状态无法编辑。
+ .visibilitystates-old-format = 可见性状态需要 DWG 2010 或更高版本格式的图形。
+ .visibilitystates-no-parameter = 没有该名称的可见性参数。
+ .visibilitystates-no-state = 没有该名称的可见性状态。
+ .visibilitystates-state-exists = 该可见性状态已存在。
+ .visibilitystates-cannot-move = 该可见性状态无法再移动。
+ .visibilitystates-bad-name = 请输入由字母、数字和下划线组成的名称。
+ .visibilitystates-name-taken = 该名称已被另一个变量使用。
+ .visibilitystates-no-objects = 请选择正在编辑的空间中的对象。
+ .visibilitystates-panel-elsewhere = 可见性状态在块自身图形的模型空间中编辑。
+ .visibilitystates-panel-unsupported = 此图形的可见性状态无法在此处编辑。
+ .visibilitystates-first-state = 第一个状态
+ .visibilitystates-panel-empty = 此图形中没有可见性状态。单击 + 添加参数。
+ .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ 个对象)
+ .visibilitystates-move-up = 上移
+ .visibilitystates-move-down = 下移
+ .visibilitystates-state-objects = 此状态的对象
+ .visibilitystates-new-state = 新建状态
+ .visibilitystates-add-state = 添加状态
+ .visibilitystates-back = 返回参数列表
+ .visibilitystates-add-to-state = 将对象添加到此状态
+ .visibilitystates-no-objects-yet = 该参数尚未控制任何对象。请将对象添加到此状态。
+ .visibilitystates-remove-from-parameter = 从参数中移除
+ .visibilitystates-same-everywhere = 在参数的所有状态中显示相同
+ .visibilitystates-same-everywhere-note = 一个或多个对象在此参数的所有状态中显示相同。
.bvstate-current = 当前可见性状态: __ocs_fmt_0__
.bvhide-select = 选择要隐藏的对象:
.bvshow-select = 选择要显示的对象:
diff --git a/locales/zh-TW/opencadstudio.ftl b/locales/zh-TW/opencadstudio.ftl
index 355e21a6fc..cf714233e1 100644
--- a/locales/zh-TW/opencadstudio.ftl
+++ b/locales/zh-TW/opencadstudio.ftl
@@ -3589,6 +3589,42 @@ modify =
.bvstate-exists = 可見性狀態「__ocs_fmt_0__」已存在。
.bvstate-last = 無法刪除唯一的可見性狀態。
.bvstate-needs-bedit = __ocs_fmt_0__:請先在圖塊編輯器中開啟圖塊(BEDIT)。
+ .visibilitystates-parameter = VISIBILITYSTATES 輸入新參數:
+ .visibilitystates-parameter-or = VISIBILITYSTATES 輸入新參數或 [__ocs_fmt_0__]:
+ .visibilitystates-state = VISIBILITYSTATES 輸入 __ocs_fmt_0__ 的新狀態:
+ .visibilitystates-state-or = VISIBILITYSTATES 輸入 __ocs_fmt_0__ 的新狀態或 [__ocs_fmt_1__]:
+ .visibilitystates-action = VISIBILITYSTATES 選取動作 [加入/移除/顯示/隱藏/選取狀態] <加入>:
+ .visibilitystates-add-objects = 加入物件
+ .visibilitystates-remove-objects = 移除物件
+ .visibilitystates-make-visible = 顯示物件
+ .visibilitystates-make-invisible = 隱藏物件
+ .visibilitystates-select-state = 選取狀態
+ .visibilitystates-model-space = VISIBILITYSTATES 在模型空間中運作:請開啟 BricsCAD 圖塊的圖面。
+ .visibilitystates-unsupported = 此處的可見性狀態無法編輯。
+ .visibilitystates-old-format = 可見性狀態需要 DWG 2010 或更新格式的圖面。
+ .visibilitystates-no-parameter = 沒有此名稱的可見性參數。
+ .visibilitystates-no-state = 沒有此名稱的可見性狀態。
+ .visibilitystates-state-exists = 此可見性狀態已存在。
+ .visibilitystates-cannot-move = 此可見性狀態無法再移動。
+ .visibilitystates-bad-name = 請輸入由字母、數字和底線組成的名稱。
+ .visibilitystates-name-taken = 此名稱已由另一個變數使用。
+ .visibilitystates-no-objects = 請選取正在編輯之空間中的物件。
+ .visibilitystates-panel-elsewhere = 可見性狀態需在圖塊本身圖面的模型空間中編輯。
+ .visibilitystates-panel-unsupported = 此圖面的可見性狀態無法在此處編輯。
+ .visibilitystates-first-state = 第一個狀態
+ .visibilitystates-panel-empty = 此圖面中沒有可見性狀態。按一下 + 以新增參數。
+ .visibilitystates-parameter-objects = __ocs_fmt_0__(__ocs_fmt_1__ 個物件)
+ .visibilitystates-move-up = 上移
+ .visibilitystates-move-down = 下移
+ .visibilitystates-state-objects = 此狀態的物件
+ .visibilitystates-new-state = 新狀態
+ .visibilitystates-add-state = 新增狀態
+ .visibilitystates-back = 返回參數
+ .visibilitystates-add-to-state = 將物件加入此狀態
+ .visibilitystates-no-objects-yet = 此參數尚未控制任何物件。請將物件加入此狀態。
+ .visibilitystates-remove-from-parameter = 從參數中移除
+ .visibilitystates-same-everywhere = 在參數的所有狀態中顯示相同
+ .visibilitystates-same-everywhere-note = 一個或多個物件在此參數的所有狀態中顯示相同。
.bvstate-current = 目前可見性狀態:__ocs_fmt_0__
.bvhide-select = 選取要隱藏的物件:
.bvshow-select = 選取要顯示的物件:
diff --git a/src/app/block_parameter_properties.rs b/src/app/block_parameter_properties.rs
index a4f74eda62..4d288d6ff2 100644
--- a/src/app/block_parameter_properties.rs
+++ b/src/app/block_parameter_properties.rs
@@ -45,8 +45,13 @@ impl OpenCADStudio {
} else {
None
};
- let definition =
- |handle| crate::scene::block_actions::instance::definition(&tab.scene.document, handle);
+ // A BricsCAD parametric block's references, whether they show the
+ // block or a copy of it, share the block.
+ let definition = |handle| {
+ crate::scene::bricscad_parameters::master_block(&tab.scene.document, handle).or_else(
+ || crate::scene::block_actions::instance::definition(&tab.scene.document, handle),
+ )
+ };
let first = definition(handles[0])?;
handles
.iter()
@@ -71,6 +76,12 @@ impl OpenCADStudio {
let doc = &tab.scene.document;
let mut rows = native::properties(doc, None, tab.id, insert);
rows.extend(Self::indexed_visibility_property(doc, tab.id, insert));
+ rows.extend(Self::bricscad_visibility_properties(
+ doc,
+ tab.id,
+ insert,
+ editor_session.is_none(),
+ ));
rows
};
let key = |value: &PropValue| match value {
@@ -175,6 +186,8 @@ impl OpenCADStudio {
.document
.dynamic_visibility_for_insert(key.insert)
.map(|(definition, _)| definition)
+ } else if matches!(key.component, BlockParameterComponent::Bricscad(_)) {
+ crate::scene::bricscad_parameters::master_block(&tab.scene.document, key.insert)
} else {
crate::scene::block_actions::instance::definition(&tab.scene.document, key.insert)
};
@@ -229,6 +242,9 @@ impl OpenCADStudio {
(BlockParameterComponent::Visibility(_), Input::Choice(state)) => {
Self::stage_visibility_property(source, target, state)
}
+ (BlockParameterComponent::Bricscad(_), Input::Choice(state)) => {
+ Self::stage_bricscad_visibility(source, target, state)
+ }
_ => native::evaluate(source, None, target, input),
}?;
if let Some(next) = next {
@@ -242,6 +258,9 @@ impl OpenCADStudio {
(BlockParameterComponent::Visibility(_), Input::Choice(state)) => {
Self::stage_visibility_property(&tab.scene.document, key, state)
}
+ (BlockParameterComponent::Bricscad(_), Input::Choice(state)) => {
+ Self::stage_bricscad_visibility(&tab.scene.document, key, state)
+ }
_ => native::evaluate(&tab.scene.document, baseline, key, input),
}
};
diff --git a/src/app/bricscad_visibility_tests.rs b/src/app/bricscad_visibility_tests.rs
new file mode 100644
index 0000000000..413129b209
--- /dev/null
+++ b/src/app/bricscad_visibility_tests.rs
@@ -0,0 +1,177 @@
+//! A reference to a BricsCAD parametric block names the block and lists its
+//! visibility parameters in Properties, also when it shows an anonymous copy
+//! of the block in another state, and a state picked there is shown the way
+//! BricsCAD shows it.
+
+use super::*;
+use crate::scene::model::object::{BlockParameterComponent, BlockParameterKey, PropValue};
+use document::Handle;
+
+/// The BricsCAD drawing in `tests/fixtures/bricscad` (see its README), opened
+/// the way the application opens a file.
+fn opened() -> OpenCADStudio {
+ let mut app = OpenCADStudio::new_for_test();
+ let path = concat!(
+ env!("CARGO_MANIFEST_DIR"),
+ "/tests/fixtures/bricscad/visibility-states.dwg"
+ );
+ app.automation_op(&serde_json::json!({"op": "open", "path": path}).to_string());
+ let i = app.active_tab;
+ assert!(
+ app.tabs[i]
+ .scene
+ .document
+ .block_records
+ .get("ocs-bricscad-visibility-block")
+ .is_some(),
+ "the fixture did not open"
+ );
+ app
+}
+
+fn select(app: &mut OpenCADStudio, references: &[u64]) {
+ let i = app.active_tab;
+ app.tabs[i].scene.selected.clear();
+ for (index, &reference) in references.iter().enumerate() {
+ app.tabs[i]
+ .scene
+ .select_entity(Handle::from(reference), index == 0);
+ }
+ app.tabs[i].selected_handle = (references.len() == 1).then(|| Handle::from(references[0]));
+ app.refresh_properties();
+}
+
+/// The visibility rows as label, shown state and states, with their keys.
+fn visibility_rows(app: &OpenCADStudio) -> Vec<(String, String, Vec, BlockParameterKey)> {
+ app.tabs[app.active_tab]
+ .properties
+ .sections
+ .iter()
+ .flat_map(|section| §ion.props)
+ .filter_map(|property| match &property.value {
+ PropValue::BlockChoice {
+ key,
+ selected,
+ options,
+ ..
+ } if matches!(key.component, BlockParameterComponent::Bricscad(_)) => Some((
+ property.label.clone(),
+ options
+ .get(*selected)
+ .cloned()
+ .unwrap_or_else(|| "*VARIES*".into()),
+ options.clone(),
+ *key,
+ )),
+ _ => None,
+ })
+ .collect()
+}
+
+fn shown(app: &OpenCADStudio) -> Vec<(String, String)> {
+ visibility_rows(app)
+ .into_iter()
+ .map(|(label, state, ..)| (label, state))
+ .collect()
+}
+
+fn pairs(list: &[(&str, &str)]) -> Vec<(String, String)> {
+ list.iter()
+ .map(|(a, b)| (a.to_string(), b.to_string()))
+ .collect()
+}
+
+fn block_name(app: &OpenCADStudio) -> String {
+ let row = app.tabs[app.active_tab]
+ .properties
+ .sections
+ .iter()
+ .flat_map(|section| §ion.props)
+ .find(|property| property.field == "block")
+ .expect("no block row");
+ match &row.value {
+ PropValue::EditChoice { value, .. } | PropValue::ReadOnly(value) => value.clone(),
+ other => panic!("block row is {other:?}"),
+ }
+}
+
+/// Pick `state` in the list of `parameter`, as a click in Properties does.
+fn pick(app: &mut OpenCADStudio, parameter: &str, state: &str) {
+ let (_, _, options, key) = visibility_rows(app)
+ .into_iter()
+ .find(|(label, ..)| label == parameter)
+ .unwrap_or_else(|| panic!("no {parameter} row"));
+ let index = options.iter().position(|option| option == state).unwrap();
+ let _ = app.update(Message::PropBlockChoice { key, index });
+}
+
+#[test]
+fn a_reference_lists_the_states_it_was_set_to_and_names_its_block() {
+ let mut app = opened();
+ for (reference, lamp, label) in [
+ (0xEE, "On", "Shown"),
+ (0x146, "Off", "Shown"),
+ (0x19E, "Off", "Hidden"),
+ ] {
+ select(&mut app, &[reference]);
+ assert_eq!(
+ shown(&app),
+ pairs(&[("LAMP", lamp), ("LABEL", label)]),
+ "{reference:X}"
+ );
+ let rows = visibility_rows(&app);
+ assert_eq!(rows[0].2, ["On", "Off"]);
+ assert_eq!(rows[1].2, ["Shown", "Hidden"]);
+ assert_eq!(
+ block_name(&app),
+ "ocs-bricscad-visibility-block",
+ "{reference:X} shows its block's name, not its copy's"
+ );
+ }
+}
+
+#[test]
+fn a_state_picked_in_properties_is_shown_and_undone_in_one_step() {
+ let mut app = opened();
+ let i = app.active_tab;
+ let before = app.tabs[i].scene.document.clone();
+ select(&mut app, &[0xEE]);
+ pick(&mut app, "LABEL", "Hidden");
+ assert_eq!(shown(&app), pairs(&[("LAMP", "On"), ("LABEL", "Hidden")]));
+ assert!(app.tabs[i].dirty);
+ let _ = app.update(Message::Undo);
+ select(&mut app, &[0xEE]);
+ assert_eq!(shown(&app), pairs(&[("LAMP", "On"), ("LABEL", "Shown")]));
+ assert!(
+ app.tabs[i]
+ .scene
+ .document
+ .block_records
+ .get("*U4")
+ .is_none(),
+ "undo takes the new copy away"
+ );
+ assert_eq!(
+ app.tabs[i].scene.document.block_records.iter().count(),
+ before.block_records.iter().count()
+ );
+}
+
+#[test]
+fn references_selected_together_switch_together() {
+ let mut app = opened();
+ select(&mut app, &[0xEE, 0x146]);
+ assert_eq!(
+ shown(&app),
+ pairs(&[("LAMP", "*VARIES*"), ("LABEL", "Shown")])
+ );
+ pick(&mut app, "LABEL", "Hidden");
+ for (reference, lamp) in [(0xEE, "On"), (0x146, "Off")] {
+ select(&mut app, &[reference]);
+ assert_eq!(
+ shown(&app),
+ pairs(&[("LAMP", lamp), ("LABEL", "Hidden")]),
+ "{reference:X}"
+ );
+ }
+}
diff --git a/src/app/commands/bricscad_visibility.rs b/src/app/commands/bricscad_visibility.rs
new file mode 100644
index 0000000000..4d55d9060e
--- /dev/null
+++ b/src/app/commands/bricscad_visibility.rs
@@ -0,0 +1,318 @@
+//! VISIBILITYSTATES and its palette (VISIBILITYSTATESPANELOPEN): the
+//! visibility states of a BricsCAD parametric block, in model space of the
+//! block's own drawing (see `scene::bricscad_parameters::author`).
+
+use crate::app::{Message, OpenCADStudio};
+use crate::command::CadCommand;
+use crate::modules::draw::modify::visibilitystates::{VisibilityStatesCommand, SEP};
+use crate::scene::bricscad_parameters::{self as bricscad, Action};
+use crate::ui::window::bricscad_visibility::{Model, VisMsg};
+use document::Handle;
+use iced::Task;
+use std::rc::Rc;
+
+/// Marks the step that runs after the objects are picked.
+const PICKED: &str = "PICKED";
+
+impl OpenCADStudio {
+ /// Model space, the block of a BricsCAD block drawing. A block definition
+ /// is left alone: the anonymous copies its references show would keep the
+ /// states it had.
+ fn visibility_states_owner(&mut self, i: usize) -> Option {
+ if let Some(owner) = Self::model_space_owner(&self.tabs[i]) {
+ return Some(owner);
+ }
+ self.command_line.push_error(
+ crate::t!(
+ "VISIBILITYSTATES works in model space: open the drawing of the BricsCAD block."
+ )
+ .as_ref(),
+ );
+ None
+ }
+
+ fn model_space_owner(tab: &crate::app::DocumentTab) -> Option {
+ (tab.active_block_edit_session().is_none() && tab.scene.current_layout == "Model")
+ .then_some(tab.scene.document.header.model_space_block_handle)
+ }
+
+ pub(super) fn dispatch_bricscad_visibility(
+ &mut self,
+ cmd: &str,
+ i: usize,
+ ) -> Option> {
+ match cmd {
+ "VISIBILITYSTATESPANELOPEN" => {
+ self.set_bricscad_visibility_panel(true);
+ return Some(Task::none());
+ }
+ "VISIBILITYSTATESPANELCLOSE" => {
+ self.set_bricscad_visibility_panel(false);
+ return Some(Task::none());
+ }
+ _ => {}
+ }
+ if cmd == "VISIBILITYSTATES" {
+ let Some(owner) = self.visibility_states_owner(i) else {
+ return Some(Task::none());
+ };
+ let parameters = bricscad::parameter_states(&self.tabs[i].scene.document, owner);
+ let command = VisibilityStatesCommand::new(parameters);
+ self.command_line.push_info(&command.prompt());
+ self.command_line.set_step_options(command.options());
+ self.tabs[i].active_cmd = Some(Box::new(command));
+ return Some(Task::none());
+ }
+ let fields = cmd.strip_prefix("_VISIBILITYSTATES")?;
+ let fields: Vec<&str> = fields.strip_prefix(SEP)?.split(SEP).collect();
+ let (parameter, state, action, picked) = match fields.as_slice() {
+ [parameter, state, action] => (*parameter, *state, *action, false),
+ [parameter, state, action, PICKED] => (*parameter, *state, *action, true),
+ _ => return Some(Task::none()),
+ };
+ let action = match action {
+ "ADD" => Action::Add,
+ "REMOVE" => Action::Remove,
+ "VISIBLE" => Action::Visible,
+ "INVISIBLE" => Action::Invisible,
+ "SELECT" => Action::Select,
+ _ => return Some(Task::none()),
+ };
+ if action != Action::Select && !picked && self.tabs[i].scene.selected.is_empty() {
+ self.pick_for_bricscad_visibility(i, cmd);
+ return Some(Task::none());
+ }
+ self.tabs[i].active_cmd = None;
+ let objects = if action == Action::Select {
+ Vec::new()
+ } else {
+ self.tabs[i].scene.selected_handles_in_order()
+ };
+ self.apply_bricscad_visibility(i, parameter, state, action, &objects);
+ Some(Task::none())
+ }
+
+ /// Ask for the objects of `cmd` (`_VISIBILITYSTATES` with its fields).
+ fn pick_for_bricscad_visibility(&mut self, i: usize, cmd: &str) {
+ use crate::modules::draw::select::SelectObjectsCommand;
+ self.tabs[i].scene.deselect_all();
+ let pending = format!("{cmd}{SEP}{PICKED}");
+ let command =
+ SelectObjectsCommand::with_prompt("VISIBILITYSTATES", &pending, "Select objects:");
+ self.command_line.push_info(&command.prompt());
+ self.tabs[i].active_cmd = Some(Box::new(command));
+ }
+
+ /// One VISIBILITYSTATES step on model space of tab `i`, one undo step;
+ /// whether it was done.
+ fn apply_bricscad_visibility(
+ &mut self,
+ i: usize,
+ parameter: &str,
+ state: &str,
+ action: Action,
+ objects: &[Handle],
+ ) -> bool {
+ let Some(owner) = self.visibility_states_owner(i) else {
+ return false;
+ };
+ // The edit runs on a copy, so a refusal leaves the drawing as it was;
+ // what the editor holds goes into the drawing first.
+ self.tabs[i].scene.sync_native_parametric_graph();
+ let mut scene = crate::scene::Scene::new();
+ scene.document = self.tabs[i].scene.document.clone();
+ scene.load_named_parameters_from_document();
+ scene.load_parametric_constraints_from_document();
+ match scene.edit_bricscad_visibility(owner, parameter, state, action, objects) {
+ Ok(()) => {
+ self.push_undo_snapshot(i, "VISIBILITYSTATES");
+ self.apply_action_document_and_bump(i, scene.document);
+ self.tabs[i].scene.load_named_parameters_from_document();
+ self.tabs[i]
+ .scene
+ .load_parametric_constraints_from_document();
+ self.tabs[i].dirty = true;
+ self.finish_pending_history(i);
+ if action != Action::Select {
+ self.tabs[i].scene.deselect_all();
+ }
+ let shown = bricscad::parameter_states(&self.tabs[i].scene.document, owner)
+ .into_iter()
+ .find(|(name, _)| name.eq_ignore_ascii_case(parameter))
+ .and_then(|_| {
+ bricscad::current_state(&self.tabs[i].scene.document, owner, parameter)
+ });
+ if let Some(shown) = shown {
+ self.command_line
+ .push_output(crate::tf!("Current visibility state: {}", shown).as_ref());
+ }
+ self.refresh_properties();
+ true
+ }
+ Err(error) => {
+ self.command_line.push_error(crate::t!(error).as_ref());
+ false
+ }
+ }
+ }
+
+ pub(in crate::app) fn set_bricscad_visibility_panel(&mut self, open: bool) {
+ let id = crate::ui::dock::PanelId::BricscadVisibility;
+ self.bricscad_visibility.show = open;
+ if open {
+ self.dock_open_at_default(id);
+ } else {
+ self.dock_unpeek(id);
+ }
+ }
+
+ /// What the palette shows of `tab`: model space's parameters, read once
+ /// per change of the drawing; `None` outside model space.
+ pub(in crate::app) fn bricscad_visibility_model(
+ &self,
+ tab: &crate::app::DocumentTab,
+ ) -> Option> {
+ Self::model_space_owner(tab)?;
+ let key = (
+ tab.id,
+ tab.edit_revision,
+ crate::i18n::language_generation(),
+ );
+ let mut cache = self.bricscad_visibility.cache.borrow_mut();
+ match cache.as_ref() {
+ Some((at, model)) if *at == key => Some(model.clone()),
+ _ => {
+ let model = Rc::new(crate::ui::window::bricscad_visibility::read(
+ &tab.scene.document,
+ ));
+ *cache = Some((key, model.clone()));
+ Some(model)
+ }
+ }
+ }
+
+ pub(in crate::app) fn on_bricscad_visibility(&mut self, message: VisMsg) -> Task {
+ let i = self.active_tab;
+ let panel = &mut self.bricscad_visibility;
+ match message {
+ VisMsg::Select(parameter, state) => {
+ self.apply_bricscad_visibility(i, ¶meter, &state, Action::Select, &[]);
+ }
+ VisMsg::Open(parameter, state) => {
+ panel.page = Some((parameter, state));
+ panel.new_state = None;
+ panel.new_parameter = None;
+ }
+ VisMsg::Move(parameter, state, up) => {
+ let action = if up { Action::MoveUp } else { Action::MoveDown };
+ self.apply_bricscad_visibility(i, ¶meter, &state, action, &[]);
+ }
+ VisMsg::Back => panel.page = None,
+ VisMsg::Fold(parameter) => {
+ let key = parameter.to_uppercase();
+ if let Some(k) = panel.folded.iter().position(|p| *p == key) {
+ panel.folded.remove(k);
+ } else {
+ panel.folded.push(key);
+ }
+ }
+ VisMsg::NewParameter => {
+ panel.new_parameter = Some(Default::default());
+ panel.new_state = None;
+ }
+ VisMsg::NewParameterName(name) => {
+ if let Some((n, _)) = panel.new_parameter.as_mut() {
+ *n = name;
+ }
+ }
+ VisMsg::NewParameterState(state) => {
+ if let Some((_, s)) = panel.new_parameter.as_mut() {
+ *s = state;
+ }
+ }
+ VisMsg::NewParameterPick => {
+ let Some((name, state)) = panel.new_parameter.take() else {
+ return Task::none();
+ };
+ let (name, state) = (name.trim().to_string(), state.trim().to_string());
+ if name.is_empty() || state.is_empty() {
+ panel.new_parameter = Some((name, state));
+ return Task::none();
+ }
+ panel.page = Some((name.clone(), state.clone()));
+ if self.visibility_states_owner(i).is_some() {
+ self.pick_for_bricscad_visibility(
+ i,
+ &format!("_VISIBILITYSTATES{SEP}{name}{SEP}{state}{SEP}ADD"),
+ );
+ }
+ }
+ VisMsg::NewState(parameter) => {
+ panel.new_state = Some((parameter, String::new()));
+ panel.new_parameter = None;
+ }
+ VisMsg::NewStateName(name) => {
+ if let Some((_, n)) = panel.new_state.as_mut() {
+ *n = name;
+ }
+ }
+ VisMsg::NewStateCommit => {
+ let Some((parameter, name)) = panel.new_state.take() else {
+ return Task::none();
+ };
+ let name = name.trim().to_string();
+ if name.is_empty() {
+ return Task::none();
+ }
+ if self.apply_bricscad_visibility(i, ¶meter, &name, Action::NewState, &[]) {
+ self.bricscad_visibility.page = Some((parameter, name));
+ } else {
+ self.bricscad_visibility.new_state = Some((parameter, name));
+ }
+ }
+ VisMsg::Cancel => {
+ panel.new_parameter = None;
+ panel.new_state = None;
+ }
+ VisMsg::Show(entity, shown) => {
+ if let Some((parameter, state)) = panel.page.clone() {
+ let action = if shown {
+ Action::Visible
+ } else {
+ Action::Invisible
+ };
+ self.apply_bricscad_visibility(i, ¶meter, &state, action, &[entity]);
+ }
+ }
+ VisMsg::Remove(entity) => {
+ if let Some((parameter, state)) = panel.page.clone() {
+ self.apply_bricscad_visibility(
+ i,
+ ¶meter,
+ &state,
+ Action::Remove,
+ &[entity],
+ );
+ }
+ }
+ VisMsg::AddObjects => {
+ if let Some((parameter, state)) = panel.page.clone() {
+ if self.visibility_states_owner(i).is_some() {
+ self.pick_for_bricscad_visibility(
+ i,
+ &format!("_VISIBILITYSTATES{SEP}{parameter}{SEP}{state}{SEP}ADD"),
+ );
+ }
+ }
+ }
+ VisMsg::Highlight(entity) => {
+ if self.tabs[i].scene.document.get_entity(entity).is_some() {
+ self.tabs[i].scene.deselect_all();
+ self.tabs[i].scene.select_entity(entity, true);
+ self.refresh_properties();
+ }
+ }
+ }
+ Task::none()
+ }
+}
diff --git a/src/app/commands/mod.rs b/src/app/commands/mod.rs
index 5196473e82..027f1ee26a 100644
--- a/src/app/commands/mod.rs
+++ b/src/app/commands/mod.rs
@@ -29,6 +29,7 @@ pub(crate) fn linetype_library_lock() -> std::sync::MutexGuard<'static, ()> {
mod revcloud_vars;
pub(crate) use purge::purge_pass;
mod block_editor_vars;
+mod bricscad_visibility;
mod bvisibility;
mod count;
mod dash;
@@ -816,6 +817,9 @@ impl OpenCADStudio {
if let Some(t) = self.dispatch_model_import(cmd, i) {
return Some(t);
}
+ if let Some(t) = self.dispatch_bricscad_visibility(cmd, i) {
+ return Some(t);
+ }
if let Some(t) = self.dispatch_bvisibility(cmd, i) {
return Some(t);
}
diff --git a/src/app/control/block_ops.rs b/src/app/control/block_ops.rs
index 06d8f20183..fd535414ee 100644
--- a/src/app/control/block_ops.rs
+++ b/src/app/control/block_ops.rs
@@ -242,6 +242,16 @@ pub(crate) fn resolve_effective_block(
}
}
+ // 5. Fallback: a copy BricsCAD made of one of its parametric blocks, for a
+ // reference in another state, names that block in its own objects. The
+ // steps above find nothing for it or the copy itself.
+ if let Some(original) = evaluated_handle
+ .filter(|copy| def_handle.is_none_or(|definition| definition == *copy))
+ .and_then(|copy| crate::scene::bricscad_parameters::original_block(doc, copy))
+ {
+ def_handle = Some(original);
+ }
+
if let Some(def_h) = def_handle {
if let Some(def_rec) = doc.block_records.iter().find(|r| r.handle == def_h) {
let true_name = doc
@@ -258,7 +268,7 @@ pub(crate) fn resolve_effective_block(
}
}
- // 5. Fallback: check AcDbDynamicBlockTrueName XData on Insert or evaluated BlockRecord
+ // 6. Fallback: check AcDbDynamicBlockTrueName XData on Insert or evaluated BlockRecord
let xdata_true_name = insert
.common
.extended_data
diff --git a/src/app/dock/update.rs b/src/app/dock/update.rs
index 79545c604d..0e3da6d5bd 100644
--- a/src/app/dock/update.rs
+++ b/src/app/dock/update.rs
@@ -625,6 +625,7 @@ impl OpenCADStudio {
}
PanelId::PointCloudManager => self.pc_manager.show = true,
PanelId::Count => self.set_count_palette(true),
+ PanelId::BricscadVisibility => self.set_bricscad_visibility_panel(true),
PanelId::SheetSetManager => self.show_sheet_set_manager(true),
PanelId::Layers => {
self.sync_ribbon_layers();
@@ -722,6 +723,7 @@ impl OpenCADStudio {
self.count_palette.show = false;
self.ribbon.set_count_palette(false);
}
+ PanelId::BricscadVisibility => self.bricscad_visibility.show = false,
PanelId::SheetSetManager => {
self.sheet_set.show = false;
self.ribbon.set_sheet_set(false);
@@ -873,6 +875,7 @@ impl OpenCADStudio {
PanelId::NodeGraph => self.show_node_graph,
PanelId::PointCloudManager => self.pc_manager.show,
PanelId::Count => self.count_palette.show,
+ PanelId::BricscadVisibility => self.bricscad_visibility.show,
PanelId::SheetSetManager => self.sheet_set.show,
PanelId::Layers => self.show_layers,
// The walk session is the pallet's state. While the Select Objects
diff --git a/src/app/dock/view.rs b/src/app/dock/view.rs
index 1f35adbf05..b37fc2f944 100644
--- a/src/app/dock/view.rs
+++ b/src/app/dock/view.rs
@@ -716,6 +716,12 @@ impl OpenCADStudio {
crate::ui::dock::PanelId::NodeGraph => {
tab.graph.panel(width, chrome, self.node_graph_links)
}
+ crate::ui::dock::PanelId::BricscadVisibility => crate::ui::window::bricscad_visibility::view(
+ &self.bricscad_visibility,
+ self.bricscad_visibility_model(tab),
+ width,
+ chrome,
+ ),
crate::ui::dock::PanelId::Count => crate::ui::window::count_palette::view(
&self.count_palette,
tab.count.as_ref(),
diff --git a/src/app/history.rs b/src/app/history.rs
index 7fd6b7a60a..e5b0471bca 100644
--- a/src/app/history.rs
+++ b/src/app/history.rs
@@ -388,8 +388,17 @@ impl OpenCADStudio {
.graph_before
.take()
.map(|before| Box::new((before, self.tabs[i].graph.undo_state())));
+ let named_parameters_after = self.tabs[i].scene.named_parameters();
+ let named_parameters =
+ (&pending.named_parameters_before != named_parameters_after).then(|| {
+ (
+ pending.named_parameters_before,
+ named_parameters_after.clone(),
+ )
+ });
if !pending.keep_empty
&& graph.is_none()
+ && named_parameters.is_none()
&& visibility_states.is_none()
&& entities.is_empty()
&& reference_designations.is_empty()
@@ -421,7 +430,7 @@ impl OpenCADStudio {
reference_designations,
reference_session,
graph,
- named_parameters: None,
+ named_parameters,
label: pending.label,
};
self.push_undo_entry(i, HistorySnapshot::Delta(Box::new(delta)));
@@ -524,6 +533,7 @@ impl OpenCADStudio {
reference_designations_before: Vec::new(),
reference_session_before: self.reference_session_state(i),
parametric_constraints_before: self.tabs[i].scene.parametric_constraints.clone(),
+ named_parameters_before: self.tabs[i].scene.named_parameters().clone(),
plugin_owned: false,
keep_empty: false,
held: false,
diff --git a/src/app/message.rs b/src/app/message.rs
index 8e7266ff8d..f0b2b8c2d3 100644
--- a/src/app/message.rs
+++ b/src/app/message.rs
@@ -2674,6 +2674,8 @@ pub enum Message {
/// A click or search in the Point Cloud Manager.
PcManager(crate::ui::window::pc_manager::PcManagerMsg),
Count(crate::ui::window::count_palette::CountMsg),
+ /// The Visibility States palette of a BricsCAD parametric block.
+ BricscadVisibility(crate::ui::window::bricscad_visibility::VisMsg),
/// The LayerWalk pallet (LAYWALK).
Laywalk(crate::ui::window::layer_walk::LayerWalkMsg),
/// The QuickCalc pallet.
diff --git a/src/app/mod.rs b/src/app/mod.rs
index 58b53ed716..f2e0425ae2 100644
--- a/src/app/mod.rs
+++ b/src/app/mod.rs
@@ -36,6 +36,10 @@ mod block_test;
#[cfg(test)]
mod block_test_tests;
mod block_visibility;
+#[cfg(test)]
+mod bricscad_visibility_tests;
+#[cfg(test)]
+mod visibilitystates_tests;
pub(crate) mod calc;
mod command_driver;
mod extraction_catalog;
@@ -1462,6 +1466,7 @@ pub(super) struct OpenCADStudio {
/// Point Cloud Manager palette (POINTCLOUDMANAGER).
pub(crate) pc_manager: crate::ui::window::pc_manager::PcManager,
pub(crate) count_palette: crate::ui::window::count_palette::CountPalette,
+ pub(crate) bricscad_visibility: crate::ui::window::bricscad_visibility::VisibilityPanel,
/// The QuickCalc pallet (QUICKCALC / QC).
pub(crate) quick_calc: crate::ui::window::quick_calc::QuickCalcPalette,
/// The Assistant pallet (ASSISTANT): chat with an external AI agent about this drawing.
@@ -3182,6 +3187,7 @@ impl OpenCADStudio {
show_browser: false,
pc_manager: Default::default(),
count_palette: Default::default(),
+ bricscad_visibility: Default::default(),
quick_calc: Default::default(),
assistant: Default::default(),
sheet_set: Default::default(),
diff --git a/src/app/properties.rs b/src/app/properties.rs
index 4e0fb56e5f..4a4eeb66c7 100644
--- a/src/app/properties.rs
+++ b/src/app/properties.rs
@@ -1073,6 +1073,15 @@ impl OpenCADStudio {
custom_properties.extend(Self::visibility_property(doc, handle));
}
custom_properties.extend(Self::visible_blocks_property(doc, handle));
+ // A BricsCAD parametric block's states, switched from a list
+ // outside the Block Editor and Test Block.
+ custom_properties.extend(Self::bricscad_visibility_properties(
+ doc,
+ self.tabs[i].id,
+ handle,
+ self.tabs[i].active_block_edit_session().is_none()
+ && self.tabs[i].block_test.is_none(),
+ ));
if !custom_properties.is_empty() {
sections.push(crate::scene::model::object::PropSection {
title: t!("Custom").into_owned(),
diff --git a/src/app/tab_document.rs b/src/app/tab_document.rs
index a5c3245212..3e38ae73b0 100644
--- a/src/app/tab_document.rs
+++ b/src/app/tab_document.rs
@@ -1538,6 +1538,9 @@ pub(super) struct PendingHistorySnapshot {
/// removes a constraint a plugin created inside its scope.
pub(super) parametric_constraints_before:
Vec,
+ /// The drawing-wide parameter table when the scope opened. A step that
+ /// changes it (BricsCAD's visibility columns are parameters) puts it back.
+ pub(super) named_parameters_before: crate::scene::named_parameters::ParameterTable,
/// Opened by a plugin's `push_undo`: while a plugin request runs, the
/// commands it drives join this scope instead of closing it.
pub(super) plugin_owned: bool,
diff --git a/src/app/update/dispatch.rs b/src/app/update/dispatch.rs
index 5cf1a3d72d..93de6d562a 100644
--- a/src/app/update/dispatch.rs
+++ b/src/app/update/dispatch.rs
@@ -1943,6 +1943,7 @@ impl OpenCADStudio {
Message::PdfShxDialog(message) => self.update_pdf_shx_dialog(message),
Message::PcManager(message) => self.update_pc_manager(message),
Message::Count(message) => self.on_count(message),
+ Message::BricscadVisibility(message) => self.on_bricscad_visibility(message),
Message::Laywalk(message) => self.on_layer_walk(message),
Message::QuickCalc(message) => self.on_quick_calc(message),
Message::Assistant(message) => self.on_assistant(message),
diff --git a/src/app/visibility.rs b/src/app/visibility.rs
index eb1365d9e0..85e6e3fd96 100644
--- a/src/app/visibility.rs
+++ b/src/app/visibility.rs
@@ -120,6 +120,15 @@ fn visibility_revision(parameter: &BlockVisibilityParameter) -> u64 {
hash.finish()
}
+/// Identifies a BricsCAD visibility parameter by its name and states, so a
+/// list built for one block is not applied to a parameter that changed.
+fn bricscad_revision(parameter: &crate::scene::bricscad_parameters::VisibilityParameter) -> u64 {
+ let mut hash = std::collections::hash_map::DefaultHasher::new();
+ parameter.name.hash(&mut hash);
+ parameter.states.hash(&mut hash);
+ hash.finish()
+}
+
fn visibility_label(parameter: &BlockVisibilityParameter) -> String {
if parameter.name.trim().is_empty() {
"Visibility1".into()
@@ -626,6 +635,96 @@ impl OpenCADStudio {
})
}
+ /// The visibility parameters of a reference to a BricsCAD parametric
+ /// block, one row each with the state the reference shows. With
+ /// `editable`, a reference that can be switched (see
+ /// `bricscad_parameters::can_switch`) gets a list of the states; any
+ /// other shows the state with the states as tooltip.
+ pub(super) fn bricscad_visibility_properties(
+ doc: &document::Document,
+ document: u64,
+ handle: Handle,
+ editable: bool,
+ ) -> Vec {
+ use crate::scene::bricscad_parameters as bricscad;
+ let parameters = bricscad::reference_parameters(doc, handle);
+ if parameters.is_empty() {
+ return Vec::new();
+ }
+ let master = bricscad::master_block(doc, handle)
+ .filter(|_| editable && bricscad::can_switch(doc, handle));
+ let master_parameters = master
+ .map(|master| bricscad::visibility_parameters(doc, master))
+ .unwrap_or_default();
+ parameters
+ .into_iter()
+ .map(|parameter| {
+ let feature = master_parameters
+ .iter()
+ .find(|shown| shown.name == parameter.name && shown.states == parameter.states)
+ .map(|shown| shown.feature);
+ let value = match (master, feature) {
+ (Some(definition), Some(feature)) => PropValue::BlockChoice {
+ key: BlockParameterKey {
+ document,
+ definition,
+ insert: handle,
+ batch_generation: None,
+ editor_session: None,
+ parameter: feature,
+ component: BlockParameterComponent::Bricscad(bricscad_revision(
+ ¶meter,
+ )),
+ },
+ selected: parameter.current.unwrap_or(usize::MAX),
+ options: parameter.states.clone(),
+ description: String::new(),
+ },
+ _ => PropValue::ReadOnlyWithTooltip {
+ value: parameter
+ .current
+ .and_then(|index| parameter.states.get(index).cloned())
+ .unwrap_or_default(),
+ tooltip: parameter.states.join(", "),
+ },
+ };
+ Property {
+ value,
+ label: parameter.name,
+ field: "bricscad_visibility",
+ }
+ })
+ .collect()
+ }
+
+ /// Show state `state` of the BricsCAD visibility parameter `key` names on
+ /// a copy of `doc`; `None` when the reference shows it already.
+ pub(super) fn stage_bricscad_visibility(
+ doc: &document::Document,
+ key: BlockParameterKey,
+ state: usize,
+ ) -> Result, &'static str> {
+ use crate::scene::bricscad_parameters as bricscad;
+ const INVALID: &str = "Select supported targets belonging to this block.";
+ if bricscad::master_block(doc, key.insert) != Some(key.definition) {
+ return Err(INVALID);
+ }
+ let parameter = bricscad::visibility_parameters(doc, key.definition)
+ .into_iter()
+ .find(|parameter| parameter.feature == key.parameter)
+ .ok_or(INVALID)?;
+ if key.component != BlockParameterComponent::Bricscad(bricscad_revision(¶meter)) {
+ return Err(INVALID);
+ }
+ let state = parameter.states.get(state).ok_or(INVALID)?;
+ let mut scene = crate::scene::Scene::new();
+ scene.document = doc.clone();
+ match scene.set_bricscad_visibility(key.insert, ¶meter.name, state)? {
+ true => Ok(Some(scene.document)),
+ false => Ok(None),
+ }
+ }
+
/// Recompute the visibility grip for the active tab's single selection and
/// append it (as a Triangle grip) to `selected_grips`. Clears it when the
/// selection is not a dynamic-block reference. `wo` is the world offset
diff --git a/src/app/visibilitystates_tests.rs b/src/app/visibilitystates_tests.rs
new file mode 100644
index 0000000000..9194a67032
--- /dev/null
+++ b/src/app/visibilitystates_tests.rs
@@ -0,0 +1,307 @@
+//! VISIBILITYSTATES typed at the command line on the BricsCAD drawing of five
+//! lines in `tests/fixtures/bricscad` leaves what BricsCAD leaves, and each
+//! step is one undo step.
+
+use super::*;
+use document::Handle;
+
+fn opened(name: &str) -> OpenCADStudio {
+ let mut app = OpenCADStudio::new_for_test();
+ let path = format!(
+ "{}/tests/fixtures/bricscad/{name}",
+ env!("CARGO_MANIFEST_DIR")
+ );
+ app.automation_op(&serde_json::json!({"op": "open", "path": path}).to_string());
+ app
+}
+
+fn feed(app: &mut OpenCADStudio, text: &str) {
+ let _ = app.update(Message::CommandInput(text.to_string()));
+ let _ = app.update(Message::CommandSubmit);
+}
+
+/// One run of the command: the lines by number are selected first, as an
+/// operator picks them before or when the command asks.
+fn visibility_states(
+ app: &mut OpenCADStudio,
+ parameter: &str,
+ state: &str,
+ action: &str,
+ lines: &[usize],
+) {
+ let i = app.active_tab;
+ app.tabs[i].scene.deselect_all();
+ for (k, n) in lines.iter().enumerate() {
+ let handle = Handle::from(crate::scene::bricscad_parameters::author_tests::LINES[n - 1]);
+ app.tabs[i].scene.select_entity(handle, k == 0);
+ }
+ let _ = app.dispatch_command("VISIBILITYSTATES");
+ feed(app, parameter);
+ feed(app, state);
+ feed(app, action);
+ assert!(
+ app.tabs[i].active_cmd.is_none(),
+ "{parameter} {state} {action} left a step open"
+ );
+}
+
+#[test]
+fn typed_at_the_command_line_the_run_leaves_what_bricscad_leaves() {
+ let mut app = opened("authoring-start.dwg");
+ for (parameter, state, action, lines) in [
+ ("P1", "S1", "A", &[1, 2][..]),
+ ("P1", "S2", "I", &[1]),
+ ("P1", "S3", "I", &[2]),
+ ("P1", "S2", "V", &[1]),
+ ("P1", "S1", "A", &[3]),
+ ("P1", "S1", "R", &[3]),
+ ("P2", "Sichtbar", "A", &[4]),
+ ("P2", "Unsichtbar", "I", &[4]),
+ ("P2", "Sichtbar", "A", &[2]),
+ ("P1", "S4", "V", &[1]),
+ ("P1", "S2", "S", &[]),
+ ("P1", "S3", "S", &[]),
+ ] {
+ visibility_states(&mut app, parameter, state, action, lines);
+ }
+ let ours = crate::scene::bricscad_parameters::author_tests::describe(
+ &app.tabs[app.active_tab].scene.document,
+ );
+ let theirs = crate::scene::bricscad_parameters::author_tests::describe(
+ &opened("authoring-select.dwg").tabs[0].scene.document,
+ );
+ // The test runs in English; BricsCAD named them in German.
+ let ours: Vec = ours
+ .into_iter()
+ .map(|line| {
+ line.replace("Suppress_", "Unterdrücken_")
+ .replace(
+ "controlling visibility of entities in ",
+ "Steuerung der Sichtbarkeit von Objekten in ",
+ )
+ .replace("Entity_", "Objekt_")
+ })
+ .collect();
+ assert_eq!(ours, theirs);
+}
+
+#[test]
+fn each_run_is_one_undo_step_and_a_refusal_changes_nothing() {
+ let mut app = opened("authoring-start.dwg");
+ let i = app.active_tab;
+ let start = app.tabs[i].scene.document.clone();
+ visibility_states(&mut app, "P1", "S1", "A", &[1, 2]);
+ assert_ne!(app.tabs[i].scene.document, start);
+ let _ = app.update(Message::Undo);
+ assert!(
+ crate::scene::bricscad_parameters::parameter_states(
+ &app.tabs[i].scene.document,
+ app.tabs[i].scene.document.header.model_space_block_handle
+ )
+ .is_empty(),
+ "undo takes the parameter away"
+ );
+ let _ = app.update(Message::Redo);
+ assert_eq!(
+ crate::scene::bricscad_parameters::parameter_states(
+ &app.tabs[i].scene.document,
+ app.tabs[i].scene.document.header.model_space_block_handle
+ ),
+ [("P1".to_string(), vec!["S1".to_string()])],
+ "redo brings it back"
+ );
+ let _ = app.update(Message::Undo);
+ // A state to select that does not exist is refused, the drawing unchanged.
+ let before = app.tabs[i].scene.document.clone();
+ let undo = app.tabs[i].history.undo_stack.len();
+ visibility_states(&mut app, "P9", "S1", "S", &[]);
+ assert_eq!(app.tabs[i].history.undo_stack.len(), undo);
+ assert!(app.tabs[i].scene.document == before);
+}
+
+#[test]
+fn in_the_block_editor_the_command_changes_nothing() {
+ let mut app = opened("visibility-states.dwg");
+ let i = app.active_tab;
+ let _ = app.dispatch_command(&format!("BEDIT_BEGIN:{}", 0xEE));
+ assert!(app.tabs[i].active_block_edit.is_some());
+ let before = app.tabs[i].scene.document.clone();
+ let _ = app.dispatch_command("VISIBILITYSTATES");
+ assert!(app.tabs[i].active_cmd.is_none());
+ assert!(app.tabs[i].scene.document == before);
+}
+
+#[test]
+fn objects_picked_when_the_command_asks_are_the_ones_it_takes() {
+ let mut app = opened("authoring-start.dwg");
+ let i = app.active_tab;
+ app.tabs[i].scene.deselect_all();
+ let _ = app.dispatch_command("VISIBILITYSTATES");
+ feed(&mut app, "P1");
+ feed(&mut app, "S1");
+ feed(&mut app, "A");
+ let lines = crate::scene::bricscad_parameters::author_tests::LINES;
+ for handle in [lines[0], lines[1]] {
+ let command = app.tabs[i]
+ .active_cmd
+ .as_mut()
+ .expect("the command asks for objects");
+ let _ = command.on_entity_pick(Handle::from(handle), glam::DVec3::ZERO);
+ }
+ feed(&mut app, "");
+ assert!(app.tabs[i].active_cmd.is_none());
+
+ let mut scene = crate::scene::bricscad_parameters::author_tests::fixture("authoring-start.dwg");
+ let model = scene.document.header.model_space_block_handle;
+ scene
+ .edit_bricscad_visibility(
+ model,
+ "P1",
+ "S1",
+ crate::scene::bricscad_parameters::Action::Add,
+ &[Handle::from(lines[0]), Handle::from(lines[1])],
+ )
+ .unwrap();
+ assert_eq!(
+ crate::scene::bricscad_parameters::author_tests::describe(&app.tabs[i].scene.document),
+ crate::scene::bricscad_parameters::author_tests::describe(&scene.document)
+ );
+}
+
+mod palette {
+ use super::*;
+ use crate::scene::bricscad_parameters::author_tests::LINES;
+ use crate::ui::window::bricscad_visibility::VisMsg;
+
+ fn send(app: &mut OpenCADStudio, message: VisMsg) {
+ let _ = app.update(Message::BricscadVisibility(message));
+ }
+
+ fn states(app: &OpenCADStudio) -> Vec<(String, Vec, usize)> {
+ let i = app.active_tab;
+ let model = app
+ .bricscad_visibility_model(&app.tabs[i])
+ .expect("model space");
+ model
+ .parameters
+ .as_ref()
+ .expect("the parameters can be edited")
+ .iter()
+ .map(|p| (p.name.clone(), p.states.clone(), p.current))
+ .collect()
+ }
+
+ fn shown_in(app: &OpenCADStudio, parameter: &str, state: &str) -> Vec {
+ let i = app.active_tab;
+ let model = app.bricscad_visibility_model(&app.tabs[i]).unwrap();
+ let p = model
+ .parameters
+ .as_ref()
+ .unwrap()
+ .iter()
+ .find(|p| p.name == parameter)
+ .unwrap()
+ .clone();
+ let s = p.states.iter().position(|x| x == state).unwrap();
+ p.objects
+ .iter()
+ .filter(|(_, pattern)| pattern[s])
+ .map(|(h, _)| h.value())
+ .collect()
+ }
+
+ #[test]
+ fn the_palette_switches_moves_adds_and_each_step_undoes() {
+ let mut app = opened("authoring-select.dwg");
+ let i = app.active_tab;
+ let _ = app.dispatch_command("VISIBILITYSTATESPANELOPEN");
+ assert!(app.bricscad_visibility.show);
+ let s = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::>();
+ assert_eq!(
+ states(&app)[0],
+ ("P1".into(), s(&["S1", "S2", "S3", "S4"]), 2)
+ );
+
+ // A click on a state shows it.
+ send(&mut app, VisMsg::Select("P1".into(), "S1".into()));
+ assert_eq!(states(&app)[0].2, 0);
+
+ // Up and down: the order Properties lists them in.
+ send(&mut app, VisMsg::Move("P1".into(), "S4".into(), true));
+ assert_eq!(
+ states(&app)[0],
+ ("P1".into(), s(&["S1", "S2", "S4", "S3"]), 0)
+ );
+ let _ = app.update(Message::Undo);
+ assert_eq!(states(&app)[0].1, s(&["S1", "S2", "S3", "S4"]));
+
+ // A new state opens its page; a tick shows an object in it.
+ send(&mut app, VisMsg::NewState("P1".into()));
+ send(&mut app, VisMsg::NewStateName("Leer".into()));
+ send(&mut app, VisMsg::NewStateCommit);
+ assert_eq!(
+ app.bricscad_visibility.page,
+ Some(("P1".into(), "Leer".into()))
+ );
+ assert_eq!(shown_in(&app, "P1", "Leer"), Vec::::new());
+ send(&mut app, VisMsg::Show(Handle::from(LINES[0]), true));
+ assert_eq!(shown_in(&app, "P1", "Leer"), vec![LINES[0]]);
+
+ // Add objects: picked in the drawing, they show in this state only.
+ send(&mut app, VisMsg::AddObjects);
+ assert!(
+ app.tabs[i].active_cmd.is_some(),
+ "the palette asks for objects"
+ );
+ let _ = app.tabs[i]
+ .active_cmd
+ .as_mut()
+ .unwrap()
+ .on_entity_pick(Handle::from(LINES[4]), glam::DVec3::ZERO);
+ feed(&mut app, "");
+ assert!(app.tabs[i].active_cmd.is_none());
+ assert_eq!(shown_in(&app, "P1", "Leer"), vec![LINES[0], LINES[4]]);
+ assert_eq!(shown_in(&app, "P1", "S1"), vec![LINES[0], LINES[1]]);
+
+ // Removed from the parameter: no state rules it any more.
+ send(&mut app, VisMsg::Remove(Handle::from(LINES[4])));
+ assert_eq!(shown_in(&app, "P1", "Leer"), vec![LINES[0]]);
+ let _ = app.update(Message::Undo);
+ assert_eq!(shown_in(&app, "P1", "Leer"), vec![LINES[0], LINES[4]]);
+ }
+
+ #[test]
+ fn a_new_parameter_starts_with_the_objects_picked() {
+ let mut app = opened("authoring-start.dwg");
+ let i = app.active_tab;
+ let _ = app.dispatch_command("VISIBILITYSTATESPANELOPEN");
+ assert_eq!(states(&app), vec![]);
+ send(&mut app, VisMsg::NewParameter);
+ send(&mut app, VisMsg::NewParameterName("LAMPE".into()));
+ send(&mut app, VisMsg::NewParameterState("An".into()));
+ send(&mut app, VisMsg::NewParameterPick);
+ for handle in [LINES[1], LINES[2]] {
+ let _ = app.tabs[i]
+ .active_cmd
+ .as_mut()
+ .expect("the palette asks for objects")
+ .on_entity_pick(Handle::from(handle), glam::DVec3::ZERO);
+ }
+ feed(&mut app, "");
+ assert_eq!(states(&app), vec![("LAMPE".into(), vec!["An".into()], 0)]);
+ assert_eq!(shown_in(&app, "LAMPE", "An"), vec![LINES[1], LINES[2]]);
+ assert_eq!(
+ app.bricscad_visibility.page,
+ Some(("LAMPE".into(), "An".into()))
+ );
+ }
+
+ #[test]
+ fn outside_model_space_the_palette_shows_nothing_to_edit() {
+ let mut app = opened("visibility-states.dwg");
+ let i = app.active_tab;
+ assert!(app.bricscad_visibility_model(&app.tabs[i]).is_some());
+ let _ = app.dispatch_command(&format!("BEDIT_BEGIN:{}", 0xEE));
+ assert!(app.bricscad_visibility_model(&app.tabs[i]).is_none());
+ }
+}
diff --git a/src/locale_catalog.rs b/src/locale_catalog.rs
index d8a38cd94f..f57ed389f7 100644
--- a/src/locale_catalog.rs
+++ b/src/locale_catalog.rs
@@ -1756,6 +1756,42 @@ pub(super) fn message_attribute(source: &str) -> Option<(&'static str, &'static
"Visibility state \"{}\" already exists." => Some(("modify", "bvstate-exists")),
"The only visibility state cannot be deleted." => Some(("modify", "bvstate-last")),
"{}: open the block in the Block Editor first (BEDIT)." => Some(("modify", "bvstate-needs-bedit")),
+ "VISIBILITYSTATES Enter a new parameter:" => Some(("modify", "visibilitystates-parameter")),
+ "VISIBILITYSTATES Enter a new parameter or [{}]:" => Some(("modify", "visibilitystates-parameter-or")),
+ "VISIBILITYSTATES Enter a new state for {}:" => Some(("modify", "visibilitystates-state")),
+ "VISIBILITYSTATES Enter a new state for {} or [{}]:" => Some(("modify", "visibilitystates-state-or")),
+ "VISIBILITYSTATES Select action [Add objects/Remove objects/make objects Visible/make objects Invisible/Select state] :" => Some(("modify", "visibilitystates-action")),
+ "Add objects" => Some(("modify", "visibilitystates-add-objects")),
+ "Remove objects" => Some(("modify", "visibilitystates-remove-objects")),
+ "make objects Visible" => Some(("modify", "visibilitystates-make-visible")),
+ "make objects Invisible" => Some(("modify", "visibilitystates-make-invisible")),
+ "Select state" => Some(("modify", "visibilitystates-select-state")),
+ "VISIBILITYSTATES works in model space: open the drawing of the BricsCAD block." => Some(("modify", "visibilitystates-model-space")),
+ "The visibility states here cannot be edited." => Some(("modify", "visibilitystates-unsupported")),
+ "Visibility states need a drawing in DWG 2010 format or later." => Some(("modify", "visibilitystates-old-format")),
+ "No visibility parameter of that name." => Some(("modify", "visibilitystates-no-parameter")),
+ "No visibility state of that name." => Some(("modify", "visibilitystates-no-state")),
+ "That visibility state exists already." => Some(("modify", "visibilitystates-state-exists")),
+ "The visibility state cannot move further." => Some(("modify", "visibilitystates-cannot-move")),
+ "Enter a name of letters, digits and underscores." => Some(("modify", "visibilitystates-bad-name")),
+ "That name is used by another variable." => Some(("modify", "visibilitystates-name-taken")),
+ "Select objects of the space being edited." => Some(("modify", "visibilitystates-no-objects")),
+ "Visibility states are edited in model space of the block's own drawing." => Some(("modify", "visibilitystates-panel-elsewhere")),
+ "The visibility states of this drawing cannot be edited here." => Some(("modify", "visibilitystates-panel-unsupported")),
+ "First state" => Some(("modify", "visibilitystates-first-state")),
+ "There are no visibility states in this drawing. Click + to add a parameter." => Some(("modify", "visibilitystates-panel-empty")),
+ "{} ({} objects)" => Some(("modify", "visibilitystates-parameter-objects")),
+ "Move up" => Some(("modify", "visibilitystates-move-up")),
+ "Move down" => Some(("modify", "visibilitystates-move-down")),
+ "Objects of this state" => Some(("modify", "visibilitystates-state-objects")),
+ "New state" => Some(("modify", "visibilitystates-new-state")),
+ "Add state" => Some(("modify", "visibilitystates-add-state")),
+ "Back to the parameters" => Some(("modify", "visibilitystates-back")),
+ "Add objects to this state" => Some(("modify", "visibilitystates-add-to-state")),
+ "The parameter rules no objects yet. Add objects to this state." => Some(("modify", "visibilitystates-no-objects-yet")),
+ "Remove from parameter" => Some(("modify", "visibilitystates-remove-from-parameter")),
+ "Shown the same in every state of the parameter" => Some(("modify", "visibilitystates-same-everywhere")),
+ "One or more objects show the same in every state of this parameter." => Some(("modify", "visibilitystates-same-everywhere-note")),
"Current visibility state: {}" => Some(("modify", "bvstate-current")),
"Select objects to hide:" => Some(("modify", "bvhide-select")),
"Select objects to make visible:" => Some(("modify", "bvshow-select")),
diff --git a/src/modules/draw/modify/mod.rs b/src/modules/draw/modify/mod.rs
index 88449a126d..0b249fd506 100644
--- a/src/modules/draw/modify/mod.rs
+++ b/src/modules/draw/modify/mod.rs
@@ -35,3 +35,4 @@ pub mod translate;
pub mod trim;
pub mod txtexp;
pub mod vertex_edit;
+pub mod visibilitystates;
diff --git a/src/modules/draw/modify/visibilitystates.rs b/src/modules/draw/modify/visibilitystates.rs
new file mode 100644
index 0000000000..b119dbe58a
--- /dev/null
+++ b/src/modules/draw/modify/visibilitystates.rs
@@ -0,0 +1,249 @@
+// VISIBILITYSTATES — the visibility states of a BricsCAD parametric block, in
+// model space of the block's own drawing: name a parameter and a state (new
+// ones are made), then add, remove, show or hide objects in it, or make it
+// current. The prompts follow BricsCAD's.
+
+use crate::command::{CadCommand, CmdOption, CmdResult, InputKind};
+use document::Handle;
+use glam::DVec3;
+
+/// Separates the fields of the steps the command hands over.
+pub const SEP: char = '\u{1f}';
+
+enum Step {
+ Parameter,
+ State(String),
+ Action(String, String),
+}
+
+pub struct VisibilityStatesCommand {
+ /// Each parameter with its states.
+ parameters: Vec<(String, Vec)>,
+ step: Step,
+}
+
+impl VisibilityStatesCommand {
+ pub fn new(parameters: Vec<(String, Vec)>) -> Self {
+ Self {
+ parameters,
+ step: Step::Parameter,
+ }
+ }
+
+ fn known<'a>(names: impl IntoIterator- , name: &str) -> Option
{
+ names
+ .into_iter()
+ .find(|candidate| candidate.eq_ignore_ascii_case(name))
+ .cloned()
+ }
+
+ fn states(&self, parameter: &str) -> Vec {
+ self.parameters
+ .iter()
+ .find(|(name, _)| name.eq_ignore_ascii_case(parameter))
+ .map(|(_, states)| states.clone())
+ .unwrap_or_default()
+ }
+
+ fn done(parts: &[&str]) -> CmdResult {
+ let mut command = String::from("_VISIBILITYSTATES");
+ for part in parts {
+ command.push(SEP);
+ command.push_str(part);
+ }
+ CmdResult::Dispatch(command)
+ }
+}
+
+impl CadCommand for VisibilityStatesCommand {
+ fn name(&self) -> &'static str {
+ "VISIBILITYSTATES"
+ }
+
+ fn prompt(&self) -> String {
+ match &self.step {
+ Step::Parameter => {
+ let names: Vec = self.parameters.iter().map(|(n, _)| n.clone()).collect();
+ if names.is_empty() {
+ crate::t!("VISIBILITYSTATES Enter a new parameter:").into_owned()
+ } else {
+ crate::tf!(
+ "VISIBILITYSTATES Enter a new parameter or [{}]:",
+ names.join("/")
+ )
+ .into_owned()
+ }
+ }
+ Step::State(parameter) => {
+ let states = self.states(parameter);
+ if states.is_empty() {
+ crate::tf!("VISIBILITYSTATES Enter a new state for {}:", parameter)
+ .into_owned()
+ } else {
+ crate::tf!(
+ "VISIBILITYSTATES Enter a new state for {} or [{}]:",
+ parameter,
+ states.join("/")
+ )
+ .into_owned()
+ }
+ }
+ Step::Action(..) => crate::t!(
+ "VISIBILITYSTATES Select action [Add objects/Remove objects/make objects Visible/make objects Invisible/Select state] :"
+ )
+ .into_owned(),
+ }
+ }
+
+ fn options(&self) -> Vec {
+ match &self.step {
+ Step::Parameter => self
+ .parameters
+ .iter()
+ .map(|(name, _)| CmdOption::new(name, name))
+ .collect(),
+ Step::State(parameter) => self
+ .states(parameter)
+ .iter()
+ .map(|state| CmdOption::new(state, state))
+ .collect(),
+ Step::Action(..) => vec![
+ CmdOption::new(crate::t!("Add objects").as_ref(), "A"),
+ CmdOption::new(crate::t!("Remove objects").as_ref(), "R"),
+ CmdOption::new(crate::t!("make objects Visible").as_ref(), "V"),
+ CmdOption::new(crate::t!("make objects Invisible").as_ref(), "I"),
+ CmdOption::new(crate::t!("Select state").as_ref(), "S"),
+ ],
+ }
+ }
+
+ fn wants_text_input(&self) -> bool {
+ true
+ }
+
+ fn input_kind(&self) -> InputKind {
+ match self.step {
+ Step::Action(..) => InputKind::SingleToken,
+ _ => InputKind::FreeText,
+ }
+ }
+
+ fn on_text_input(&mut self, text: &str) -> Option {
+ let text = text.trim();
+ match &self.step {
+ Step::Parameter if text.is_empty() => Some(CmdResult::Cancel),
+ Step::Parameter => {
+ let names: Vec = self.parameters.iter().map(|(n, _)| n.clone()).collect();
+ let name = Self::known(&names, text).unwrap_or_else(|| text.to_string());
+ self.step = Step::State(name);
+ Some(CmdResult::NeedPoint)
+ }
+ Step::State(_) if text.is_empty() => Some(CmdResult::NeedPoint),
+ Step::State(parameter) => {
+ let parameter = parameter.clone();
+ let state =
+ Self::known(&self.states(¶meter), text).unwrap_or_else(|| text.to_string());
+ self.step = Step::Action(parameter, state);
+ Some(CmdResult::NeedPoint)
+ }
+ Step::Action(parameter, state) => {
+ // A translated prompt hands back the whole source option.
+ let keyword = text.trim_start_matches('_').to_ascii_uppercase();
+ let action = match keyword.as_str() {
+ "" | "A" | "ADD" | "ADD OBJECTS" => "ADD",
+ "R" | "REMOVE" | "REMOVE OBJECTS" => "REMOVE",
+ "V" | "VISIBLE" | "MAKE OBJECTS VISIBLE" => "VISIBLE",
+ "I" | "INVISIBLE" | "MAKE OBJECTS INVISIBLE" => "INVISIBLE",
+ "S" | "SELECT" | "ST" | "STATE" | "SELECT STATE" => "SELECT",
+ _ => {
+ return Some(CmdResult::ReportError(
+ crate::t!("Invalid option keyword.").into_owned(),
+ ))
+ }
+ };
+ Some(Self::done(&[parameter, state, action]))
+ }
+ }
+ }
+
+ fn on_point(&mut self, _pt: DVec3) -> CmdResult {
+ CmdResult::NeedPoint
+ }
+
+ fn on_entity_pick(&mut self, _handle: Handle, _pt: DVec3) -> CmdResult {
+ CmdResult::NeedPoint
+ }
+
+ fn on_enter(&mut self) -> CmdResult {
+ self.on_text_input("").unwrap_or(CmdResult::Cancel)
+ }
+}
+
+inventory::submit!(crate::command::CommandRegistration {
+ names: &[
+ "VISIBILITYSTATES",
+ "VISIBILITYSTATESPANELOPEN",
+ "VISIBILITYSTATESPANELCLOSE"
+ ]
+});
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn command() -> VisibilityStatesCommand {
+ VisibilityStatesCommand::new(vec![("LAMP".into(), vec!["On".into(), "Off".into()])])
+ }
+
+ fn dispatched(result: Option) -> Vec {
+ match result {
+ Some(CmdResult::Dispatch(command)) => command.split(SEP).map(str::to_string).collect(),
+ _ => panic!("the command hands nothing over"),
+ }
+ }
+
+ #[test]
+ fn known_names_take_their_own_case_and_the_action_defaults_to_add() {
+ let mut command = command();
+ assert!(command.prompt().contains("[LAMP]"), "{}", command.prompt());
+ command.on_text_input("lamp");
+ assert!(
+ command.prompt().contains("[On/Off]"),
+ "{}",
+ command.prompt()
+ );
+ command.on_text_input("off");
+ assert_eq!(
+ dispatched(command.on_text_input("")),
+ ["_VISIBILITYSTATES", "LAMP", "Off", "ADD"]
+ );
+ }
+
+ #[test]
+ fn new_names_and_each_action_keyword() {
+ for (keyword, action) in [
+ ("_A", "ADD"),
+ ("R", "REMOVE"),
+ ("v", "VISIBLE"),
+ ("_Invisible", "INVISIBLE"),
+ ("S", "SELECT"),
+ ("make objects Visible", "VISIBLE"),
+ ("Select state", "SELECT"),
+ ] {
+ let mut command = command();
+ command.on_text_input("Label");
+ command.on_text_input("Shown");
+ assert_eq!(
+ dispatched(command.on_text_input(keyword)),
+ ["_VISIBILITYSTATES", "Label", "Shown", action]
+ );
+ }
+ let mut command = command();
+ command.on_text_input("LAMP");
+ command.on_text_input("On");
+ assert!(matches!(
+ command.on_text_input("X"),
+ Some(CmdResult::ReportError(_))
+ ));
+ }
+}
diff --git a/src/modules/parametric/mod.rs b/src/modules/parametric/mod.rs
index a117a91c25..afefb28c52 100644
--- a/src/modules/parametric/mod.rs
+++ b/src/modules/parametric/mod.rs
@@ -180,6 +180,12 @@ impl CadModule for ParametricModule {
"Parameters Manager",
include_bytes!("../../../assets/icons/constrain/parameters.svg"),
)),
+ // The visibility states of a BricsCAD parametric block.
+ RibbonItem::LargeTool(command(
+ "VISIBILITYSTATESPANELOPEN",
+ "Visibility States",
+ crate::ui::icons::EYE,
+ )),
],
},
]
@@ -278,7 +284,7 @@ mod tests {
);
assert_eq!(
groups[2].tools.iter().map(item_id).collect::>(),
- ["DELCONSTRAINT", "PARAMETERS"]
+ ["DELCONSTRAINT", "PARAMETERS", "VISIBILITYSTATESPANELOPEN"]
);
let RibbonItem::LargeDropdown { items, default, .. } = &groups[1].tools[0] else {
diff --git a/src/scene/block_parameter_properties.rs b/src/scene/block_parameter_properties.rs
index 9acb4d3731..daf89a0955 100644
--- a/src/scene/block_parameter_properties.rs
+++ b/src/scene/block_parameter_properties.rs
@@ -190,6 +190,7 @@ pub(crate) fn component_id(component: &Component) -> String {
Component::Angle => "Angle".to_owned(),
Component::Flip => "Flip".to_owned(),
Component::Visibility(_) => "Visibility".to_owned(),
+ Component::Bricscad(_) => "BricscadVisibility".to_owned(),
Component::TableRow(_) => "TableRow".to_owned(),
Component::LookupOutput { column, .. } => format!("Lookup{column}"),
}
@@ -376,6 +377,7 @@ pub(crate) fn evaluate(
}
Component::Flip
| Component::Visibility(_)
+ | Component::Bricscad(_)
| Component::TableRow(_)
| Component::LookupOutput { .. } => unreachable!(),
}
diff --git a/src/scene/bricscad_parameters.rs b/src/scene/bricscad_parameters.rs
new file mode 100644
index 0000000000..026b597d36
--- /dev/null
+++ b/src/scene/bricscad_parameters.rs
@@ -0,0 +1,195 @@
+//! Visibility states of BricsCAD parametric blocks, read from the objects
+//! BricsCAD keeps them in.
+//!
+//! BricsCAD stores a parametric block's parameters in objects of its own
+//! classes under `BDM_DATABASE` in the block's extension dictionary. They are
+//! read as raw records (`ObjectType::Unknown`); this module decodes the few it
+//! needs from their DWG bytes (DWG 2010 and later):
+//!
+//! - `BDMDBFEATUREMANAGER` (`FEATURE_MANAGER`) lists the block's features.
+//! - A `BDMDBFEATUREDATA` of type `BdmConfigurationFeature` whose table type
+//! is `VisibilityStates` is one visibility parameter: its name and the state
+//! the block shows (`LastKeyValue`).
+//! - Its `BDMDBCONFIGURATIONTABLE` names the states (`KeyValues`).
+//! - The `BdmDbPersIdManager` (`PERSIDMANAGER`) of an anonymous copy names the
+//! block it was made from (`original.block`).
+//!
+//! A reference in a state other than the definition's shows such a copy, whose
+//! own features hold the state it shows; the members a state hides sit on the
+//! layer `*SUPPRESS` there.
+//!
+//! [`record`] decodes and encodes the objects; `switch` changes the state a
+//! reference shows the way BricsCAD does.
+
+use document::objects::ObjectType;
+use document::{Document, EntityType, Handle};
+
+mod author;
+pub(crate) mod record;
+mod switch;
+
+pub(crate) use author::{parameter_states, parameter_views, shown_layers, Action, ParameterView};
+
+pub(crate) use switch::can_switch;
+
+use record::{Properties, Record};
+
+/// A visibility parameter of a BricsCAD parametric block.
+#[derive(Debug, Clone, PartialEq)]
+pub struct VisibilityParameter {
+ pub name: String,
+ pub states: Vec,
+ /// The state the block shows, by index into `states`.
+ pub current: Option,
+ /// The parameter's feature in the block it was read from.
+ pub feature: Handle,
+}
+
+/// The visibility parameters of block record `block`, in the order its feature
+/// list holds them. Empty for a block BricsCAD did not make parametric, and
+/// for one whose objects cannot be read.
+pub fn visibility_parameters(document: &Document, block: Handle) -> Vec {
+ features(document, block)
+ .into_iter()
+ .filter_map(|feature| visibility_parameter(document, feature))
+ .collect()
+}
+
+/// The visibility parameters of the block reference `insert`, in the states
+/// it shows.
+pub fn reference_parameters(document: &Document, insert: Handle) -> Vec {
+ shown_block(document, insert)
+ .map(|block| visibility_parameters(document, block))
+ .unwrap_or_default()
+}
+
+/// The state parameter `name` of `owner` (block or model space) shows.
+pub fn current_state(document: &Document, owner: Handle, name: &str) -> Option {
+ visibility_parameters(document, owner)
+ .into_iter()
+ .find(|parameter| parameter.name.eq_ignore_ascii_case(name))
+ .and_then(|parameter| parameter.states.get(parameter.current?).cloned())
+}
+
+/// The block an anonymous copy of a BricsCAD parametric block was made from.
+pub fn original_block(document: &Document, block: Handle) -> Option {
+ let manager = database_entry(document, block, "PERSIDMANAGER")?;
+ let original = properties(document, manager)?
+ .get("original.block")?
+ .object()?;
+ (!original.is_null() && original != block).then_some(original)
+}
+
+/// The BricsCAD parametric block a reference shows, or shows a copy of.
+pub fn master_block(document: &Document, insert: Handle) -> Option {
+ let block = shown_block(document, insert)?;
+ let master = original_block(document, block).unwrap_or(block);
+ (!visibility_parameters(document, master).is_empty()).then_some(master)
+}
+
+/// The block record a reference shows.
+fn shown_block(document: &Document, insert: Handle) -> Option {
+ let Some(EntityType::Insert(reference)) = document.get_entity(insert) else {
+ return None;
+ };
+ document
+ .block_records
+ .get(&reference.block_name)
+ .map(|record| record.handle)
+}
+
+/// The features of `block`'s feature manager, in stored order.
+fn features(document: &Document, block: Handle) -> Vec {
+ database_entry(document, block, "FEATURE_MANAGER")
+ .and_then(|manager| properties(document, manager))
+ .and_then(|manager| {
+ Some(
+ manager
+ .get("Features")?
+ .items()?
+ .iter()
+ .filter_map(record::Value::object)
+ .collect(),
+ )
+ })
+ .unwrap_or_default()
+}
+
+fn visibility_parameter(document: &Document, feature: Handle) -> Option {
+ let handle = feature;
+ let feature = properties(document, feature)?;
+ if feature.text("Feature_type")? != "BdmConfigurationFeature"
+ || feature.text("TableType")? != "VisibilityStates"
+ {
+ return None;
+ }
+ let table = properties(document, feature.get("ConfigTable")?.object()?)?;
+ let states: Vec = table
+ .get("KeyValues")?
+ .items()?
+ .iter()
+ .map(|state| state.text().map(str::to_string))
+ .collect::>()?;
+ let name = table
+ .text("KeyName")
+ .or_else(|| feature.text("Name"))?
+ .to_string();
+ let current = feature
+ .text("LastKeyValue")
+ .and_then(|shown| states.iter().position(|state| state == shown));
+ Some(VisibilityParameter {
+ name,
+ states,
+ current,
+ feature: handle,
+ })
+}
+
+/// Entry `key` of the `BDM_DATABASE` dictionary in `owner`'s extension
+/// dictionary.
+fn database_entry(document: &Document, owner: Handle, key: &str) -> Option {
+ let dictionary = |handle: Handle| match document.objects.get(&handle)? {
+ ObjectType::Dictionary(dictionary) => Some(dictionary),
+ _ => None,
+ };
+ let extension = dictionary(document.extension_dictionary_handle(owner)?)?;
+ dictionary(extension.get("BDM_DATABASE")?)?.get(key)
+}
+
+/// The record of the BricsCAD object `handle`, decoded from the DWG record it
+/// was read from. `None` for any other object, a record from a DXF file or a
+/// DWG before 2010, and a record that does not decode in full.
+pub(crate) fn record(document: &Document, handle: Handle) -> Option {
+ let ObjectType::Unknown {
+ type_name,
+ raw_dwg_data: Some(data),
+ raw_dwg_handle_bits,
+ raw_dwg_version: Some(version),
+ ..
+ } = document.objects.get(&handle)?
+ else {
+ return None;
+ };
+ record::decode(type_name, data, *raw_dwg_handle_bits, *version)
+}
+
+/// The properties of the BricsCAD object `handle` whose record is a plain
+/// property list (see [`record`]).
+pub(crate) fn properties(document: &Document, handle: Handle) -> Option {
+ match record(document, handle)?.body {
+ record::Body::Properties(properties) => Some(properties),
+ _ => None,
+ }
+}
+
+#[cfg(test)]
+mod tests;
+
+#[cfg(test)]
+mod record_tests;
+
+#[cfg(test)]
+mod switch_tests;
+
+#[cfg(test)]
+pub(crate) mod author_tests;
diff --git a/src/scene/bricscad_parameters/author.rs b/src/scene/bricscad_parameters/author.rs
new file mode 100644
index 0000000000..4bc1b11538
--- /dev/null
+++ b/src/scene/bricscad_parameters/author.rs
@@ -0,0 +1,2287 @@
+//! VISIBILITYSTATES: authoring the visibility states of a BricsCAD
+//! parametric block in model space of the block's own drawing, stored the way
+//! BricsCAD stores them. (A block definition stores them the same way, but
+//! the anonymous copies its references show would keep the states they had,
+//! so the command offers model space only.)
+//!
+//! BricsCAD keeps, per owner (model space or block definition):
+//!
+//! - per visibility parameter a configuration feature with a table: one row
+//! per state, one column (`look_n`) per group of objects the parameter
+//! rules, 1 where the group shows in that state;
+//! - per group of objects that show and hide together a suppression feature
+//! whose variable is `1 - ` the product of the group's columns, one per
+//! parameter that rules the group, in parameter order;
+//! - the variables of all of them in the owner's associative network, and a
+//! dependency and a `BDMOBJECT` per object.
+//!
+//! An action on objects changes, for each object, the pattern of states in
+//! which the parameter shows it:
+//!
+//! - Add and Visible on an object the parameter does not rule: only in the
+//! state; Invisible: in every state but that one; Add on one it rules
+//! changes nothing;
+//! - Visible and Invisible on one it rules: set or clear the state;
+//! - Remove: the parameter no longer rules it.
+//!
+//! Objects whose patterns now agree with a group's join it. When all members
+//! of a group change alike the group changes in place; otherwise the changed
+//! ones leave it. A group left with no member, or ruled by no parameter, goes
+//! with its columns. A new state starts with every group hidden. After every
+//! action the owner shows its current states again. All of this is what
+//! BricsCAD V26 does for the same commands.
+
+use std::collections::{BTreeMap, BTreeSet};
+
+use document::objects::{
+ AssocAction, AssocActionDependency, AssocDependency, AssocEvalValue, AssocEvalVariant,
+ AssocNetwork, AssocValueDependency, AssocVariable, AssocVariableDependency, AssociativeData,
+ AssociativeObject, Dictionary, ObjectType,
+};
+use document::{Document, DxfVersion, EntityType, Handle};
+use rustc_hash::{FxHashMap, FxHashSet};
+
+use super::record::{Body, Properties, Record, Ref, Value};
+use super::switch::{apply_states, set_variable, store, unknown, SUPPRESS_LAYER};
+use super::{database_entry, features, record as read_record};
+use crate::scene::Scene;
+
+/// What VISIBILITYSTATES does to the picked objects.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum Action {
+ Add,
+ Remove,
+ Visible,
+ Invisible,
+ /// Make the state current.
+ Select,
+ /// Add the state, with every object the parameter rules hidden, and make
+ /// it current (the palette's "Add state"; the command makes a state with
+ /// its first action).
+ NewState,
+ /// Move the state one place up or down in the parameter's list, the
+ /// order Properties lists the states in.
+ MoveUp,
+ MoveDown,
+}
+
+const UNSUPPORTED: &str = "The visibility states here cannot be edited.";
+const OLD_FORMAT: &str = "Visibility states need a drawing in DWG 2010 format or later.";
+const NO_PARAMETER: &str = "No visibility parameter of that name.";
+const NO_STATE: &str = "No visibility state of that name.";
+const STATE_EXISTS: &str = "That visibility state exists already.";
+const CANNOT_MOVE: &str = "The visibility state cannot move further.";
+const BAD_NAME: &str = "Enter a name of letters, digits and underscores.";
+const NAME_TAKEN: &str = "That name is used by another variable.";
+const NO_OBJECTS: &str = "Select objects of the space being edited.";
+
+type Result = std::result::Result;
+
+/// The classes of BricsCAD's objects, as BricsCAD V26 registers them.
+const CLASSES: &[(&str, &str, &str)] = &[
+ (
+ "BDMDBFEATUREMANAGER",
+ "BdmDbFeatureManager",
+ "BricsCAD|Description: features data",
+ ),
+ (
+ "BDMDBFEATUREDATA",
+ "BdmDbFeatureData",
+ "BricsCAD|Description: features data",
+ ),
+ (
+ "BDMDBCONFIGURATIONTABLE",
+ "BdmDbConfigurationTable",
+ "BricsCAD|Description: configurations data",
+ ),
+ (
+ "BDMDBCONFIGVARREACTOR",
+ "BdmDbConfigVarReactor",
+ "BricsCAD|Description: features reactor",
+ ),
+ (
+ "BDMDBPERSIDREACTOR",
+ "BdmDbPersIdReactor",
+ "BricsCAD|Description: features reactor",
+ ),
+ (
+ "BdmDbPersIdManager",
+ "BdmDbPersIdManager",
+ "BricsCAD|Description: model data",
+ ),
+ (
+ "BDMDBCONSTRAINTMANAGER",
+ "BdmDbConstraintManager",
+ "BricsCAD|Description: 3D constraints data",
+ ),
+ (
+ "BDMOBJECT",
+ "BdmDbObject",
+ "BdmModule|Description: Driving Dimension",
+ ),
+ (
+ "BDMDBOBJECTDEPENDENCY",
+ "BdmDbObjectDependency",
+ "BricsCAD|Description: 3D constraints data",
+ ),
+ (
+ "BDMDBEXPRESSIONREACTOR",
+ "BdmDbExpressionReactor",
+ "BricsCAD|Description: features reactor",
+ ),
+];
+
+/// The names BricsCAD gives suppressions and objects, and the description of
+/// a column, in the language of its interface. A drawing that has some keeps
+/// its own.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) struct Naming {
+ pub(crate) suppression: &'static str,
+ pub(crate) description: &'static str,
+ pub(crate) object: &'static str,
+}
+
+impl Naming {
+ pub(crate) const ENGLISH: Self = Self {
+ suppression: "Suppress_",
+ description: "controlling visibility of entities in ",
+ object: "Entity_",
+ };
+ pub(crate) const GERMAN: Self = Self {
+ suppression: "Unterdrücken_",
+ description: "Steuerung der Sichtbarkeit von Objekten in ",
+ object: "Objekt_",
+ };
+
+ /// The names for the interface language `tag` (`de-DE`, …).
+ pub(crate) fn for_language(tag: &str) -> Self {
+ if tag.to_ascii_lowercase().starts_with("de") {
+ Self::GERMAN
+ } else {
+ Self::ENGLISH
+ }
+ }
+}
+
+/// The visibility parameters of an owner, with their states, for the prompts.
+/// A visibility parameter of an owner as the palette shows it.
+#[derive(Clone, Debug, PartialEq)]
+pub(crate) struct ParameterView {
+ pub(crate) name: String,
+ pub(crate) states: Vec,
+ /// The state shown, by index into `states`.
+ pub(crate) current: usize,
+ /// Each object the parameter rules, in drawing order, with whether it
+ /// shows in each state.
+ pub(crate) objects: Vec<(Handle, Vec)>,
+}
+
+/// The visibility parameters of `owner` with the objects each rules; `None`
+/// when they cannot be edited here.
+pub(crate) fn parameter_views(document: &Document, owner: Handle) -> Option> {
+ let setup = Setup::read(document, owner).ok()?;
+ let order: FxHashMap = owner_members(document, owner)
+ .into_iter()
+ .enumerate()
+ .map(|(k, handle)| (handle, k))
+ .collect();
+ Some(
+ setup
+ .parameters
+ .iter()
+ .enumerate()
+ .map(|(p, parameter)| {
+ let mut objects: Vec<(Handle, Vec)> = setup
+ .groups
+ .iter()
+ .enumerate()
+ .filter_map(|(g, group)| {
+ let pattern = setup.signature(g).remove(&p)?;
+ Some(
+ group
+ .members
+ .iter()
+ .map(move |member| (member.entity, pattern.clone())),
+ )
+ })
+ .flatten()
+ .collect();
+ objects.sort_by_key(|(entity, _)| order.get(entity).copied().unwrap_or(usize::MAX));
+ ParameterView {
+ name: parameter.name.clone(),
+ states: parameter.states.clone(),
+ current: parameter
+ .current
+ .min(parameter.states.len().saturating_sub(1)),
+ objects,
+ }
+ })
+ .collect(),
+ )
+}
+
+/// The layer each member of `owner` is on when no state hides it.
+pub(crate) fn shown_layers(document: &Document, owner: Handle) -> FxHashMap {
+ original_layers(document, owner)
+}
+
+pub(crate) fn parameter_states(document: &Document, owner: Handle) -> Vec<(String, Vec)> {
+ Setup::read(document, owner)
+ .map(|setup| {
+ setup
+ .parameters
+ .into_iter()
+ .map(|parameter| (parameter.name, parameter.states))
+ .collect()
+ })
+ .unwrap_or_default()
+}
+
+impl Scene {
+ /// VISIBILITYSTATES on `owner` (model space or a block definition): apply
+ /// `action` in `state` of `parameter` to `objects`, making the parameter
+ /// and the state when they are new. Names match regardless of case. On an
+ /// error the document may be part-way changed; callers work on a copy or
+ /// take an undo snapshot first.
+ pub(crate) fn edit_bricscad_visibility(
+ &mut self,
+ owner: Handle,
+ parameter: &str,
+ state: &str,
+ action: Action,
+ objects: &[Handle],
+ ) -> Result<()> {
+ let language = crate::i18n::loader()
+ .current_languages()
+ .into_iter()
+ .next()
+ .map(|language| language.to_string())
+ .unwrap_or_default();
+ let naming = Naming::for_language(&language);
+ self.edit_bricscad_visibility_named(owner, parameter, state, action, objects, naming)
+ }
+
+ /// [`Self::edit_bricscad_visibility`] with the names for a drawing that has
+ /// none yet.
+ pub(crate) fn edit_bricscad_visibility_named(
+ &mut self,
+ owner: Handle,
+ parameter: &str,
+ state: &str,
+ action: Action,
+ objects: &[Handle],
+ naming: Naming,
+ ) -> Result<()> {
+ if self.document.version < DxfVersion::AC1024 {
+ return Err(OLD_FORMAT);
+ }
+ // What the editor holds goes into the drawing first, so the reload at
+ // the end loses nothing.
+ self.sync_native_parametric_graph();
+ let document = &self.document;
+ let layers = original_layers(document, owner);
+ let mut setup = Setup::read(document, owner)?;
+ setup.learn_names(document, naming);
+ let parameter = parameter.trim();
+ let state = state.trim();
+ if state.is_empty() {
+ return Err(NO_STATE);
+ }
+ let p = match setup
+ .parameters
+ .iter()
+ .position(|p| p.name.eq_ignore_ascii_case(parameter))
+ {
+ Some(p) => p,
+ None if !matches!(action, Action::Add | Action::Visible | Action::Invisible) => {
+ return Err(NO_PARAMETER)
+ }
+ None => {
+ if !valid_name(parameter) {
+ return Err(BAD_NAME);
+ }
+ if setup
+ .variable_names(document)
+ .contains(¶meter.to_lowercase())
+ {
+ return Err(NAME_TAKEN);
+ }
+ setup.parameters.push(Parameter::new(parameter));
+ setup.parameters.len() - 1
+ }
+ };
+ let s = match setup.parameters[p]
+ .states
+ .iter()
+ .position(|s| s.eq_ignore_ascii_case(state))
+ {
+ Some(_) if action == Action::NewState => return Err(STATE_EXISTS),
+ Some(s) => s,
+ None if matches!(
+ action,
+ Action::Select | Action::Remove | Action::MoveUp | Action::MoveDown
+ ) =>
+ {
+ return Err(NO_STATE)
+ }
+ None => {
+ if !valid_name(state) {
+ return Err(BAD_NAME);
+ }
+ setup.parameters[p].add_state(state)
+ }
+ };
+ if matches!(action, Action::MoveUp | Action::MoveDown) {
+ let parameter = &mut setup.parameters[p];
+ let to = if action == Action::MoveUp {
+ s.checked_sub(1)
+ } else {
+ (s + 1 < parameter.states.len()).then_some(s + 1)
+ };
+ parameter.swap_states(s, to.ok_or(CANNOT_MOVE)?);
+ } else if matches!(action, Action::Select | Action::NewState) {
+ setup.parameters[p].current = s;
+ } else {
+ // BricsCAD works through a selection from its last object.
+ let mut seen = FxHashSet::default();
+ let objects: Vec = objects
+ .iter()
+ .rev()
+ .copied()
+ .filter(|handle| {
+ seen.insert(*handle)
+ && document
+ .get_entity(*handle)
+ .is_some_and(|entity| entity.common().owner_handle == owner)
+ })
+ .collect();
+ if objects.is_empty() {
+ return Err(NO_OBJECTS);
+ }
+ setup.act(p, s, action, &objects);
+ }
+ if setup.parameters[p].states.is_empty()
+ || setup.parameters[p].columns.is_empty() && setup.parameters[p].feature.is_none()
+ {
+ // A new parameter that came to rule nothing is not made.
+ return Err(NO_OBJECTS);
+ }
+ let states: BTreeMap = setup
+ .parameters
+ .iter()
+ .map(|parameter| {
+ (
+ parameter.name.clone(),
+ parameter.states[parameter.current.min(parameter.states.len() - 1)].clone(),
+ )
+ })
+ .collect();
+ let parameter_name = setup.parameters[p].name.clone();
+ setup.write(&mut self.document)?;
+ let members = owner_members(&self.document, owner);
+ apply_states(
+ &mut self.document,
+ owner,
+ &members,
+ &layers,
+ &states,
+ &BTreeSet::new(),
+ true,
+ )?;
+ let chosen = matches!(action, Action::Select | Action::NewState).then_some(parameter_name);
+ number_keys(&mut self.document, owner, chosen.as_deref())?;
+ self.load_named_parameters_from_document();
+ self.load_parametric_constraints_from_document();
+ Ok(())
+ }
+}
+
+/// Give each enabled key the number of the state it shows: BricsCAD shows the
+/// state of that number again when it next evaluates the owner. A disabled
+/// key is left alone; BricsCAD reads its state by name, and its variable may
+/// hold an expression of its own (openCirt's templates have keys showing the
+/// second state over a variable `0`). The key of `chosen`, the parameter a
+/// state was picked for, is set the way BricsCAD sets it when it shows a
+/// state: enabled, holding the state's number, its variable that number with
+/// no expression.
+fn number_keys(document: &mut Document, owner: Handle, chosen: Option<&str>) -> Result<()> {
+ for feature in features(document, owner) {
+ let Some(properties) = super::properties(document, feature) else {
+ continue;
+ };
+ if properties.text("Feature_type") != Some("BdmConfigurationFeature")
+ || properties.text("TableType") != Some("VisibilityStates")
+ {
+ continue;
+ }
+ let states: Vec = properties
+ .get("ConfigTable")
+ .and_then(Value::object)
+ .and_then(|table| super::properties(document, table))
+ .and_then(|table| {
+ table
+ .get("KeyValues")?
+ .items()?
+ .iter()
+ .map(|state| state.text().map(str::to_string))
+ .collect()
+ })
+ .ok_or(UNSUPPORTED)?;
+ let is_chosen = chosen.is_some_and(|name| {
+ properties
+ .text("Name")
+ .is_some_and(|own| own.eq_ignore_ascii_case(name))
+ });
+ let reactors: Vec = properties
+ .get("Reactors")
+ .and_then(Value::items)
+ .map(|items| items.iter().filter_map(Value::object).collect())
+ .unwrap_or_default();
+ for reactor in reactors {
+ let mut record = read_record(document, reactor).ok_or(UNSUPPORTED)?;
+ let properties = record.body.properties_mut();
+ if properties.get("IsKeyVar") != Some(&Value::Flag(true)) {
+ continue;
+ }
+ if !is_chosen && properties.get("IsEnabled") == Some(&Value::Flag(false)) {
+ continue;
+ }
+ let Some(row) = properties
+ .text("String")
+ .and_then(|state| states.iter().position(|name| name == state))
+ else {
+ continue;
+ };
+ let variable = properties
+ .get("VarId")
+ .and_then(Value::object)
+ .ok_or(UNSUPPORTED)?;
+ properties.set("Value", Value::Real(row as f64));
+ if is_chosen {
+ properties.set("IsEnabled", Value::Flag(true));
+ }
+ store(document, &record);
+ let real = AssocEvalVariant {
+ code: 40,
+ value: AssocEvalValue::Real(row as f64),
+ };
+ if is_chosen {
+ set_variable(document, variable, Some(String::new()), real)?;
+ } else {
+ let value = match variable_value(document, variable).value {
+ AssocEvalValue::Long(_) => AssocEvalVariant {
+ code: 90,
+ value: AssocEvalValue::Long(row as i32),
+ },
+ _ => real,
+ };
+ set_variable(document, variable, None, value)?;
+ }
+ }
+ }
+ Ok(())
+}
+
+/// Every member of `owner`, in drawing order.
+fn owner_members(document: &Document, owner: Handle) -> Vec {
+ document
+ .entities()
+ .filter(|entity| {
+ entity.common().owner_handle == owner
+ && !matches!(entity, EntityType::Block(_) | EntityType::BlockEnd(_))
+ })
+ .map(|entity| entity.common().handle)
+ .collect()
+}
+
+/// Each member's layer as it is when no state hides it: a member on
+/// `*SUPPRESS` takes the layer its suppression keeps for it.
+fn original_layers(document: &Document, owner: Handle) -> FxHashMap {
+ let mut kept: FxHashMap = FxHashMap::default();
+ for feature in features(document, owner) {
+ let Some(properties) = super::properties(document, feature) else {
+ continue;
+ };
+ if let Some(entries) = properties.get("aEntLayerKey").and_then(Value::entries) {
+ for (entity, layer) in entries {
+ if let (Some(entity), Some(layer)) = (entity.object(), layer.object()) {
+ kept.insert(entity, layer);
+ }
+ }
+ }
+ }
+ let layer_name = |handle: Handle| {
+ document
+ .layers
+ .iter()
+ .find(|layer| layer.handle == handle)
+ .map(|layer| layer.name.clone())
+ };
+ owner_members(document, owner)
+ .into_iter()
+ .filter_map(|member| {
+ let layer = &document.get_entity(member)?.common().layer;
+ let layer = if layer == SUPPRESS_LAYER {
+ kept.get(&member)
+ .and_then(|handle| layer_name(*handle))
+ .unwrap_or_else(|| "0".to_string())
+ } else {
+ layer.clone()
+ };
+ Some((member, layer))
+ })
+ .collect()
+}
+
+/// Letters (any script), digits and underscores, not starting with a digit.
+fn valid_name(name: &str) -> bool {
+ let mut chars = name.chars();
+ chars
+ .next()
+ .is_some_and(|first| first.is_alphabetic() || first == '_')
+ && chars.all(|c| c.is_alphanumeric() || c == '_')
+}
+
+/// One column of a parameter's table: a group's pattern under it.
+#[derive(Debug, Clone)]
+struct Column {
+ name: String,
+ values: Vec,
+ reactor: Option,
+ variable: Option,
+}
+
+#[derive(Debug, Clone)]
+struct Parameter {
+ name: String,
+ states: Vec,
+ current: usize,
+ columns: Vec,
+ feature: Option,
+ table: Option,
+ key_reactor: Option,
+ key_variable: Option,
+}
+
+impl Parameter {
+ fn new(name: &str) -> Self {
+ Self {
+ name: name.to_string(),
+ states: Vec::new(),
+ current: 0,
+ columns: Vec::new(),
+ feature: None,
+ table: None,
+ key_reactor: None,
+ key_variable: None,
+ }
+ }
+
+ /// A new state, in which every group is hidden.
+ /// Swap two states with their rows; the shown state stays shown.
+ fn swap_states(&mut self, a: usize, b: usize) {
+ self.states.swap(a, b);
+ for column in &mut self.columns {
+ column.values.swap(a, b);
+ }
+ if self.current == a {
+ self.current = b;
+ } else if self.current == b {
+ self.current = a;
+ }
+ }
+
+ fn add_state(&mut self, name: &str) -> usize {
+ self.states.push(name.to_string());
+ for column in &mut self.columns {
+ column.values.push(false);
+ }
+ self.states.len() - 1
+ }
+}
+
+#[derive(Debug, Clone)]
+struct Member {
+ entity: Handle,
+ dependency: Option,
+}
+
+#[derive(Debug, Clone)]
+struct Group {
+ name: String,
+ /// The columns the suppression multiplies: parameter index and column
+ /// name, in parameter order.
+ columns: Vec<(usize, String)>,
+ members: Vec,
+ feature: Option,
+ persid: Option,
+ expression: Option,
+ variable: Option,
+ /// The name of the group's variable; BricsCAD's own drawings have groups
+ /// whose variable is named after another group (`Unterdrücken_1` with
+ /// the variable `Unterdrücken_7`).
+ variable_name: String,
+ columns_changed: bool,
+}
+
+/// Per parameter, the states a group shows in.
+type Signature = BTreeMap>;
+
+/// One owner's visibility parameters and groups, read from its objects and
+/// written back.
+struct Setup {
+ owner: Handle,
+ parameters: Vec,
+ groups: Vec,
+ /// Columns, groups and dependencies that go, by their objects.
+ erased_columns: Vec,
+ erased_groups: Vec,
+ released: Vec,
+ suppress_prefix: Option,
+ description_prefix: Option,
+ object_prefix: Option,
+ /// The lowercased names of the network's variables that are no
+ /// parameter's, column's or group's.
+ foreign: FxHashSet,
+}
+
+impl Setup {
+ fn read(document: &Document, owner: Handle) -> Result {
+ let mut setup = Self {
+ owner,
+ parameters: Vec::new(),
+ groups: Vec::new(),
+ erased_columns: Vec::new(),
+ erased_groups: Vec::new(),
+ released: Vec::new(),
+ suppress_prefix: None,
+ description_prefix: None,
+ object_prefix: None,
+ foreign: FxHashSet::default(),
+ };
+ let variable = |handle: Handle| match document.objects.get(&handle) {
+ Some(ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::Variable(variable),
+ ..
+ })) => Some(variable),
+ _ => None,
+ };
+ let handles = |properties: &Properties, name: &str| -> Vec {
+ properties
+ .get(name)
+ .and_then(Value::items)
+ .map(|items| items.iter().filter_map(Value::object).collect())
+ .unwrap_or_default()
+ };
+ let mut suppressions = Vec::new();
+ for feature in features(document, owner) {
+ let properties = super::properties(document, feature).ok_or(UNSUPPORTED)?;
+ match properties.text("Feature_type") {
+ Some("BdmConfigurationFeature") => {
+ if properties.text("TableType") != Some("VisibilityStates") {
+ return Err(UNSUPPORTED);
+ }
+ let table_handle = properties
+ .get("ConfigTable")
+ .and_then(Value::object)
+ .ok_or(UNSUPPORTED)?;
+ let table = super::properties(document, table_handle).ok_or(UNSUPPORTED)?;
+ let texts = |key: &str| -> Option> {
+ table
+ .get(key)?
+ .items()?
+ .iter()
+ .map(|item| item.text().map(str::to_string))
+ .collect()
+ };
+ let states = texts("KeyValues").ok_or(UNSUPPORTED)?;
+ let names = texts("ColNames").ok_or(UNSUPPORTED)?;
+ let values: Vec = table
+ .get("DblValues")
+ .and_then(Value::items)
+ .and_then(|items| {
+ items
+ .iter()
+ .map(|item| match item {
+ Value::Real(value) => Some(*value),
+ _ => None,
+ })
+ .collect()
+ })
+ .ok_or(UNSUPPORTED)?;
+ if values.len() != states.len() * names.len() {
+ return Err(UNSUPPORTED);
+ }
+ let mut reactors: FxHashMap = FxHashMap::default();
+ let mut key = None;
+ for reactor in handles(&properties, "Reactors") {
+ let reactor_properties =
+ super::properties(document, reactor).ok_or(UNSUPPORTED)?;
+ let variable = reactor_properties
+ .get("VarId")
+ .and_then(Value::object)
+ .ok_or(UNSUPPORTED)?;
+ if reactor_properties.get("IsKeyVar") == Some(&Value::Flag(true)) {
+ key = Some((reactor, variable));
+ } else {
+ let name = reactor_properties
+ .text("VarName")
+ .ok_or(UNSUPPORTED)?
+ .to_string();
+ reactors.insert(name, (reactor, variable));
+ }
+ }
+ let (key_reactor, key_variable) = key.ok_or(UNSUPPORTED)?;
+ let columns = names
+ .iter()
+ .enumerate()
+ .map(|(c, name)| {
+ let (reactor, variable) = reactors.get(name).ok_or(UNSUPPORTED)?;
+ if setup.description_prefix.is_none() {
+ setup.description_prefix = description_prefix(document, *variable);
+ }
+ Ok(Column {
+ name: name.clone(),
+ values: (0..states.len())
+ .map(|row| values[row * names.len() + c] != 0.0)
+ .collect(),
+ reactor: Some(*reactor),
+ variable: Some(*variable),
+ })
+ })
+ .collect::>>()?;
+ let name = table
+ .text("KeyName")
+ .or_else(|| properties.text("Name"))
+ .ok_or(UNSUPPORTED)?
+ .to_string();
+ let current = properties
+ .text("LastKeyValue")
+ .and_then(|shown| states.iter().position(|state| state == shown))
+ .unwrap_or(0);
+ setup.parameters.push(Parameter {
+ name,
+ states,
+ current,
+ columns,
+ feature: Some(feature),
+ table: Some(table_handle),
+ key_reactor: Some(key_reactor),
+ key_variable: Some(key_variable),
+ });
+ }
+ Some("BdmSuppressFeature") => suppressions.push((feature, properties)),
+ // Model space of a drawing also holds the entries of block
+ // references; they are not this owner's parameters.
+ _ => {}
+ }
+ }
+ for (feature, properties) in suppressions {
+ let name = properties.text("Name").ok_or(UNSUPPORTED)?.to_string();
+ let mut persid = None;
+ let mut expression = None;
+ let mut members = Vec::new();
+ let mut suppress_variable = None;
+ for reactor in handles(&properties, "Reactors") {
+ let reactor_properties = super::properties(document, reactor).ok_or(UNSUPPORTED)?;
+ if reactor_properties.get("pers_ids").is_some() {
+ persid = Some(reactor);
+ for dependency in handles(&reactor_properties, "pers_ids") {
+ match read_record(document, dependency).map(|record| record.body) {
+ Some(Body::Dependency { entity, .. }) => members.push(Member {
+ entity: entity.handle,
+ dependency: Some(dependency),
+ }),
+ _ => return Err(UNSUPPORTED),
+ }
+ }
+ } else if let Some(variable) = reactor_properties.get("var").and_then(Value::object)
+ {
+ expression = Some(reactor);
+ suppress_variable = Some(variable);
+ }
+ }
+ let variable_handle = suppress_variable.ok_or(UNSUPPORTED)?;
+ let expression_text = &variable(variable_handle).ok_or(UNSUPPORTED)?.expression;
+ let factors: Vec = expression_text
+ .split_once('-')
+ .filter(|(one, _)| one.trim() == "1")
+ .map(|(_, product)| product.split('*').map(|f| f.trim().to_string()).collect())
+ .ok_or(UNSUPPORTED)?;
+ let mut columns = Vec::new();
+ for factor in factors {
+ let p = setup
+ .parameters
+ .iter()
+ .position(|p| p.columns.iter().any(|c| c.name == factor))
+ .ok_or(UNSUPPORTED)?;
+ columns.push((p, factor));
+ }
+ if setup.suppress_prefix.is_none() {
+ setup.suppress_prefix = name
+ .rsplit_once('_')
+ .filter(|(_, n)| n.parse::().is_ok())
+ .map(|(prefix, _)| format!("{prefix}_"));
+ }
+ setup.groups.push(Group {
+ name,
+ columns,
+ members,
+ feature: Some(feature),
+ persid: Some(persid.ok_or(UNSUPPORTED)?),
+ expression: Some(expression.ok_or(UNSUPPORTED)?),
+ variable: Some(variable_handle),
+ variable_name: variable(variable_handle).ok_or(UNSUPPORTED)?.name.clone(),
+ columns_changed: false,
+ });
+ }
+ // Each column belongs to one group.
+ let mut used = FxHashSet::default();
+ for group in &setup.groups {
+ for (_, column) in &group.columns {
+ if !used.insert(column.clone()) {
+ return Err(UNSUPPORTED);
+ }
+ }
+ }
+ if let Some(network) = owner_network(document, owner) {
+ let managed = setup.taken();
+ setup.foreign = document
+ .objects
+ .values()
+ .filter_map(|object| match object {
+ ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::Variable(variable),
+ ..
+ }) if variable.action.owning_network == network => {
+ Some(variable.name.to_lowercase())
+ }
+ _ => None,
+ })
+ .filter(|name| !managed.contains(name))
+ .collect();
+ }
+ Ok(setup)
+ }
+
+ /// Fill in the names the owner does not show: from the rest of the
+ /// drawing, else `naming`.
+ fn learn_names(&mut self, document: &Document, naming: Naming) {
+ if self.object_prefix.is_none() {
+ self.object_prefix = document.objects.iter().find_map(|(handle, object)| {
+ matches!(object, ObjectType::Unknown { type_name, .. } if type_name == "BDMOBJECT")
+ .then(|| read_record(document, *handle))
+ .flatten()
+ .and_then(|record| {
+ let name = record.body.properties().text("NAME")?.to_string();
+ let (prefix, number) = name.rsplit_once('_')?;
+ number.parse::().ok()?;
+ Some(format!("{prefix}_"))
+ })
+ });
+ }
+ if self.suppress_prefix.is_none() || self.description_prefix.is_none() {
+ for (handle, object) in &document.objects {
+ if !matches!(object, ObjectType::Unknown { type_name, .. } if type_name == "BDMDBFEATUREDATA")
+ {
+ continue;
+ }
+ let Some(properties) = super::properties(document, *handle) else {
+ continue;
+ };
+ if properties.text("Feature_type") != Some("BdmSuppressFeature") {
+ continue;
+ }
+ let Some(name) = properties.text("Name") else {
+ continue;
+ };
+ if self.suppress_prefix.is_none() {
+ self.suppress_prefix = name
+ .rsplit_once('_')
+ .filter(|(_, n)| n.parse::().is_ok())
+ .map(|(prefix, _)| format!("{prefix}_"));
+ }
+ if self.description_prefix.is_none() {
+ self.description_prefix =
+ document.objects.values().find_map(|object| match object {
+ ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::Variable(variable),
+ ..
+ }) => variable
+ .description
+ .strip_suffix(name)
+ .filter(|prefix| !prefix.is_empty())
+ .map(str::to_string),
+ _ => None,
+ });
+ }
+ if self.suppress_prefix.is_some() && self.description_prefix.is_some() {
+ break;
+ }
+ }
+ }
+ self.suppress_prefix
+ .get_or_insert_with(|| naming.suppression.to_string());
+ self.description_prefix
+ .get_or_insert_with(|| naming.description.to_string());
+ self.object_prefix
+ .get_or_insert_with(|| naming.object.to_string());
+ }
+
+ /// The lowercased names of the owner's variables.
+ /// The lowercased names a new column or group may not take: every
+ /// variable of the network but those this edit erases.
+ fn taken(&self) -> FxHashSet {
+ self.parameters
+ .iter()
+ .flat_map(|p| {
+ std::iter::once(p.name.to_lowercase())
+ .chain(p.columns.iter().map(|c| c.name.to_lowercase()))
+ })
+ .chain(
+ self.groups
+ .iter()
+ .flat_map(|g| [g.name.to_lowercase(), g.variable_name.to_lowercase()]),
+ )
+ .chain(self.foreign.iter().cloned())
+ .collect()
+ }
+
+ fn variable_names(&self, document: &Document) -> FxHashSet {
+ let mut names: FxHashSet = self
+ .parameters
+ .iter()
+ .flat_map(|p| {
+ std::iter::once(p.name.to_lowercase())
+ .chain(p.columns.iter().map(|c| c.name.to_lowercase()))
+ })
+ .chain(self.groups.iter().map(|g| g.name.to_lowercase()))
+ .collect();
+ if let Some(network) = owner_network(document, self.owner) {
+ for object in document.objects.values() {
+ if let ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::Variable(variable),
+ ..
+ }) = object
+ {
+ if variable.action.owning_network == network {
+ names.insert(variable.name.to_lowercase());
+ }
+ }
+ }
+ }
+ names
+ }
+
+ fn signature(&self, group: usize) -> Signature {
+ self.groups[group]
+ .columns
+ .iter()
+ .map(|(p, name)| {
+ let values = self.parameters[*p]
+ .columns
+ .iter()
+ .find(|column| &column.name == name)
+ .map(|column| column.values.clone())
+ .unwrap_or_default();
+ (*p, values)
+ })
+ .collect()
+ }
+
+ fn group_of(&self, entity: Handle) -> Option {
+ self.groups
+ .iter()
+ .position(|group| group.members.iter().any(|member| member.entity == entity))
+ }
+
+ /// Apply `action` in state `s` of parameter `p` to `objects`.
+ fn act(&mut self, p: usize, s: usize, action: Action, objects: &[Handle]) {
+ let states = self.parameters[p].states.len();
+ let mut changes: Vec<(Option, Signature, Handle)> = Vec::new();
+ for &entity in objects {
+ let group = self.group_of(entity);
+ let old = group.map(|g| self.signature(g)).unwrap_or_default();
+ let mut new = old.clone();
+ match (old.get(&p), action) {
+ (Some(_), Action::Add)
+ | (None, Action::Remove)
+ | (_, Action::Select | Action::NewState | Action::MoveUp | Action::MoveDown) => {}
+ (Some(_), Action::Remove) => {
+ new.remove(&p);
+ }
+ (Some(pattern), Action::Visible | Action::Invisible) => {
+ let mut pattern = pattern.clone();
+ pattern[s] = action == Action::Visible;
+ new.insert(p, pattern);
+ }
+ (None, Action::Add | Action::Visible) => {
+ new.insert(p, (0..states).map(|k| k == s).collect());
+ }
+ (None, Action::Invisible) => {
+ new.insert(p, (0..states).map(|k| k != s).collect());
+ }
+ }
+ if new != old {
+ changes.push((group, new, entity));
+ }
+ }
+ // Objects of one group that change alike change together.
+ let mut batches: Vec<(Option, Signature, Vec)> = Vec::new();
+ for (group, signature, entity) in changes {
+ match batches
+ .iter_mut()
+ .find(|(g, sig, _)| *g == group && *sig == signature)
+ {
+ Some((_, _, entities)) => entities.push(entity),
+ None => batches.push((group, signature, vec![entity])),
+ }
+ }
+ for (group, signature, entities) in batches {
+ let whole = group.is_some_and(|g| {
+ let members: BTreeSet =
+ self.groups[g].members.iter().map(|m| m.entity).collect();
+ members == entities.iter().copied().collect::>()
+ });
+ match group {
+ Some(g) if whole => self.reshape(g, &signature),
+ _ => {
+ let mut moved: Vec = Vec::new();
+ if let Some(g) = group {
+ let members = std::mem::take(&mut self.groups[g].members);
+ let (leaving, staying): (Vec<_>, Vec<_>) = members
+ .into_iter()
+ .partition(|member| entities.contains(&member.entity));
+ self.groups[g].members = staying;
+ moved = leaving;
+ }
+ for entity in &entities {
+ if !moved.iter().any(|member| member.entity == *entity) {
+ moved.push(Member {
+ entity: *entity,
+ dependency: None,
+ });
+ }
+ }
+ if signature.is_empty() {
+ self.released
+ .extend(moved.iter().filter_map(|member| member.dependency));
+ continue;
+ }
+ let target = (0..self.groups.len()).find(|&h| {
+ !self.groups[h].members.is_empty() && self.signature(h) == signature
+ });
+ match target {
+ Some(h) => self.groups[h].members.extend(moved),
+ None => self.add_group(&signature, moved),
+ }
+ }
+ }
+ }
+ // Groups left with no member go.
+ let mut g = 0;
+ while g < self.groups.len() {
+ if self.groups[g].members.is_empty() {
+ self.erase_group(g);
+ } else {
+ g += 1;
+ }
+ }
+ }
+
+ /// Change group `g` to `signature` in place.
+ fn reshape(&mut self, g: usize, signature: &Signature) {
+ if signature.is_empty() {
+ let members = std::mem::take(&mut self.groups[g].members);
+ self.released
+ .extend(members.into_iter().filter_map(|member| member.dependency));
+ return;
+ }
+ for (&p, pattern) in signature {
+ let existing = self.groups[g]
+ .columns
+ .iter()
+ .find(|(q, _)| *q == p)
+ .map(|(_, name)| name.clone());
+ match existing {
+ Some(name) => {
+ if let Some(column) = self.parameters[p]
+ .columns
+ .iter_mut()
+ .find(|c| c.name == name)
+ {
+ column.values = pattern.clone();
+ }
+ }
+ None => {
+ let name = self.add_column(p, pattern.clone());
+ let group = &mut self.groups[g];
+ group.columns.push((p, name));
+ group.columns.sort_by_key(|(q, _)| *q);
+ group.columns_changed = true;
+ }
+ }
+ }
+ let dropped: Vec<(usize, String)> = self.groups[g]
+ .columns
+ .iter()
+ .filter(|(p, _)| !signature.contains_key(p))
+ .cloned()
+ .collect();
+ for (p, name) in dropped {
+ self.erase_column(p, &name);
+ self.groups[g].columns.retain(|(_, column)| *column != name);
+ self.groups[g].columns_changed = true;
+ }
+ }
+
+ fn add_group(&mut self, signature: &Signature, members: Vec) {
+ let prefix = self.suppress_prefix.clone().unwrap_or_default();
+ let taken = self.taken();
+ let mut number = self
+ .groups
+ .iter()
+ .filter_map(|group| group.name.strip_prefix(&prefix)?.parse::().ok())
+ .max()
+ .unwrap_or(0)
+ + 1;
+ // BricsCAD finds variables by name: a second variable of the same
+ // name gets the two mixed up.
+ while taken.contains(&format!("{prefix}{number}").to_lowercase()) {
+ number += 1;
+ }
+ let name = format!("{prefix}{number}");
+ let columns = signature
+ .iter()
+ .map(|(&p, pattern)| (p, self.add_column(p, pattern.clone())))
+ .collect();
+ self.groups.push(Group {
+ variable_name: name.clone(),
+ name,
+ columns,
+ members,
+ feature: None,
+ persid: None,
+ expression: None,
+ variable: None,
+ columns_changed: true,
+ });
+ }
+
+ /// A new column of parameter `p`, named with the lowest free number.
+ fn add_column(&mut self, p: usize, values: Vec) -> String {
+ let taken = self.taken();
+ let number = (1..)
+ .find(|n| !taken.contains(&format!("look_{n}")))
+ .unwrap_or(1);
+ let name = format!("look_{number}");
+ self.parameters[p].columns.push(Column {
+ name: name.clone(),
+ values,
+ reactor: None,
+ variable: None,
+ });
+ name
+ }
+
+ fn erase_column(&mut self, p: usize, name: &str) {
+ if let Some(index) = self.parameters[p]
+ .columns
+ .iter()
+ .position(|c| c.name == name)
+ {
+ let column = self.parameters[p].columns.remove(index);
+ self.erased_columns.push(column);
+ }
+ }
+
+ fn erase_group(&mut self, g: usize) {
+ let group = self.groups.remove(g);
+ for (p, name) in &group.columns {
+ self.erase_column(*p, name);
+ }
+ self.released
+ .extend(group.members.iter().filter_map(|member| member.dependency));
+ self.erased_groups.push(group);
+ }
+
+ /// Write the setup back into the owner's objects.
+ fn write(mut self, document: &mut Document) -> Result<()> {
+ let version = document.version;
+ let types = Types::ensure(document);
+ let database = ensure_database(document, self.owner, &types, version)?;
+ let network = ensure_network(document, self.owner)?;
+ let description_prefix = self.description_prefix.clone().unwrap_or_default();
+ let object_prefix = self.object_prefix.clone().unwrap_or_default();
+ let mut new_features = Vec::new();
+
+ // Columns and groups that go: their variables leave the network
+ // after the suppressions that read them are rewritten below.
+ let mut erased_variables: Vec = Vec::new();
+ let mut erased_objects: Vec = Vec::new();
+ for column in &self.erased_columns {
+ erased_variables.extend(column.variable);
+ erased_objects.extend(column.reactor);
+ }
+ for group in &self.erased_groups {
+ erased_variables.extend(group.variable);
+ erased_objects.extend(group.feature);
+ erased_objects.extend(group.persid);
+ erased_objects.extend(group.expression);
+ }
+
+ // Group names, for the columns' descriptions.
+ let mut column_group: FxHashMap = FxHashMap::default();
+ for group in &self.groups {
+ for (_, column) in &group.columns {
+ column_group.insert(column.clone(), group.name.clone());
+ }
+ }
+
+ for parameter in &mut self.parameters {
+ let current = parameter
+ .current
+ .min(parameter.states.len().saturating_sub(1));
+ let key_variable = match parameter.key_variable {
+ Some(variable) => variable,
+ None => new_variable(
+ document,
+ network,
+ ¶meter.name,
+ "",
+ "",
+ AssocEvalVariant {
+ code: 40,
+ value: AssocEvalValue::Real(0.0),
+ },
+ ),
+ };
+ parameter.key_variable = Some(key_variable);
+ let feature = parameter
+ .feature
+ .unwrap_or_else(|| document.allocate_handle());
+ let table = parameter
+ .table
+ .unwrap_or_else(|| document.allocate_handle());
+ if parameter.key_reactor.is_none() {
+ let handle = document.allocate_handle();
+ let record = Record::new(
+ types.config_reactor,
+ handle,
+ Ref::new(feature, 4),
+ Body::Properties(variable_reactor(
+ true,
+ ¶meter.states[current],
+ 0.0,
+ key_variable,
+ ¶meter.name,
+ )),
+ version,
+ );
+ document
+ .objects
+ .insert(handle, unknown("BDMDBCONFIGVARREACTOR", &record));
+ add_reactor(document, key_variable, handle);
+ parameter.key_reactor = Some(handle);
+ }
+ for column in &mut parameter.columns {
+ let value = column.values.get(current).copied().unwrap_or(false);
+ let variable = match column.variable {
+ Some(variable) => variable,
+ None => {
+ let group = column_group.get(&column.name).cloned().unwrap_or_default();
+ new_variable(
+ document,
+ network,
+ &column.name,
+ "",
+ &format!("{description_prefix}{group}"),
+ AssocEvalVariant {
+ code: 40,
+ value: AssocEvalValue::Real(f64::from(u8::from(value))),
+ },
+ )
+ }
+ };
+ column.variable = Some(variable);
+ if column.reactor.is_none() {
+ let handle = document.allocate_handle();
+ let record = Record::new(
+ types.config_reactor,
+ handle,
+ Ref::new(feature, 4),
+ Body::Properties(variable_reactor(
+ false,
+ "",
+ f64::from(u8::from(value)),
+ variable,
+ &column.name,
+ )),
+ version,
+ );
+ document
+ .objects
+ .insert(handle, unknown("BDMDBCONFIGVARREACTOR", &record));
+ add_reactor(document, variable, handle);
+ column.reactor = Some(handle);
+ }
+ }
+ let table_record = Record::new(
+ types.table,
+ table,
+ Ref::new(feature, 4),
+ Body::Properties(table_properties(parameter)),
+ version,
+ );
+ document
+ .objects
+ .insert(table, unknown("BDMDBCONFIGURATIONTABLE", &table_record));
+ let mut reactors = vec![parameter.key_reactor.unwrap_or_default()];
+ reactors.extend(parameter.columns.iter().filter_map(|column| column.reactor));
+ let reactors = Value::List {
+ element: 8,
+ items: reactors
+ .into_iter()
+ .map(|reactor| Value::Object {
+ kind: 3,
+ target: Ref::new(reactor, 3),
+ })
+ .collect(),
+ };
+ match parameter.feature {
+ Some(existing) => {
+ let mut record = read_record(document, existing).ok_or(UNSUPPORTED)?;
+ let properties = record.body.properties_mut();
+ properties.set("Reactors", reactors);
+ properties.set(
+ "LastKeyValue",
+ Value::Text(parameter.states[current].clone()),
+ );
+ store(document, &record);
+ }
+ None => {
+ let record = Record::new(
+ types.feature,
+ feature,
+ Ref::new(database.features, 4),
+ Body::Properties(Properties(vec![
+ ("_ver".into(), Value::Byte(1)),
+ ("CloningType".into(), Value::Flag(true)),
+ (
+ "ConfigTable".into(),
+ Value::Object {
+ kind: 3,
+ target: Ref::new(table, 3),
+ },
+ ),
+ (
+ "Feature_type".into(),
+ Value::Text("BdmConfigurationFeature".into()),
+ ),
+ ("FreeConfig".into(), Value::Text("Custom".into())),
+ (
+ "LastKeyValue".into(),
+ Value::Text(parameter.states[current].clone()),
+ ),
+ ("Name".into(), Value::Text(parameter.name.clone())),
+ ("Reactors".into(), reactors),
+ ("Status".into(), Value::Integer(1)),
+ ("TableType".into(), Value::Text("VisibilityStates".into())),
+ ])),
+ version,
+ );
+ document
+ .objects
+ .insert(feature, unknown("BDMDBFEATUREDATA", &record));
+ new_features.push(feature);
+ parameter.feature = Some(feature);
+ parameter.table = Some(table);
+ }
+ }
+ }
+
+ // The objects every member needs.
+ let entity_objects = entity_objects(document, self.owner, database.constraints);
+ let mut new_objects: Vec = Vec::new();
+ let mut new_dependencies: Vec = Vec::new();
+ let mut next_object_number = entity_objects
+ .values()
+ .filter_map(|object| {
+ read_record(document, *object)?
+ .body
+ .properties()
+ .text("NAME")?
+ .strip_prefix(object_prefix.as_str())?
+ .parse::()
+ .ok()
+ })
+ .max()
+ .unwrap_or(0)
+ + 1;
+ let mut entity_objects = entity_objects;
+
+ let variables_by_name: FxHashMap = self
+ .parameters
+ .iter()
+ .flat_map(|p| p.columns.iter())
+ .filter_map(|column| Some((column.name.clone(), column.variable?)))
+ .collect();
+ for group in &mut self.groups {
+ let expression = format!(
+ "1 - {}",
+ group
+ .columns
+ .iter()
+ .map(|(_, name)| name.as_str())
+ .collect::>()
+ .join(" * ")
+ );
+ let reads: Vec = group
+ .columns
+ .iter()
+ .filter_map(|(_, name)| variables_by_name.get(name).copied())
+ .collect();
+ let variable = match group.variable {
+ Some(variable) => {
+ if group.columns_changed {
+ set_expression(document, variable, &expression, &reads);
+ }
+ variable
+ }
+ None => {
+ let variable = new_variable(
+ document,
+ network,
+ &group.name,
+ &expression,
+ "",
+ AssocEvalVariant {
+ code: 90,
+ value: AssocEvalValue::Long(0),
+ },
+ );
+ set_expression(document, variable, &expression, &reads);
+ variable
+ }
+ };
+ group.variable = Some(variable);
+ let feature = group.feature.unwrap_or_else(|| document.allocate_handle());
+ let persid = group.persid.unwrap_or_else(|| document.allocate_handle());
+ let expression_reactor = group
+ .expression
+ .unwrap_or_else(|| document.allocate_handle());
+ if group.feature.is_none() {
+ let record = Record::new(
+ types.feature,
+ feature,
+ Ref::new(database.features, 4),
+ Body::Properties(Properties(vec![
+ ("_ver".into(), Value::Byte(1)),
+ (
+ "Feature_type".into(),
+ Value::Text("BdmSuppressFeature".into()),
+ ),
+ ("Name".into(), Value::Text(group.name.clone())),
+ (
+ "Reactors".into(),
+ Value::List {
+ element: 8,
+ items: [persid, expression_reactor]
+ .into_iter()
+ .map(|reactor| Value::Object {
+ kind: 3,
+ target: Ref::new(reactor, 3),
+ })
+ .collect(),
+ },
+ ),
+ ("Status".into(), Value::Integer(0)),
+ (
+ "aEntLayerKey".into(),
+ Value::Map {
+ key: 8,
+ value: 8,
+ entries: Vec::new(),
+ },
+ ),
+ ])),
+ version,
+ );
+ document
+ .objects
+ .insert(feature, unknown("BDMDBFEATUREDATA", &record));
+ new_features.push(feature);
+ let record = Record::new(
+ types.expression_reactor,
+ expression_reactor,
+ Ref::new(feature, 4),
+ Body::Properties(Properties(vec![
+ ("_ver".into(), Value::Byte(1)),
+ ("deleteOnErase".into(), Value::Flag(true)),
+ ("expr".into(), Value::Text("1".into())),
+ ("prop".into(), Value::Text("suppress".into())),
+ ("react".into(), Value::Flag(false)),
+ ("strType".into(), Value::Flag(false)),
+ ("value".into(), Value::Real(0.0)),
+ (
+ "var".into(),
+ Value::Object {
+ kind: 0,
+ target: Ref::new(variable, 4),
+ },
+ ),
+ ])),
+ version,
+ );
+ document.objects.insert(
+ expression_reactor,
+ unknown("BDMDBEXPRESSIONREACTOR", &record),
+ );
+ add_reactor(document, variable, expression_reactor);
+ group.feature = Some(feature);
+ group.expression = Some(expression_reactor);
+ }
+ // Members: a dependency each, on this group's reactor.
+ let mut dependencies = Vec::with_capacity(group.members.len());
+ for member in &mut group.members {
+ let dependency = match member.dependency {
+ Some(dependency) => {
+ let mut record = read_record(document, dependency).ok_or(UNSUPPORTED)?;
+ if record.reactors.iter().map(|r| r.handle).ne([persid]) {
+ record.reactors = vec![Ref::new(persid, 4)];
+ store(document, &record);
+ }
+ dependency
+ }
+ None => {
+ let handle = document.allocate_handle();
+ let mut record = Record::new(
+ types.dependency,
+ handle,
+ Ref::new(database.dependencies, 4),
+ Body::Dependency {
+ properties: Properties::default(),
+ tail: 0,
+ entity: Ref::new(member.entity, 5),
+ },
+ version,
+ );
+ record.reactors = vec![Ref::new(persid, 4)];
+ document
+ .objects
+ .insert(handle, unknown("BDMDBOBJECTDEPENDENCY", &record));
+ new_dependencies.push(handle);
+ // The member's object lists the dependency.
+ match entity_objects.get(&member.entity) {
+ Some(&object) => {
+ let mut object_record =
+ read_record(document, object).ok_or(UNSUPPORTED)?;
+ let Some(Value::List { items, .. }) = object_record
+ .body
+ .properties_mut()
+ .get_mut("PersIdDependencies")
+ else {
+ return Err(UNSUPPORTED);
+ };
+ items.push(Value::Object {
+ kind: 0,
+ target: Ref::new(handle, 4),
+ });
+ store(document, &object_record);
+ }
+ None => {
+ let object = document.allocate_handle();
+ let record = Record::new(
+ types.object,
+ object,
+ Ref::new(database.constraints, 4),
+ Body::Object {
+ lead: 5,
+ lead_count: 0,
+ entity: Ref::new(member.entity, 4),
+ properties: Properties(vec![
+ (
+ "NAME".into(),
+ Value::Text(format!(
+ "{object_prefix}{next_object_number}"
+ )),
+ ),
+ (
+ "PersIdDependencies".into(),
+ Value::List {
+ element: 8,
+ items: vec![Value::Object {
+ kind: 0,
+ target: Ref::new(handle, 4),
+ }],
+ },
+ ),
+ ]),
+ tail: 0,
+ },
+ version,
+ );
+ next_object_number += 1;
+ document
+ .objects
+ .insert(object, unknown("BDMOBJECT", &record));
+ new_objects.push(object);
+ entity_objects.insert(member.entity, object);
+ if let Some(entity) = document.get_entity_mut(member.entity) {
+ entity.common_mut().reactors.push(object);
+ }
+ }
+ }
+ handle
+ }
+ };
+ member.dependency = Some(dependency);
+ dependencies.push(dependency);
+ }
+ let persid_record = Record::new(
+ types.persid_reactor,
+ persid,
+ Ref::new(feature, 4),
+ Body::Properties(Properties(vec![
+ ("_ver".into(), Value::Byte(1)),
+ ("mask".into(), Value::Integer(1)),
+ (
+ "pers_ids".into(),
+ Value::List {
+ element: 8,
+ items: dependencies
+ .iter()
+ .map(|dependency| Value::Object {
+ kind: 0,
+ target: Ref::new(*dependency, 4),
+ })
+ .collect(),
+ },
+ ),
+ ("tag".into(), Value::Integer(0)),
+ ])),
+ version,
+ );
+ match group.persid {
+ Some(existing) => {
+ let mut record = read_record(document, existing).ok_or(UNSUPPORTED)?;
+ record.body = persid_record.body;
+ store(document, &record);
+ }
+ None => {
+ document
+ .objects
+ .insert(persid, unknown("BDMDBPERSIDREACTOR", &persid_record));
+ group.persid = Some(persid);
+ }
+ }
+ }
+
+ // Dependencies of objects no group rules any more go; their objects
+ // stay, as BricsCAD keeps them, with the dependency struck off.
+ for &dependency in &self.released {
+ for &object in entity_objects.values() {
+ let Some(mut record) = read_record(document, object) else {
+ continue;
+ };
+ if let Some(Value::List { items, .. }) =
+ record.body.properties_mut().get_mut("PersIdDependencies")
+ {
+ let before = items.len();
+ items.retain(|item| item.object() != Some(dependency));
+ if items.len() != before {
+ store(document, &record);
+ }
+ }
+ }
+ erased_objects.push(dependency);
+ }
+
+ for variable in &erased_variables {
+ erase_variable(document, network, *variable);
+ }
+ for object in &erased_objects {
+ document.objects.remove(object);
+ }
+ let erased: FxHashSet = erased_objects.iter().copied().collect();
+
+ // The managers list what was added and drop what went.
+ let mut record = read_record(document, database.features).ok_or(UNSUPPORTED)?;
+ if let Some(Value::List { items, .. }) = record.body.properties_mut().get_mut("Features") {
+ items.retain(|item| item.object().is_none_or(|h| !erased.contains(&h)));
+ items.extend(new_features.iter().map(|feature| Value::Object {
+ kind: 3,
+ target: Ref::new(*feature, 3),
+ }));
+ }
+ store(document, &record);
+ let mut record = read_record(document, database.dependencies).ok_or(UNSUPPORTED)?;
+ if let Some(Value::List { items, .. }) = record.body.properties_mut().get_mut("deps") {
+ items.retain(|item| item.object().is_none_or(|h| !erased.contains(&h)));
+ items.extend(new_dependencies.iter().map(|dependency| Value::Object {
+ kind: 3,
+ target: Ref::new(*dependency, 3),
+ }));
+ }
+ store(document, &record);
+ if !new_objects.is_empty() {
+ let mut record = read_record(document, database.constraints).ok_or(UNSUPPORTED)?;
+ let Body::ConstraintManager {
+ counts, children, ..
+ } = &mut record.body
+ else {
+ return Err(UNSUPPORTED);
+ };
+ let at = usize::try_from(counts[1]).map_err(|_| UNSUPPORTED)?;
+ for (k, object) in new_objects.iter().enumerate() {
+ children.insert((at + k).min(children.len()), Ref::new(*object, 3));
+ }
+ counts[1] += new_objects.len() as i32;
+ store(document, &record);
+ }
+ Ok(())
+ }
+}
+
+/// The prefix of a column variable's description, the text before the name
+/// of the suppression it controls.
+fn description_prefix(document: &Document, variable: Handle) -> Option {
+ let Some(ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::Variable(variable),
+ ..
+ })) = document.objects.get(&variable)
+ else {
+ return None;
+ };
+ let (prefix, _) = variable.description.rsplit_once(' ')?;
+ Some(format!("{prefix} "))
+}
+
+fn table_properties(parameter: &Parameter) -> Properties {
+ let rows = parameter.states.len();
+ let mut values = Vec::with_capacity(rows * parameter.columns.len());
+ for row in 0..rows {
+ for column in ¶meter.columns {
+ values.push(column.values.get(row).copied().unwrap_or(false));
+ }
+ }
+ let texts = |items: Vec| Value::List {
+ element: 2,
+ items: items.into_iter().map(Value::Text).collect(),
+ };
+ Properties(vec![
+ (
+ "ColNames".into(),
+ texts(parameter.columns.iter().map(|c| c.name.clone()).collect()),
+ ),
+ (
+ "ColNum".into(),
+ Value::Integer(parameter.columns.len() as i32),
+ ),
+ (
+ "ColTypes".into(),
+ Value::List {
+ element: 3,
+ items: parameter
+ .columns
+ .iter()
+ .map(|_| Value::Integer(0))
+ .collect(),
+ },
+ ),
+ (
+ "DblValues".into(),
+ Value::List {
+ element: 4,
+ items: values
+ .iter()
+ .map(|v| Value::Real(f64::from(u8::from(*v))))
+ .collect(),
+ },
+ ),
+ ("KeyName".into(), Value::Text(parameter.name.clone())),
+ ("KeyType".into(), Value::Integer(1)),
+ ("KeyValues".into(), texts(parameter.states.clone())),
+ ("RowNum".into(), Value::Integer(rows as i32)),
+ (
+ "Values".into(),
+ texts(
+ values
+ .iter()
+ .map(|v| if *v { "1".into() } else { "0".into() })
+ .collect(),
+ ),
+ ),
+ ])
+}
+
+fn variable_reactor(
+ key: bool,
+ string: &str,
+ value: f64,
+ variable: Handle,
+ name: &str,
+) -> Properties {
+ Properties(vec![
+ ("_ver".into(), Value::Byte(1)),
+ ("DeleteVarOnErase".into(), Value::Flag(true)),
+ ("IsEnabled".into(), Value::Flag(true)),
+ ("IsKeyVar".into(), Value::Flag(key)),
+ ("IsString".into(), Value::Flag(key)),
+ ("String".into(), Value::Text(string.to_string())),
+ ("Value".into(), Value::Real(value)),
+ (
+ "VarId".into(),
+ Value::Object {
+ kind: 0,
+ target: Ref::new(variable, 4),
+ },
+ ),
+ ("VarName".into(), Value::Text(name.to_string())),
+ ])
+}
+
+/// The type numbers of BricsCAD's classes in this drawing.
+struct Types {
+ feature_manager: u16,
+ feature: u16,
+ table: u16,
+ config_reactor: u16,
+ persid_reactor: u16,
+ persid_manager: u16,
+ constraint_manager: u16,
+ object: u16,
+ dependency: u16,
+ expression_reactor: u16,
+}
+
+impl Types {
+ fn ensure(document: &mut Document) -> Self {
+ crate::scene::dwg_native_constraints::ensure_associative_classes_registered(document);
+ let mut number = |dxf: &str| -> u16 {
+ let (dxf, cpp, application) = CLASSES
+ .iter()
+ .find(|(name, ..)| *name == dxf)
+ .copied()
+ .unwrap_or((dxf, dxf, ""));
+ if document.classes.get_by_name(dxf).is_none() {
+ document.classes.add_or_update(document::classes::DxfClass {
+ dxf_name: dxf.to_string(),
+ cpp_class_name: cpp.to_string(),
+ application_name: application.to_string(),
+ proxy_flags: document::classes::ProxyFlags(1025),
+ instance_count: 0,
+ was_zombie: false,
+ is_an_entity: false,
+ class_number: 0,
+ item_class_id: 0x1F3,
+ dwg_version: 33,
+ maintenance_version: 55,
+ unknown1: 0,
+ unknown2: 0,
+ });
+ }
+ document
+ .classes
+ .get_by_name(dxf)
+ .map_or(0, |class| class.class_number as u16)
+ };
+ Self {
+ feature_manager: number("BDMDBFEATUREMANAGER"),
+ feature: number("BDMDBFEATUREDATA"),
+ table: number("BDMDBCONFIGURATIONTABLE"),
+ config_reactor: number("BDMDBCONFIGVARREACTOR"),
+ persid_reactor: number("BDMDBPERSIDREACTOR"),
+ persid_manager: number("BdmDbPersIdManager"),
+ constraint_manager: number("BDMDBCONSTRAINTMANAGER"),
+ object: number("BDMOBJECT"),
+ dependency: number("BDMDBOBJECTDEPENDENCY"),
+ expression_reactor: number("BDMDBEXPRESSIONREACTOR"),
+ }
+ }
+}
+
+struct Database {
+ features: Handle,
+ dependencies: Handle,
+ constraints: Handle,
+}
+
+/// The owner's `BDM_DATABASE` with its three managers, made when missing.
+fn ensure_database(
+ document: &mut Document,
+ owner: Handle,
+ types: &Types,
+ version: DxfVersion,
+) -> Result {
+ if let (Some(features), Some(dependencies), Some(constraints)) = (
+ database_entry(document, owner, "FEATURE_MANAGER"),
+ database_entry(document, owner, "PERSIDMANAGER"),
+ database_entry(document, owner, "BDM_DATABASE"),
+ ) {
+ return Ok(Database {
+ features,
+ dependencies,
+ constraints,
+ });
+ }
+ let extension = document.ensure_extension_dictionary(owner);
+ if matches!(
+ document.objects.get(&extension),
+ Some(ObjectType::Dictionary(dictionary)) if dictionary.get("BDM_DATABASE").is_some()
+ ) {
+ // A database without its three managers is not one this writes into.
+ return Err(UNSUPPORTED);
+ }
+ let [dictionary, features, dependencies, constraints] =
+ [(); 4].map(|_| document.allocate_handle());
+ let mut database = Dictionary::new();
+ database.handle = dictionary;
+ database.owner = extension;
+ database.reactors = vec![extension];
+ database.entries = vec![
+ ("FEATURE_MANAGER".into(), features),
+ ("PERSIDMANAGER".into(), dependencies),
+ ("BDM_DATABASE".into(), constraints),
+ ];
+ document
+ .objects
+ .insert(dictionary, ObjectType::Dictionary(database));
+ let managers = [
+ (
+ "BDMDBFEATUREMANAGER",
+ types.feature_manager,
+ features,
+ Body::Properties(Properties(vec![
+ ("_ver".into(), Value::Byte(1)),
+ (
+ "ColorPolicy".into(),
+ Value::Object {
+ kind: 3,
+ target: Ref::new(Handle::NULL, 3),
+ },
+ ),
+ (
+ "Contexts".into(),
+ Value::List {
+ element: 8,
+ items: Vec::new(),
+ },
+ ),
+ (
+ "Features".into(),
+ Value::List {
+ element: 8,
+ items: Vec::new(),
+ },
+ ),
+ ])),
+ ),
+ (
+ "BdmDbPersIdManager",
+ types.persid_manager,
+ dependencies,
+ Body::Properties(Properties(vec![
+ ("_ver".into(), Value::Byte(1)),
+ (
+ "deps".into(),
+ Value::List {
+ element: 8,
+ items: Vec::new(),
+ },
+ ),
+ ])),
+ ),
+ (
+ "BDMDBCONSTRAINTMANAGER",
+ types.constraint_manager,
+ constraints,
+ Body::ConstraintManager {
+ counts: [2, 0, 0, 0, 0],
+ children: Vec::new(),
+ settings: Properties(vec![(
+ "DesignIntentSettings".into(),
+ Value::Text("DISABLE_HEURISTIC_BODY_FIX".into()),
+ )]),
+ },
+ ),
+ ];
+ for (class, object_type, handle, body) in managers {
+ let mut record = Record::new(object_type, handle, Ref::new(dictionary, 4), body, version);
+ record.reactors = vec![Ref::new(dictionary, 4)];
+ document.objects.insert(handle, unknown(class, &record));
+ }
+ if let Some(ObjectType::Dictionary(extension)) = document.objects.get_mut(&extension) {
+ extension.add_entry("BDM_DATABASE", dictionary);
+ }
+ Ok(Database {
+ features,
+ dependencies,
+ constraints,
+ })
+}
+
+/// The owner's associative network.
+fn owner_network(document: &Document, owner: Handle) -> Option {
+ let dictionary = |handle: Handle| match document.objects.get(&handle)? {
+ ObjectType::Dictionary(dictionary) => Some(dictionary),
+ _ => None,
+ };
+ let extension = dictionary(document.extension_dictionary_handle(owner)?)?;
+ let mut network = extension.get("ACAD_ASSOCNETWORK")?;
+ while let Some(inner) = dictionary(network) {
+ network = inner.get("ACAD_ASSOCNETWORK")?;
+ }
+ matches!(
+ document.objects.get(&network),
+ Some(ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::Network(_),
+ ..
+ }))
+ )
+ .then_some(network)
+}
+
+/// The owner's associative network, made and attached to the drawing's root
+/// network when missing.
+fn ensure_network(document: &mut Document, owner: Handle) -> Result {
+ if let Some(network) = owner_network(document, owner) {
+ return Ok(network);
+ }
+ let extension = document.ensure_extension_dictionary(owner);
+ if matches!(
+ document.objects.get(&extension),
+ Some(ObjectType::Dictionary(dictionary)) if dictionary.get("ACAD_ASSOCNETWORK").is_some()
+ ) {
+ return Err(UNSUPPORTED);
+ }
+ let [dictionary, network] = [(); 2].map(|_| document.allocate_handle());
+ let mut holder = Dictionary::new();
+ holder.handle = dictionary;
+ holder.owner = extension;
+ holder.reactors = vec![extension];
+ holder.entries = vec![("ACAD_ASSOCNETWORK".into(), network)];
+ document
+ .objects
+ .insert(dictionary, ObjectType::Dictionary(holder));
+ document.objects.insert(
+ network,
+ ObjectType::Associative(AssociativeObject {
+ handle: network,
+ owner: dictionary,
+ reactors: vec![dictionary],
+ dxf_name: "ACDBASSOCNETWORK".into(),
+ cpp_class_name: "AcDbAssocNetwork".into(),
+ data: AssociativeData::Network(AssocNetwork {
+ action: AssocAction {
+ class_version: 2,
+ ..Default::default()
+ },
+ ..Default::default()
+ }),
+ ..Default::default()
+ }),
+ );
+ if let Some(ObjectType::Dictionary(extension)) = document.objects.get_mut(&extension) {
+ extension.add_entry("ACAD_ASSOCNETWORK", dictionary);
+ }
+ let mut networks = FxHashMap::default();
+ networks.insert(network, network);
+ Scene::register_copied_constraint_networks(document, &networks).map_err(|_| UNSUPPORTED)?;
+ Ok(network)
+}
+
+/// A new variable in `network`, its last action.
+fn new_variable(
+ document: &mut Document,
+ network: Handle,
+ name: &str,
+ expression: &str,
+ description: &str,
+ value: AssocEvalVariant,
+) -> Handle {
+ let handle = document.allocate_handle();
+ let index = match document.objects.get_mut(&network) {
+ Some(ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::Network(network),
+ ..
+ })) => {
+ network.network_action_index += 1;
+ network.actions.push(AssocActionDependency {
+ is_owned: true,
+ dependency: handle,
+ });
+ network.network_action_index
+ }
+ _ => 0,
+ };
+ document.objects.insert(
+ handle,
+ ObjectType::Associative(AssociativeObject {
+ handle,
+ owner: network,
+ dxf_name: "ACDBASSOCVARIABLE".into(),
+ cpp_class_name: "AcDbAssocVariable".into(),
+ data: AssociativeData::Variable(AssocVariable {
+ action: AssocAction {
+ class_version: 2,
+ owning_network: network,
+ action_index: index,
+ ..Default::default()
+ },
+ class_version: 2,
+ name: name.to_string(),
+ expression: expression.to_string(),
+ evaluator: "AcDbCalc:1.0".into(),
+ description: description.to_string(),
+ value,
+ ..Default::default()
+ }),
+ ..Default::default()
+ }),
+ );
+ handle
+}
+
+fn add_reactor(document: &mut Document, object: Handle, reactor: Handle) {
+ if let Some(ObjectType::Associative(object)) = document.objects.get_mut(&object) {
+ if !object.reactors.contains(&reactor) {
+ object.reactors.push(reactor);
+ }
+ }
+}
+
+fn variable_value(document: &Document, variable: Handle) -> AssocEvalVariant {
+ match document.objects.get(&variable) {
+ Some(ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::Variable(variable),
+ ..
+ })) => variable.value.clone(),
+ _ => AssocEvalVariant::default(),
+ }
+}
+
+/// Set a variable's expression and give it a value dependency on each
+/// variable it reads, numbered on from the ones it had.
+fn set_expression(document: &mut Document, variable: Handle, expression: &str, reads: &[Handle]) {
+ let old: Vec = match document.objects.get(&variable) {
+ Some(ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::Variable(value),
+ ..
+ })) => value.dependencies.iter().map(|d| d.dependency).collect(),
+ _ => return,
+ };
+ for dependency in old {
+ let read = match document.objects.get(&dependency) {
+ Some(ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::ValueDependency(value),
+ ..
+ })) => Some(value.dependency.dependent_on),
+ _ => None,
+ };
+ if let Some(read) = read {
+ if let Some(ObjectType::Associative(object)) = document.objects.get_mut(&read) {
+ object.reactors.retain(|reactor| *reactor != dependency);
+ }
+ }
+ document.objects.remove(&dependency);
+ }
+ let mut next = match document.objects.get(&variable) {
+ Some(ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::Variable(value),
+ ..
+ })) => value.action.max_dependency_index,
+ _ => 0,
+ };
+ let mut dependencies = Vec::new();
+ for (position, &read) in reads.iter().enumerate() {
+ next += 1;
+ let handle = document.allocate_handle();
+ let value = variable_value(document, read);
+ document.objects.insert(
+ handle,
+ ObjectType::Associative(AssociativeObject {
+ handle,
+ owner: variable,
+ dxf_name: "ACDBASSOCVALUEDEPENDENCY".into(),
+ cpp_class_name: "AcDbAssocValueDependency".into(),
+ data: AssociativeData::ValueDependency(AssocValueDependency {
+ dependency: AssocDependency {
+ class_version: 2,
+ is_read_dependency: true,
+ is_attached_to_object: true,
+ is_delegating_to_owning_action: true,
+ dependent_on: read,
+ dependency_body_id: next,
+ ..Default::default()
+ },
+ value,
+ ..Default::default()
+ }),
+ ..Default::default()
+ }),
+ );
+ add_reactor(document, read, handle);
+ // BricsCAD numbers the reads of a variable in its flags.
+ dependencies.push(AssocVariableDependency {
+ dependency: handle,
+ flags: position as _,
+ });
+ }
+ if let Some(ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::Variable(value),
+ ..
+ })) = document.objects.get_mut(&variable)
+ {
+ value.expression = expression.to_string();
+ value.dependencies = dependencies;
+ value.action.max_dependency_index = next;
+ }
+}
+
+/// Take a variable out of its network with the value dependencies it owns.
+fn erase_variable(document: &mut Document, network: Handle, variable: Handle) {
+ set_expression(document, variable, "", &[]);
+ if let Some(ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::Network(network),
+ ..
+ })) = document.objects.get_mut(&network)
+ {
+ network
+ .actions
+ .retain(|action| action.dependency != variable);
+ }
+ document.objects.remove(&variable);
+}
+
+/// For each entity of `owner`, its `BDMOBJECT` in the owner's constraint
+/// manager.
+fn entity_objects(
+ document: &Document,
+ owner: Handle,
+ constraints: Handle,
+) -> FxHashMap {
+ let mut objects = FxHashMap::default();
+ let Some(Body::ConstraintManager {
+ counts, children, ..
+ }) = read_record(document, constraints).map(|record| record.body)
+ else {
+ return objects;
+ };
+ for child in children
+ .iter()
+ .take(usize::try_from(counts[1]).unwrap_or(0))
+ {
+ if let Some(Body::Object { entity, .. }) =
+ read_record(document, child.handle).map(|record| record.body)
+ {
+ if document
+ .get_entity(entity.handle)
+ .is_some_and(|e| e.common().owner_handle == owner)
+ {
+ objects.insert(entity.handle, child.handle);
+ }
+ }
+ }
+ objects
+}
diff --git a/src/scene/bricscad_parameters/author_tests.rs b/src/scene/bricscad_parameters/author_tests.rs
new file mode 100644
index 0000000000..60cfb43f60
--- /dev/null
+++ b/src/scene/bricscad_parameters/author_tests.rs
@@ -0,0 +1,672 @@
+//! VISIBILITYSTATES against BricsCAD: the drawings in
+//! `tests/fixtures/bricscad/authoring-*.dwg` are what BricsCAD V26 saved
+//! along one run of the command on five lines (see the README there). The
+//! same run here leaves the same visibility setup.
+
+use super::author::{Action, Naming};
+use super::record::Value;
+use super::*;
+use crate::scene::Scene;
+use document::objects::{AssociativeData, AssociativeObject};
+
+pub(crate) fn fixture(name: &str) -> Scene {
+ let path = format!(
+ "{}/tests/fixtures/bricscad/{name}",
+ env!("CARGO_MANIFEST_DIR")
+ );
+ let bytes = std::fs::read(&path).unwrap_or_else(|_| panic!("read {path}"));
+ let mut scene = Scene::new();
+ scene.document = crate::io::load_bytes_finalized(std::path::Path::new(name), bytes)
+ .unwrap_or_else(|error| panic!("open {name}: {error}"));
+ scene.load_named_parameters_from_document();
+ scene.load_parametric_constraints_from_document();
+ scene
+}
+
+/// The five lines, L1 to L5, by their handles in the fixtures.
+pub(crate) const LINES: [u64; 5] = [0x92, 0x93, 0x94, 0x95, 0x96];
+
+fn line(n: usize) -> Handle {
+ Handle::from(LINES[n - 1])
+}
+
+/// One step of the run: parameter, state, action, lines by number.
+pub(super) type Step = (&'static str, &'static str, Action, &'static [usize]);
+
+/// The run up to the drawing BricsCAD saved as `authoring-select.dwg`.
+pub(super) const TO_SELECT: &[Step] = &[
+ ("P1", "S1", Action::Add, &[1, 2]),
+ ("P1", "S2", Action::Invisible, &[1]),
+ ("P1", "S3", Action::Invisible, &[2]),
+ ("P1", "S2", Action::Visible, &[1]),
+ ("P1", "S1", Action::Add, &[3]),
+ ("P1", "S1", Action::Remove, &[3]),
+ ("P2", "Sichtbar", Action::Add, &[4]),
+ ("P2", "Unsichtbar", Action::Invisible, &[4]),
+ ("P2", "Sichtbar", Action::Add, &[2]),
+ ("P1", "S4", Action::Visible, &[1]),
+ ("P1", "S2", Action::Select, &[]),
+ ("P1", "S3", Action::Select, &[]),
+];
+
+/// From the drawing after `S4` (before the two selections) on to the one
+/// BricsCAD saved as `authoring-edit.dwg`.
+pub(super) const TO_EDIT: &[Step] = &[
+ ("P1", "S1", Action::Invisible, &[5]),
+ ("P1", "S2", Action::Visible, &[4]),
+ ("P1", "S1", Action::Remove, &[1]),
+ ("P1", "S3", Action::Add, &[2]),
+ ("P1", "S2", Action::Add, &[3]),
+];
+
+pub(super) fn run(scene: &mut Scene, steps: &[Step]) {
+ let model = scene.document.header.model_space_block_handle;
+ for (parameter, state, action, lines) in steps {
+ let objects: Vec = lines.iter().map(|n| line(*n)).collect();
+ scene
+ .edit_bricscad_visibility_named(
+ model,
+ parameter,
+ state,
+ *action,
+ &objects,
+ Naming::GERMAN,
+ )
+ .unwrap_or_else(|error| panic!("{parameter} {state} {action:?} {lines:?}: {error}"));
+ }
+}
+
+/// The visibility setup of model space as text, without handles: parameters
+/// with their tables and current states, suppressions with their members,
+/// state and kept layers, the variables with their values, and each line's
+/// layer and object.
+pub(crate) fn describe(document: &Document) -> Vec {
+ let model = document.header.model_space_block_handle;
+ let mut out = Vec::new();
+ let variable = |handle: Handle| match document.objects.get(&handle) {
+ Some(ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::Variable(variable),
+ ..
+ })) => Some(variable),
+ _ => None,
+ };
+ let number = |value: &document::objects::AssocEvalVariant| match &value.value {
+ document::objects::AssocEvalValue::Real(v) => format!("{v}"),
+ document::objects::AssocEvalValue::Long(v) => format!("{v}"),
+ other => format!("{other:?}"),
+ };
+ let layer = |handle: Handle| {
+ document
+ .layers
+ .iter()
+ .find(|layer| layer.handle == handle)
+ .map_or_else(|| format!("{handle:?}"), |layer| layer.name.clone())
+ };
+ let objects = |properties: &record::Properties, name: &str| -> Vec {
+ properties
+ .get(name)
+ .and_then(Value::items)
+ .map(|items| items.iter().filter_map(Value::object).collect())
+ .unwrap_or_default()
+ };
+ let mut groups_of: std::collections::BTreeMap = Default::default();
+ for feature in features(document, model) {
+ let properties = super::properties(document, feature).expect("a feature decodes");
+ match properties.text("Feature_type") {
+ Some("BdmConfigurationFeature") => {
+ let table = super::properties(
+ document,
+ properties.get("ConfigTable").unwrap().object().unwrap(),
+ )
+ .unwrap();
+ out.push(format!(
+ "parameter {} shows {} table {:?}",
+ properties.text("Name").unwrap(),
+ properties.text("LastKeyValue").unwrap(),
+ table.0
+ ));
+ for reactor in objects(&properties, "Reactors") {
+ let reactor = super::properties(document, reactor).unwrap();
+ let key = reactor.get("IsKeyVar") == Some(&Value::Flag(true));
+ let var = variable(reactor.get("VarId").unwrap().object().unwrap()).unwrap();
+ out.push(format!(
+ " reactor {} key {key} enabled {:?} string {:?} value {} -> {} {:?} {}",
+ reactor.text("VarName").unwrap(),
+ reactor.get("IsEnabled").unwrap(),
+ reactor.text("String").unwrap(),
+ // The key variable's number follows no rule BricsCAD
+ // keeps; it reads the state from the string.
+ if key {
+ "-".into()
+ } else {
+ format!("{:?}", reactor.get("Value").unwrap())
+ },
+ var.name,
+ var.description,
+ if key { "-".into() } else { number(&var.value) },
+ ));
+ }
+ }
+ Some("BdmSuppressFeature") => {
+ let name = properties.text("Name").unwrap().to_string();
+ let mut line = format!(
+ "suppression {name} status {:?} kept {:?}",
+ properties.get("Status").unwrap(),
+ properties
+ .get("aEntLayerKey")
+ .and_then(Value::entries)
+ .unwrap()
+ .iter()
+ .map(|(entity, kept)| format!(
+ "{:X}->{}",
+ entity.object().unwrap().value(),
+ layer(kept.object().unwrap())
+ ))
+ .collect::>()
+ );
+ for reactor in objects(&properties, "Reactors") {
+ let reactor_properties = super::properties(document, reactor).unwrap();
+ if reactor_properties.get("pers_ids").is_some() {
+ let mut members: Vec = objects(&reactor_properties, "pers_ids")
+ .into_iter()
+ .map(
+ |dependency| match record(document, dependency).unwrap().body {
+ record::Body::Dependency { entity, .. } => {
+ groups_of.insert(entity.handle.value(), name.clone());
+ format!("{:X}", entity.handle.value())
+ }
+ other => panic!("{other:?}"),
+ },
+ )
+ .collect();
+ members.sort();
+ line.push_str(&format!(" members {members:?}"));
+ } else {
+ let var =
+ variable(reactor_properties.get("var").unwrap().object().unwrap())
+ .unwrap();
+ let mut reads: Vec = var
+ .dependencies
+ .iter()
+ .map(
+ |dependency| match document.objects.get(&dependency.dependency) {
+ Some(ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::ValueDependency(value),
+ ..
+ })) => variable(value.dependency.dependent_on)
+ .unwrap()
+ .name
+ .clone(),
+ other => panic!("{other:?}"),
+ },
+ )
+ .collect();
+ reads.sort();
+ line.push_str(&format!(
+ " value {:?} variable {} = {} [{}] reads {reads:?}",
+ reactor_properties.get("value").unwrap(),
+ var.name,
+ var.expression,
+ number(&var.value)
+ ));
+ }
+ }
+ out.push(line);
+ }
+ _ => {}
+ }
+ }
+ for &handle in &LINES {
+ let entity = document.get_entity(Handle::from(handle)).unwrap();
+ let objects: Vec = entity
+ .common()
+ .reactors
+ .iter()
+ .filter_map(|reactor| match record(document, *reactor)?.body {
+ record::Body::Object { properties, .. } => Some(format!(
+ "{} with {} dependencies",
+ properties.text("NAME").unwrap(),
+ properties
+ .get("PersIdDependencies")
+ .unwrap()
+ .items()
+ .unwrap()
+ .len()
+ )),
+ _ => None,
+ })
+ .collect();
+ out.push(format!(
+ "line {handle:X} layer {} in {:?} objects {objects:?}",
+ entity.common().layer,
+ groups_of.get(&handle)
+ ));
+ }
+ out
+}
+
+fn assert_same(ours: &Document, theirs: &Document) {
+ let ours = describe(ours);
+ let theirs = describe(theirs);
+ let differences: Vec = ours
+ .iter()
+ .zip(&theirs)
+ .filter(|(a, b)| a != b)
+ .map(|(a, b)| format!("ours: {a}\ntheirs: {b}"))
+ .collect();
+ assert!(
+ differences.is_empty() && ours.len() == theirs.len(),
+ "{}\n\nours:\n{}\n\ntheirs:\n{}",
+ differences.join("\n"),
+ ours.join("\n"),
+ theirs.join("\n")
+ );
+}
+
+#[test]
+fn the_run_leaves_what_bricscad_leaves_up_to_two_selections() {
+ let mut scene = fixture("authoring-start.dwg");
+ run(&mut scene, TO_SELECT);
+ assert_same(&scene.document, &fixture("authoring-select.dwg").document);
+}
+
+#[test]
+fn the_run_leaves_what_bricscad_leaves_through_remove_and_re_add() {
+ let mut scene = fixture("authoring-start.dwg");
+ run(&mut scene, &TO_SELECT[..10]);
+ run(&mut scene, TO_EDIT);
+ assert_same(&scene.document, &fixture("authoring-edit.dwg").document);
+}
+
+/// What BricsCAD keeps that the run's tables do not show: every read of a
+/// variable holds the variable's value (BricsCAD does not evaluate past a
+/// read that already holds a new value), a variable's reads are numbered,
+/// and each key has the number of the state it shows.
+#[test]
+fn reads_hold_their_values_and_keys_the_number_of_their_state() {
+ let mut scene = fixture("authoring-start.dwg");
+ run(&mut scene, TO_SELECT);
+ run(
+ &mut scene,
+ &[
+ ("P3", "S1", Action::Add, &[2]),
+ ("P1", "S1", Action::Select, &[]),
+ ],
+ );
+ let document = &scene.document;
+ let variable = |handle: Handle| match document.objects.get(&handle) {
+ Some(ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::Variable(variable),
+ ..
+ })) => variable,
+ other => panic!("{other:?}"),
+ };
+ let mut reads = 0;
+ let mut most = 0;
+ for object in document.objects.values() {
+ match object {
+ ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::ValueDependency(read),
+ ..
+ }) => {
+ let read_variable = variable(read.dependency.dependent_on);
+ assert_eq!(read.value, read_variable.value, "{}", read_variable.name);
+ reads += 1;
+ }
+ ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::Variable(variable),
+ ..
+ }) => {
+ let flags: Vec = variable
+ .dependencies
+ .iter()
+ .map(|dependency| dependency.flags as usize)
+ .collect();
+ assert_eq!(
+ flags,
+ (0..flags.len()).collect::>(),
+ "{}",
+ variable.name
+ );
+ most = most.max(flags.len());
+ }
+ _ => {}
+ }
+ }
+ assert!(reads > 0);
+ assert_eq!(most, 3, "L2 is ruled by three parameters");
+ let model = document.header.model_space_block_handle;
+ let mut keys = 0;
+ for feature in features(document, model) {
+ let properties = super::properties(document, feature).unwrap();
+ if properties.text("Feature_type") != Some("BdmConfigurationFeature") {
+ continue;
+ }
+ let parameter = visibility_parameter(document, feature).unwrap();
+ for reactor in properties.get("Reactors").unwrap().items().unwrap() {
+ let reactor = super::properties(document, reactor.object().unwrap()).unwrap();
+ if reactor.get("IsKeyVar") != Some(&Value::Flag(true)) {
+ continue;
+ }
+ let row = parameter.current.unwrap() as f64;
+ assert_eq!(
+ reactor.get("Value"),
+ Some(&Value::Real(row)),
+ "{}",
+ parameter.name
+ );
+ let key = variable(reactor.get("VarId").unwrap().object().unwrap());
+ assert_eq!(
+ key.value.value,
+ document::objects::AssocEvalValue::Real(row),
+ "{}",
+ parameter.name
+ );
+ keys += 1;
+ }
+ }
+ assert_eq!(keys, 3);
+}
+
+/// BricsCAD finds variables by name, and a second variable of a name gets
+/// the two mixed up. Some of its drawings have a group whose variable is
+/// named after another group (`Unterdrücken_1` with the variable
+/// `Unterdrücken_7`): a new group takes a name no variable has.
+#[test]
+fn a_new_group_takes_a_name_no_variable_has() {
+ let mut scene = fixture("authoring-select.dwg");
+ let model = scene.document.header.model_space_block_handle;
+ let group_variable = features(&scene.document, model)
+ .into_iter()
+ .filter_map(|feature| super::properties(&scene.document, feature))
+ .filter(|properties| properties.text("Name") == Some("Unterdrücken_2"))
+ .flat_map(|properties| {
+ properties
+ .get("Reactors")
+ .unwrap()
+ .items()
+ .unwrap()
+ .to_vec()
+ })
+ .filter_map(|reactor| super::properties(&scene.document, reactor.object()?))
+ .find_map(|reactor| reactor.get("var")?.object())
+ .unwrap();
+ match scene.document.objects.get_mut(&group_variable) {
+ Some(ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::Variable(variable),
+ ..
+ })) => variable.name = "Unterdrücken_4".into(),
+ other => panic!("{other:?}"),
+ }
+ // As if the drawing had been opened so.
+ scene.load_named_parameters_from_document();
+ scene.load_parametric_constraints_from_document();
+ run(&mut scene, &[("P1", "S1", Action::Add, &[5])]);
+ let document = &scene.document;
+ let mut names: Vec = document
+ .objects
+ .values()
+ .filter_map(|object| match object {
+ ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::Variable(variable),
+ ..
+ }) => Some(variable.name.to_lowercase()),
+ _ => None,
+ })
+ .collect();
+ let all = names.len();
+ names.sort();
+ names.dedup();
+ assert_eq!(names.len(), all, "{names:?}");
+ let described = describe(document);
+ assert!(
+ described
+ .iter()
+ .any(|line| line.starts_with("suppression Unterdrücken_5 ")
+ && line.contains("members [\"96\"]")),
+ "{described:#?}"
+ );
+}
+
+/// Each state of `parameter` by name with the objects it shows.
+fn shown_by_state(
+ document: &Document,
+ parameter: &str,
+) -> std::collections::BTreeMap> {
+ let model = document.header.model_space_block_handle;
+ let view = super::parameter_views(document, model)
+ .unwrap()
+ .into_iter()
+ .find(|p| p.name == parameter)
+ .unwrap();
+ view.states
+ .iter()
+ .enumerate()
+ .map(|(s, state)| {
+ (
+ state.clone(),
+ view.objects
+ .iter()
+ .filter(|(_, pattern)| pattern[s])
+ .map(|(entity, _)| entity.value())
+ .collect(),
+ )
+ })
+ .collect()
+}
+
+fn states_of(document: &Document, parameter: &str) -> (Vec, usize) {
+ let model = document.header.model_space_block_handle;
+ let view = super::parameter_views(document, model)
+ .unwrap()
+ .into_iter()
+ .find(|p| p.name == parameter)
+ .unwrap();
+ (view.states, view.current)
+}
+
+/// The number the key variable of `parameter` holds.
+fn key_number(document: &Document, parameter: &str) -> Value {
+ let model = document.header.model_space_block_handle;
+ for feature in features(document, model) {
+ let properties = super::properties(document, feature).unwrap();
+ if properties.text("Name") != Some(parameter) {
+ continue;
+ }
+ for reactor in properties.get("Reactors").unwrap().items().unwrap() {
+ let reactor = super::properties(document, reactor.object().unwrap()).unwrap();
+ if reactor.get("IsKeyVar") == Some(&Value::Flag(true)) {
+ return reactor.get("Value").unwrap().clone();
+ }
+ }
+ }
+ panic!("no key of {parameter}");
+}
+
+#[test]
+fn a_state_moves_with_its_objects_and_the_shown_state_stays_shown() {
+ let mut scene = fixture("authoring-select.dwg");
+ let before = shown_by_state(&scene.document, "P1");
+ assert_eq!(
+ states_of(&scene.document, "P1"),
+ (vec!["S1".into(), "S2".into(), "S3".into(), "S4".into()], 2)
+ );
+ let layers = |document: &Document| -> Vec {
+ LINES
+ .iter()
+ .map(|h| {
+ document
+ .get_entity(Handle::from(*h))
+ .unwrap()
+ .common()
+ .layer
+ .clone()
+ })
+ .collect()
+ };
+ let shown = layers(&scene.document);
+ run(&mut scene, &[("P1", "S3", Action::MoveUp, &[])]);
+ assert_eq!(
+ states_of(&scene.document, "P1"),
+ (vec!["S1".into(), "S3".into(), "S2".into(), "S4".into()], 1)
+ );
+ assert_eq!(shown_by_state(&scene.document, "P1"), before);
+ assert_eq!(layers(&scene.document), shown, "the drawing shows the same");
+ assert_eq!(key_number(&scene.document, "P1"), Value::Real(1.0));
+ run(&mut scene, &[("P1", "S1", Action::MoveDown, &[])]);
+ assert_eq!(
+ states_of(&scene.document, "P1"),
+ (vec!["S3".into(), "S1".into(), "S2".into(), "S4".into()], 0)
+ );
+ assert_eq!(shown_by_state(&scene.document, "P1"), before);
+ // Past either end nothing moves.
+ let model = scene.document.header.model_space_block_handle;
+ let unchanged = scene.document.clone();
+ for (state, action) in [("S3", Action::MoveUp), ("S4", Action::MoveDown)] {
+ assert!(scene
+ .edit_bricscad_visibility_named(model, "P1", state, action, &[], Naming::GERMAN)
+ .is_err());
+ }
+ assert!(scene.document == unchanged);
+}
+
+#[test]
+fn a_new_state_hides_every_object_of_its_parameter_and_is_shown() {
+ let mut scene = fixture("authoring-select.dwg");
+ run(&mut scene, &[("P1", "Leer", Action::NewState, &[])]);
+ let (states, current) = states_of(&scene.document, "P1");
+ assert_eq!(states.last().map(String::as_str), Some("Leer"));
+ assert_eq!(current, states.len() - 1);
+ assert_eq!(
+ shown_by_state(&scene.document, "P1")["Leer"],
+ Vec::::new()
+ );
+ // L1 and L2 are ruled by P1 (L2 also by P2): both hidden now.
+ for handle in [0x92, 0x93] {
+ assert_eq!(
+ scene
+ .document
+ .get_entity(Handle::from(handle))
+ .unwrap()
+ .common()
+ .layer,
+ "*SUPPRESS"
+ );
+ }
+ let model = scene.document.header.model_space_block_handle;
+ assert!(scene
+ .edit_bricscad_visibility_named(model, "P1", "leer", Action::NewState, &[], Naming::GERMAN)
+ .is_err());
+ assert!(scene
+ .edit_bricscad_visibility_named(model, "P9", "S1", Action::NewState, &[], Naming::GERMAN)
+ .is_err());
+}
+
+/// The key of `parameter`: whether enabled, its number, its variable's
+/// expression and value.
+fn key_of(
+ document: &Document,
+ parameter: &str,
+) -> (Value, Value, String, document::objects::AssocEvalValue) {
+ let model = document.header.model_space_block_handle;
+ for feature in features(document, model) {
+ let properties = super::properties(document, feature).unwrap();
+ if properties.text("Name") != Some(parameter) {
+ continue;
+ }
+ for reactor in properties.get("Reactors").unwrap().items().unwrap() {
+ let reactor = super::properties(document, reactor.object().unwrap()).unwrap();
+ if reactor.get("IsKeyVar") != Some(&Value::Flag(true)) {
+ continue;
+ }
+ let handle = reactor.get("VarId").unwrap().object().unwrap();
+ let Some(ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::Variable(variable),
+ ..
+ })) = document.objects.get(&handle)
+ else {
+ panic!()
+ };
+ return (
+ reactor.get("IsEnabled").unwrap().clone(),
+ reactor.get("Value").unwrap().clone(),
+ variable.expression.clone(),
+ variable.value.value.clone(),
+ );
+ }
+ }
+ panic!("no key of {parameter}");
+}
+
+/// openCirt's templates have keys BricsCAD left disabled over a variable
+/// with an expression of its own (a key showing the second state over `0`).
+/// BricsCAD reads such a state by name and leaves the key alone until the
+/// parameter's state is picked; then it enables the key and drops the
+/// expression. A key re-enabled under its expression would make BricsCAD
+/// show the first state on its next evaluation.
+#[test]
+fn a_disabled_key_is_left_alone_until_its_state_is_picked() {
+ use document::objects::{AssocEvalValue, AssocEvalVariant};
+ let mut scene = fixture("authoring-select.dwg");
+ let model = scene.document.header.model_space_block_handle;
+ // P2 shows Sichtbar (row 0); make its key like the templates' ones.
+ for feature in features(&scene.document, model) {
+ let properties = super::properties(&scene.document, feature).unwrap();
+ if properties.text("Name") != Some("P2") {
+ continue;
+ }
+ for reactor in properties.get("Reactors").unwrap().items().unwrap() {
+ let handle = reactor.object().unwrap();
+ let mut record = record(&scene.document, handle).unwrap();
+ let reactor = record.body.properties_mut();
+ if reactor.get("IsKeyVar") != Some(&Value::Flag(true)) {
+ continue;
+ }
+ reactor.set("IsEnabled", Value::Flag(false));
+ reactor.set("Value", Value::Real(1.0));
+ let variable = reactor.get("VarId").unwrap().object().unwrap();
+ super::switch::store(&mut scene.document, &record);
+ super::switch::set_variable(
+ &mut scene.document,
+ variable,
+ Some("1".into()),
+ AssocEvalVariant {
+ code: 90,
+ value: AssocEvalValue::Long(1),
+ },
+ )
+ .unwrap();
+ }
+ }
+ scene.load_named_parameters_from_document();
+ let before = key_of(&scene.document, "P2");
+ run(
+ &mut scene,
+ &[
+ ("P1", "S1", Action::Select, &[]),
+ ("P1", "S4", Action::MoveUp, &[]),
+ ("P1", "Neu", Action::NewState, &[]),
+ ("P1", "S2", Action::Visible, &[5]),
+ ],
+ );
+ assert_eq!(
+ key_of(&scene.document, "P2"),
+ before,
+ "P2 was not asked about"
+ );
+ assert_eq!(
+ states_of(&scene.document, "P2").1,
+ 0,
+ "still shows Sichtbar"
+ );
+ run(&mut scene, &[("P2", "Unsichtbar", Action::Select, &[])]);
+ assert_eq!(
+ key_of(&scene.document, "P2"),
+ (
+ Value::Flag(true),
+ Value::Real(1.0),
+ String::new(),
+ AssocEvalValue::Real(1.0)
+ )
+ );
+}
diff --git a/src/scene/bricscad_parameters/record.rs b/src/scene/bricscad_parameters/record.rs
new file mode 100644
index 0000000000..ebbe5e56af
--- /dev/null
+++ b/src/scene/bricscad_parameters/record.rs
@@ -0,0 +1,948 @@
+//! BricsCAD's parameter objects as DWG records (2010 and later), decoded so
+//! that encoding them again gives the same bits, and encoded after a change.
+//!
+//! A record holds the common object header (type, handle, extended data,
+//! owner, reactors, extension dictionary) and a body. Most of BricsCAD's
+//! classes hold a plain list of named properties; three hold a few values
+//! around such a list:
+//!
+//! - `BDMDBCONSTRAINTMANAGER`: five counts, the objects and child managers it
+//! owns, then its settings;
+//! - `BDMOBJECT`: a byte and a count, the object it stands for, its
+//! properties, a count;
+//! - `BDMDBOBJECTDEPENDENCY`: its (empty) properties, a count, the object it
+//! depends on.
+//!
+//! In the data stream a property list is a count and, per property, a type
+//! byte and the value. Names and text sit in the string stream and references
+//! in the handle stream, both in the order the data stream names them.
+
+use document::{DxfVersion, Handle};
+
+/// A reference through the handle stream and the code it is written with:
+/// a reference type (2 to 5) or one of the forms relative to the record's own
+/// handle (6, 8, 10, 12).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) struct Ref {
+ pub(crate) handle: Handle,
+ pub(crate) code: u8,
+}
+
+impl Ref {
+ pub(crate) fn new(handle: Handle, code: u8) -> Self {
+ Self { handle, code }
+ }
+}
+
+/// A property value.
+#[derive(Debug, Clone, PartialEq)]
+pub(crate) enum Value {
+ Text(String),
+ Integer(i32),
+ Real(f64),
+ Flag(bool),
+ Byte(u8),
+ /// Bytes in the data stream; BricsCAD stores some handles this way.
+ Raw(Vec),
+ /// A reference: a byte in the data stream, the handle in the handle stream.
+ Object {
+ kind: u8,
+ target: Ref,
+ },
+ List {
+ element: u8,
+ items: Vec,
+ },
+ Map {
+ key: u8,
+ value: u8,
+ entries: Vec<(Value, Value)>,
+ },
+}
+
+impl Value {
+ fn kind(&self) -> u8 {
+ match self {
+ Value::Text(_) => 2,
+ Value::Integer(_) => 3,
+ Value::Real(_) => 4,
+ Value::Flag(_) => 5,
+ Value::Byte(_) => 6,
+ Value::Raw(_) => 7,
+ Value::Object { .. } => 8,
+ Value::List { .. } => 9,
+ Value::Map { .. } => 10,
+ }
+ }
+
+ pub(crate) fn text(&self) -> Option<&str> {
+ match self {
+ Value::Text(text) => Some(text),
+ _ => None,
+ }
+ }
+
+ pub(crate) fn object(&self) -> Option {
+ match self {
+ Value::Object { target, .. } => Some(target.handle),
+ _ => None,
+ }
+ }
+
+ pub(crate) fn items(&self) -> Option<&[Value]> {
+ match self {
+ Value::List { items, .. } => Some(items),
+ _ => None,
+ }
+ }
+
+ pub(crate) fn entries(&self) -> Option<&[(Value, Value)]> {
+ match self {
+ Value::Map { entries, .. } => Some(entries),
+ _ => None,
+ }
+ }
+
+ /// Every reference in the value, in the order they are written.
+ fn refs_mut(&mut self, visit: &mut impl FnMut(&mut Ref)) {
+ match self {
+ Value::Object { target, .. } => visit(target),
+ Value::List { items, .. } => items.iter_mut().for_each(|item| item.refs_mut(visit)),
+ Value::Map { entries, .. } => entries.iter_mut().for_each(|(key, value)| {
+ key.refs_mut(visit);
+ value.refs_mut(visit);
+ }),
+ _ => {}
+ }
+ }
+}
+
+/// The named properties of a record, in stored order.
+#[derive(Debug, Clone, PartialEq, Default)]
+pub(crate) struct Properties(pub(crate) Vec<(String, Value)>);
+
+impl Properties {
+ pub(crate) fn get(&self, name: &str) -> Option<&Value> {
+ self.0
+ .iter()
+ .find(|(key, _)| key == name)
+ .map(|(_, value)| value)
+ }
+
+ pub(crate) fn get_mut(&mut self, name: &str) -> Option<&mut Value> {
+ self.0
+ .iter_mut()
+ .find(|(key, _)| key == name)
+ .map(|(_, value)| value)
+ }
+
+ pub(crate) fn text(&self, name: &str) -> Option<&str> {
+ self.get(name)?.text()
+ }
+
+ /// Replace the value of an existing property; `false` when there is none.
+ pub(crate) fn set(&mut self, name: &str, value: Value) -> bool {
+ match self.get_mut(name) {
+ Some(slot) => {
+ *slot = value;
+ true
+ }
+ None => false,
+ }
+ }
+
+ fn refs_mut(&mut self, visit: &mut impl FnMut(&mut Ref)) {
+ for (_, value) in &mut self.0 {
+ value.refs_mut(visit);
+ }
+ }
+}
+
+/// What a record holds after the common header.
+#[derive(Debug, Clone, PartialEq)]
+pub(crate) enum Body {
+ Properties(Properties),
+ /// `BDMDBCONSTRAINTMANAGER`. `counts[1]` objects and `counts[3]` child
+ /// managers, in that order in `children`.
+ ConstraintManager {
+ counts: [i32; 5],
+ children: Vec[,
+ settings: Properties,
+ },
+ /// `BDMOBJECT`.
+ Object {
+ lead: u8,
+ lead_count: i32,
+ entity: Ref,
+ properties: Properties,
+ tail: i32,
+ },
+ /// `BDMDBOBJECTDEPENDENCY`.
+ Dependency {
+ properties: Properties,
+ tail: i32,
+ entity: Ref,
+ },
+}
+
+impl Body {
+ pub(crate) fn properties(&self) -> &Properties {
+ match self {
+ Body::Properties(properties)
+ | Body::Object { properties, .. }
+ | Body::Dependency { properties, .. } => properties,
+ Body::ConstraintManager { settings, .. } => settings,
+ }
+ }
+
+ pub(crate) fn properties_mut(&mut self) -> &mut Properties {
+ match self {
+ Body::Properties(properties)
+ | Body::Object { properties, .. }
+ | Body::Dependency { properties, .. } => properties,
+ Body::ConstraintManager { settings, .. } => settings,
+ }
+ }
+
+ /// Every reference of the body, in the order they are written.
+ fn refs_mut(&mut self, visit: &mut impl FnMut(&mut Ref)) {
+ match self {
+ Body::Properties(properties) => properties.refs_mut(visit),
+ Body::ConstraintManager {
+ children, settings, ..
+ } => {
+ children.iter_mut().for_each(&mut *visit);
+ settings.refs_mut(visit);
+ }
+ Body::Object {
+ entity, properties, ..
+ } => {
+ visit(entity);
+ properties.refs_mut(visit);
+ }
+ Body::Dependency {
+ properties, entity, ..
+ } => {
+ properties.refs_mut(visit);
+ visit(entity);
+ }
+ }
+ }
+}
+
+/// One record of a BricsCAD parameter object.
+#[derive(Debug, Clone, PartialEq)]
+pub(crate) struct Record {
+ object_type: u16,
+ pub(crate) handle: Handle,
+ handle_code: u8,
+ extended_data: Vec<(Ref, Vec])>,
+ pub(crate) owner: Ref,
+ pub(crate) reactors: Vec[,
+ pub(crate) extension_dictionary: Option][,
+ binary_data: bool,
+ pub(crate) body: Body,
+ pub(crate) version: DxfVersion,
+}
+
+impl Record {
+ /// A new record of the class with DWG type number `object_type`; no
+ /// extended data, reactors or extension dictionary.
+ pub(crate) fn new(
+ object_type: u16,
+ handle: Handle,
+ owner: Ref,
+ body: Body,
+ version: DxfVersion,
+ ) -> Self {
+ Self {
+ object_type,
+ handle,
+ handle_code: 0,
+ extended_data: Vec::new(),
+ owner,
+ reactors: Vec::new(),
+ extension_dictionary: None,
+ binary_data: false,
+ body,
+ version,
+ }
+ }
+
+ /// A new record of the class of `template`, which gives the type number
+ /// and the version; no extended data, reactors or extension dictionary.
+ pub(crate) fn like(template: &Record, handle: Handle, owner: Ref, body: Body) -> Self {
+ Self {
+ object_type: template.object_type,
+ handle,
+ handle_code: template.handle_code,
+ extended_data: Vec::new(),
+ owner,
+ reactors: Vec::new(),
+ extension_dictionary: None,
+ binary_data: false,
+ body,
+ version: template.version,
+ }
+ }
+
+ /// Every reference of the record: owner, reactors, extension dictionary
+ /// and those of the body. Extended data names applications, which are
+ /// left alone.
+ pub(crate) fn refs_mut(&mut self, mut visit: impl FnMut(&mut Ref)) {
+ visit(&mut self.owner);
+ self.reactors.iter_mut().for_each(&mut visit);
+ if let Some(dictionary) = &mut self.extension_dictionary {
+ visit(dictionary);
+ }
+ self.body.refs_mut(&mut visit);
+ }
+}
+
+/// Decode the record of a `class` object: the merged data, string and handle
+/// streams as the DWG reader keeps them, without the size prefixes and the
+/// CRC. `None` for a DWG before 2010 and a record that does not decode in
+/// full: any data or string bit left over, or more than padding left in the
+/// handle stream.
+pub(crate) fn decode(
+ class: &str,
+ data: &[u8],
+ handle_bits: i64,
+ version: DxfVersion,
+) -> Option] {
+ if version < DxfVersion::AC1024 {
+ return None;
+ }
+ let total = data.len().checked_mul(8)?;
+ let handles_at = total.checked_sub(usize::try_from(handle_bits).ok()?)?;
+ let mut main = Bits::new(data, 0, handles_at);
+ let object_type = main.object_type()?;
+ let (handle_code, own) = main.handle(0)?;
+ let mut extended_data = Vec::new();
+ loop {
+ let size = main.bit_short()?;
+ if size < 0 {
+ return None;
+ }
+ if size == 0 {
+ break;
+ }
+ let (code, application) = main.handle(0)?;
+ let bytes = (0..size).map(|_| main.byte()).collect::>>()?;
+ extended_data.push((Ref::new(Handle::from(application), code), bytes));
+ }
+ let reactor_count = usize::try_from(main.bit_long()?).ok()?;
+ if reactor_count > total {
+ return None;
+ }
+ let has_extension_dictionary = !main.bit()?;
+ let binary_data = version >= DxfVersion::AC1027 && main.bit()?;
+
+ let (strings_at, strings_end) = string_stream(data, handles_at)?;
+ if main.pos > strings_at {
+ return None;
+ }
+ main.end = strings_at;
+ let mut handles = Bits::new(data, handles_at, total);
+ let reference = |handles: &mut Bits| {
+ handles
+ .handle(own)
+ .map(|(code, handle)| Ref::new(Handle::from(handle), code))
+ };
+ let owner = reference(&mut handles)?;
+ let reactors = (0..reactor_count)
+ .map(|_| reference(&mut handles))
+ .collect:: >>()?;
+ let extension_dictionary = if has_extension_dictionary {
+ Some(reference(&mut handles)?)
+ } else {
+ None
+ };
+ let mut reader = Reader {
+ main,
+ strings: Bits::new(data, strings_at, strings_end),
+ handles,
+ own,
+ };
+ let body = reader.body(class)?;
+ let complete = reader.main.pos == reader.main.end
+ && reader.strings.pos == reader.strings.end
+ && reader.handles.end - reader.handles.pos < 8;
+ complete.then_some(Record {
+ object_type,
+ handle: Handle::from(own),
+ handle_code,
+ extended_data,
+ owner,
+ reactors,
+ extension_dictionary,
+ binary_data,
+ body,
+ version,
+ })
+}
+
+/// Encode `record`: the merged streams and the bit count of its handle
+/// stream, as the DWG writer takes a raw record.
+pub(crate) fn encode(record: &Record) -> (Vec, i64) {
+ let own = record.handle.value();
+ let mut main = Writer::default();
+ let strings = Writer::default();
+ let mut handles = Writer::default();
+ main.object_type(record.object_type);
+ main.handle(record.handle_code, own, 0);
+ for (application, bytes) in &record.extended_data {
+ main.bit_short(bytes.len() as i16);
+ main.handle(application.code, application.handle.value(), 0);
+ for byte in bytes {
+ main.byte(*byte);
+ }
+ }
+ main.bit_short(0);
+ main.bit_long(record.reactors.len() as i32);
+ main.bit(record.extension_dictionary.is_none());
+ if record.version >= DxfVersion::AC1027 {
+ main.bit(record.binary_data);
+ }
+ handles.reference(record.owner, own);
+ for reactor in &record.reactors {
+ handles.reference(*reactor, own);
+ }
+ if let Some(dictionary) = record.extension_dictionary {
+ handles.reference(dictionary, own);
+ }
+ let mut encoder = Encoder {
+ main,
+ strings,
+ handles,
+ own,
+ };
+ encoder.body(&record.body);
+ let Encoder {
+ mut main,
+ strings,
+ handles,
+ ..
+ } = encoder;
+ let string_bits = strings.len;
+ if string_bits > 0 {
+ main.append(&strings);
+ if string_bits < 0x8000 {
+ main.raw_short(string_bits as u16);
+ } else {
+ main.raw_short((string_bits >> 15) as u16);
+ main.raw_short((string_bits & 0x7FFF) as u16 | 0x8000);
+ }
+ main.bit(true);
+ } else {
+ main.bit(false);
+ }
+ let main_bits = main.len;
+ main.append(&handles);
+ let bytes = main.into_bytes();
+ let handle_bits = (bytes.len() * 8 - main_bits) as i64;
+ (bytes, handle_bits)
+}
+
+/// The bit range of the string stream, which ends where the data stream's
+/// last bit says whether there is one.
+fn string_stream(data: &[u8], handles_at: usize) -> Option<(usize, usize)> {
+ let flag = handles_at.checked_sub(1)?;
+ if !Bits::new(data, flag, handles_at).bit()? {
+ return Some((flag, flag));
+ }
+ let size_at = flag.checked_sub(16)?;
+ let mut size = usize::from(Bits::new(data, size_at, flag).raw_short()?);
+ let mut start = size_at;
+ if size & 0x8000 != 0 {
+ let high_at = size_at.checked_sub(16)?;
+ let high = usize::from(Bits::new(data, high_at, size_at).raw_short()?);
+ size = (size & 0x7FFF) | (high << 15);
+ start = high_at;
+ }
+ Some((start.checked_sub(size)?, start))
+}
+
+struct Reader<'a> {
+ main: Bits<'a>,
+ strings: Bits<'a>,
+ handles: Bits<'a>,
+ own: u64,
+}
+
+impl Reader<'_> {
+ fn body(&mut self, class: &str) -> Option {
+ Some(match class {
+ "BDMDBCONSTRAINTMANAGER" => {
+ let mut counts = [0; 5];
+ for count in &mut counts {
+ *count = self.main.bit_long()?;
+ }
+ // Only the objects and child managers are understood.
+ if counts[2] != 0 || counts[4] != 0 {
+ return None;
+ }
+ let children =
+ usize::try_from(counts[1]).ok()? + usize::try_from(counts[3]).ok()?;
+ if children > self.handles.end {
+ return None;
+ }
+ let children = (0..children)
+ .map(|_| self.reference())
+ .collect::>>()?;
+ Body::ConstraintManager {
+ counts,
+ children,
+ settings: self.properties()?,
+ }
+ }
+ "BDMOBJECT" => Body::Object {
+ lead: self.main.byte()?,
+ lead_count: self.main.bit_long()?,
+ entity: self.reference()?,
+ properties: self.properties()?,
+ tail: self.main.bit_long()?,
+ },
+ "BDMDBOBJECTDEPENDENCY" => Body::Dependency {
+ properties: self.properties()?,
+ tail: self.main.bit_long()?,
+ entity: self.reference()?,
+ },
+ _ => Body::Properties(self.properties()?),
+ })
+ }
+
+ fn reference(&mut self) -> Option[ {
+ let (code, handle) = self.handles.handle(self.own)?;
+ Some(Ref::new(Handle::from(handle), code))
+ }
+
+ fn properties(&mut self) -> Option] {
+ let count = self.count()?;
+ let mut properties = Vec::with_capacity(count.min(64));
+ for _ in 0..count {
+ let name = self.text()?;
+ let kind = self.main.byte()?;
+ properties.push((name, self.value(kind, 0)?));
+ }
+ Some(Properties(properties))
+ }
+
+ fn value(&mut self, kind: u8, depth: u8) -> Option {
+ // Lists and maps nest a level or two; a deeper one is not a property
+ // list.
+ if depth > 4 {
+ return None;
+ }
+ Some(match kind {
+ 2 => Value::Text(self.text()?),
+ 3 => Value::Integer(self.main.bit_long()?),
+ 4 => Value::Real(self.main.bit_double()?),
+ 5 => Value::Flag(self.main.bit()?),
+ 6 => Value::Byte(self.main.byte()?),
+ 7 => {
+ let length = self.main.byte()?;
+ Value::Raw(
+ (0..length)
+ .map(|_| self.main.byte())
+ .collect::>()?,
+ )
+ }
+ 8 => Value::Object {
+ kind: self.main.byte()?,
+ target: self.reference()?,
+ },
+ 9 => {
+ let element = self.main.byte()?;
+ let count = self.count()?;
+ Value::List {
+ element,
+ items: (0..count)
+ .map(|_| self.value(element, depth + 1))
+ .collect:: >()?,
+ }
+ }
+ 10 => {
+ let key = self.main.byte()?;
+ let value = self.main.byte()?;
+ let count = self.count()?;
+ Value::Map {
+ key,
+ value,
+ entries: (0..count)
+ .map(|_| Some((self.value(key, depth + 1)?, self.value(value, depth + 1)?)))
+ .collect:: >()?,
+ }
+ }
+ _ => return None,
+ })
+ }
+
+ /// An element count. Every element takes at least one bit of one of the
+ /// streams, so a count beyond the record's bits is not one.
+ fn count(&mut self) -> Option {
+ let count = usize::try_from(self.main.bit_long()?).ok()?;
+ (count <= self.main.data.len() * 8).then_some(count)
+ }
+
+ /// A string from the string stream: a length, then UTF-16 code units.
+ fn text(&mut self) -> Option {
+ let length = usize::try_from(self.strings.bit_short()?).ok()?;
+ if length * 16 > self.strings.end - self.strings.pos {
+ return None;
+ }
+ let units: Vec = (0..length)
+ .map(|_| self.strings.raw_short())
+ .collect::>()?;
+ Some(String::from_utf16_lossy(&units))
+ }
+}
+
+struct Encoder {
+ main: Writer,
+ strings: Writer,
+ handles: Writer,
+ own: u64,
+}
+
+impl Encoder {
+ fn body(&mut self, body: &Body) {
+ match body {
+ Body::Properties(properties) => self.properties(properties),
+ Body::ConstraintManager {
+ counts,
+ children,
+ settings,
+ } => {
+ for count in counts {
+ self.main.bit_long(*count);
+ }
+ for child in children {
+ self.handles.reference(*child, self.own);
+ }
+ self.properties(settings);
+ }
+ Body::Object {
+ lead,
+ lead_count,
+ entity,
+ properties,
+ tail,
+ } => {
+ self.main.byte(*lead);
+ self.main.bit_long(*lead_count);
+ self.handles.reference(*entity, self.own);
+ self.properties(properties);
+ self.main.bit_long(*tail);
+ }
+ Body::Dependency {
+ properties,
+ tail,
+ entity,
+ } => {
+ self.properties(properties);
+ self.main.bit_long(*tail);
+ self.handles.reference(*entity, self.own);
+ }
+ }
+ }
+
+ fn properties(&mut self, properties: &Properties) {
+ self.main.bit_long(properties.0.len() as i32);
+ for (name, value) in &properties.0 {
+ self.text(name);
+ self.main.byte(value.kind());
+ self.value(value);
+ }
+ }
+
+ fn value(&mut self, value: &Value) {
+ match value {
+ Value::Text(text) => self.text(text),
+ Value::Integer(integer) => self.main.bit_long(*integer),
+ Value::Real(real) => self.main.bit_double(*real),
+ Value::Flag(flag) => self.main.bit(*flag),
+ Value::Byte(byte) => self.main.byte(*byte),
+ Value::Raw(bytes) => {
+ self.main.byte(bytes.len() as u8);
+ for byte in bytes {
+ self.main.byte(*byte);
+ }
+ }
+ Value::Object { kind, target } => {
+ self.main.byte(*kind);
+ self.handles.reference(*target, self.own);
+ }
+ Value::List { element, items } => {
+ self.main.byte(*element);
+ self.main.bit_long(items.len() as i32);
+ for item in items {
+ self.value(item);
+ }
+ }
+ Value::Map {
+ key,
+ value,
+ entries,
+ } => {
+ self.main.byte(*key);
+ self.main.byte(*value);
+ self.main.bit_long(entries.len() as i32);
+ for (key, value) in entries {
+ self.value(key);
+ self.value(value);
+ }
+ }
+ }
+ }
+
+ fn text(&mut self, text: &str) {
+ let units: Vec = text.encode_utf16().collect();
+ self.strings.bit_short(units.len() as i16);
+ for unit in units {
+ self.strings.raw_short(unit);
+ }
+ }
+}
+
+/// A bit range of a record, read most significant bit first.
+pub(super) struct Bits<'a> {
+ data: &'a [u8],
+ pos: usize,
+ end: usize,
+}
+
+impl<'a> Bits<'a> {
+ fn new(data: &'a [u8], pos: usize, end: usize) -> Self {
+ Self {
+ data,
+ pos,
+ end: end.min(data.len() * 8),
+ }
+ }
+
+ fn bit(&mut self) -> Option {
+ if self.pos >= self.end {
+ return None;
+ }
+ let bit = self.data[self.pos / 8] >> (7 - self.pos % 8) & 1;
+ self.pos += 1;
+ Some(bit == 1)
+ }
+
+ fn bits(&mut self, count: u32) -> Option {
+ (0..count).try_fold(0, |value, _| Some(value << 1 | u32::from(self.bit()?)))
+ }
+
+ fn byte(&mut self) -> Option {
+ self.bits(8).map(|value| value as u8)
+ }
+
+ fn raw_short(&mut self) -> Option {
+ Some(u16::from_le_bytes([self.byte()?, self.byte()?]))
+ }
+
+ fn raw_long(&mut self) -> Option {
+ Some(u32::from_le_bytes([
+ self.byte()?,
+ self.byte()?,
+ self.byte()?,
+ self.byte()?,
+ ]))
+ }
+
+ fn bit_short(&mut self) -> Option {
+ Some(match self.bits(2)? {
+ 0 => self.raw_short()? as i16,
+ 1 => i16::from(self.byte()?),
+ 2 => 0,
+ _ => 256,
+ })
+ }
+
+ fn bit_long(&mut self) -> Option {
+ match self.bits(2)? {
+ 0 => Some(self.raw_long()? as i32),
+ 1 => Some(i32::from(self.byte()?)),
+ 2 => Some(0),
+ _ => None,
+ }
+ }
+
+ fn bit_double(&mut self) -> Option {
+ match self.bits(2)? {
+ 0 => {
+ let mut bytes = [0; 8];
+ for byte in &mut bytes {
+ *byte = self.byte()?;
+ }
+ Some(f64::from_le_bytes(bytes))
+ }
+ 1 => Some(1.0),
+ 2 => Some(0.0),
+ _ => None,
+ }
+ }
+
+ /// The object type of a DWG 2010 or later record.
+ fn object_type(&mut self) -> Option {
+ match self.bits(2)? {
+ 0 => self.byte().map(u16::from),
+ 1 => self.byte().map(|byte| 0x1F0 + u16::from(byte)),
+ _ => self.raw_short(),
+ }
+ }
+
+ /// A handle reference as its code and the handle; the offset forms count
+ /// from `reference`.
+ fn handle(&mut self, reference: u64) -> Option<(u8, u64)> {
+ let form = self.byte()?;
+ let mut value = 0u64;
+ for _ in 0..form & 0x0F {
+ value = value << 8 | u64::from(self.byte()?);
+ }
+ let code = form >> 4;
+ let handle = match code {
+ 0x6 => reference.checked_add(1)?,
+ 0x8 => reference.checked_sub(1)?,
+ 0xA => reference.checked_add(value)?,
+ 0xC => reference.checked_sub(value)?,
+ _ => value,
+ };
+ Some((code, handle))
+ }
+}
+
+/// The bits of a record being written, most significant bit first.
+#[derive(Default)]
+struct Writer {
+ bytes: Vec,
+ len: usize,
+}
+
+impl Writer {
+ fn bit(&mut self, bit: bool) {
+ if self.len.is_multiple_of(8) {
+ self.bytes.push(0);
+ }
+ if bit {
+ let last = self.bytes.len() - 1;
+ self.bytes[last] |= 0x80 >> (self.len % 8);
+ }
+ self.len += 1;
+ }
+
+ fn bits(&mut self, value: u32, count: u32) {
+ for shift in (0..count).rev() {
+ self.bit(value >> shift & 1 == 1);
+ }
+ }
+
+ fn byte(&mut self, byte: u8) {
+ self.bits(u32::from(byte), 8);
+ }
+
+ fn raw_short(&mut self, value: u16) {
+ for byte in value.to_le_bytes() {
+ self.byte(byte);
+ }
+ }
+
+ fn bit_short(&mut self, value: i16) {
+ match value {
+ 0 => self.bits(2, 2),
+ 256 => self.bits(3, 2),
+ 1..=255 => {
+ self.bits(1, 2);
+ self.byte(value as u8);
+ }
+ _ => {
+ self.bits(0, 2);
+ self.raw_short(value as u16);
+ }
+ }
+ }
+
+ fn bit_long(&mut self, value: i32) {
+ match value {
+ 0 => self.bits(2, 2),
+ 1..=255 => {
+ self.bits(1, 2);
+ self.byte(value as u8);
+ }
+ _ => {
+ self.bits(0, 2);
+ for byte in value.to_le_bytes() {
+ self.byte(byte);
+ }
+ }
+ }
+ }
+
+ fn bit_double(&mut self, value: f64) {
+ if value.to_bits() == 1.0f64.to_bits() {
+ self.bits(1, 2);
+ } else if value.to_bits() == 0.0f64.to_bits() {
+ self.bits(2, 2);
+ } else {
+ self.bits(0, 2);
+ for byte in value.to_le_bytes() {
+ self.byte(byte);
+ }
+ }
+ }
+
+ fn object_type(&mut self, value: u16) {
+ if value <= 0xFF {
+ self.bits(0, 2);
+ self.byte(value as u8);
+ } else if (0x1F0..=0x2EF).contains(&value) {
+ self.bits(1, 2);
+ self.byte((value - 0x1F0) as u8);
+ } else {
+ self.bits(2, 2);
+ self.raw_short(value);
+ }
+ }
+
+ /// A handle with `code`; an offset form is recomputed from `own`, and
+ /// falls back to the matching other offset form when the handle moved.
+ fn handle(&mut self, code: u8, handle: u64, own: u64) {
+ let (code, value) = match code {
+ 0x6 | 0x8 | 0xA | 0xC => {
+ let difference = i128::from(handle) - i128::from(own);
+ match (code, difference) {
+ (0x6, 1) => (0x6, 0),
+ (0x8, -1) => (0x8, 0),
+ (_, difference) if difference > 0 => (0xA, difference as u64),
+ (_, difference) if difference < 0 => (0xC, difference.unsigned_abs() as u64),
+ _ => (0x4, handle),
+ }
+ }
+ code => (code, handle),
+ };
+ let bytes: Vec = value
+ .to_be_bytes()
+ .into_iter()
+ .skip_while(|byte| *byte == 0)
+ .collect();
+ self.byte(code << 4 | bytes.len() as u8);
+ for byte in bytes {
+ self.byte(byte);
+ }
+ }
+
+ fn reference(&mut self, reference: Ref, own: u64) {
+ self.handle(reference.code, reference.handle.value(), own);
+ }
+
+ fn append(&mut self, other: &Writer) {
+ for index in 0..other.len {
+ self.bit(other.bytes[index / 8] >> (7 - index % 8) & 1 == 1);
+ }
+ }
+
+ fn into_bytes(self) -> Vec {
+ self.bytes
+ }
+}
diff --git a/src/scene/bricscad_parameters/record_tests.rs b/src/scene/bricscad_parameters/record_tests.rs
new file mode 100644
index 0000000000..edad3ca260
--- /dev/null
+++ b/src/scene/bricscad_parameters/record_tests.rs
@@ -0,0 +1,117 @@
+use super::record::{decode, encode, Body, Ref, Value};
+use super::*;
+
+/// The BricsCAD drawing in `tests/fixtures/bricscad` (see its README).
+fn fixture() -> Document {
+ let path = concat!(
+ env!("CARGO_MANIFEST_DIR"),
+ "/tests/fixtures/bricscad/visibility-states.dwg"
+ );
+ let bytes = std::fs::read(path).expect("read the fixture");
+ crate::io::load_bytes_finalized(std::path::Path::new("visibility-states.dwg"), bytes)
+ .expect("open the fixture")
+}
+
+/// Every BricsCAD object of `document` with its class, record bytes, handle
+/// stream bits and version.
+fn bricscad_records(
+ document: &Document,
+) -> Vec<(Handle, String, Vec, i64, document::DxfVersion)> {
+ let mut records: Vec<_> = document
+ .objects
+ .iter()
+ .filter_map(|(handle, object)| match object {
+ ObjectType::Unknown {
+ type_name,
+ raw_dwg_data: Some(data),
+ raw_dwg_handle_bits,
+ raw_dwg_version: Some(version),
+ ..
+ } if type_name.to_ascii_uppercase().starts_with("BDM") => Some((
+ *handle,
+ type_name.clone(),
+ data.clone(),
+ *raw_dwg_handle_bits,
+ *version,
+ )),
+ _ => None,
+ })
+ .collect();
+ records.sort_by_key(|record| record.0);
+ records
+}
+
+#[test]
+fn every_bricscad_record_encodes_to_the_bits_it_was_read_from() {
+ let document = fixture();
+ let records = bricscad_records(&document);
+ assert_eq!(records.len(), 87, "the fixture's BricsCAD objects");
+ for (handle, class, data, handle_bits, version) in records {
+ let record = decode(&class, &data, handle_bits, version)
+ .unwrap_or_else(|| panic!("{class} {handle:?} does not decode"));
+ assert_eq!(record.handle, handle, "{class}");
+ assert_eq!(
+ encode(&record),
+ (data, handle_bits),
+ "{class} {handle:?} encodes to other bits"
+ );
+ }
+}
+
+#[test]
+fn the_three_classes_around_a_property_list_decode_to_their_parts() {
+ let document = fixture();
+ let manager = record(&document, Handle::from(0x1A5u64)).unwrap();
+ let Body::ConstraintManager {
+ counts, children, ..
+ } = &manager.body
+ else {
+ panic!("{:?}", manager.body);
+ };
+ assert_eq!(*counts, [2, 2, 0, 0, 0]);
+ assert_eq!(
+ children
+ .iter()
+ .map(|child| child.handle)
+ .collect::>(),
+ [Handle::from(0x1A6u64), Handle::from(0x1E1u64)]
+ );
+ let object = record(&document, Handle::from(0x1A6u64)).unwrap();
+ let Body::Object {
+ entity, properties, ..
+ } = &object.body
+ else {
+ panic!("{:?}", object.body);
+ };
+ assert_eq!(
+ entity.handle,
+ Handle::from(0x146u64),
+ "the reference it stands for"
+ );
+ assert_eq!(properties.text("NAME"), Some("Objekt_1"));
+ let dependency = record(&document, Handle::from(0x1A7u64)).unwrap();
+ let Body::Dependency { entity, .. } = &dependency.body else {
+ panic!("{:?}", dependency.body);
+ };
+ assert_eq!(entity.handle, Handle::from(0x146u64));
+}
+
+#[test]
+fn a_changed_record_reads_back_as_changed() {
+ let document = fixture();
+ let mut feature = record(&document, Handle::from(0x1C7u64)).unwrap();
+ assert_eq!(feature.body.properties().text("LastKeyValue"), Some("Off"));
+ // Longer text, a new handle further away and every reference moved: the
+ // offset forms are recomputed from the new handle.
+ feature.body.properties_mut().set(
+ "LastKeyValue",
+ Value::Text("A much longer state name".into()),
+ );
+ feature.handle = Handle::from(0x12_3456u64);
+ feature.refs_mut(|reference: &mut Ref| {
+ reference.handle = Handle::from(reference.handle.value() + 0x1000);
+ });
+ let (data, handle_bits) = encode(&feature);
+ let read = decode("BDMDBFEATUREDATA", &data, handle_bits, feature.version).unwrap();
+ assert_eq!(read, feature);
+}
diff --git a/src/scene/bricscad_parameters/switch.rs b/src/scene/bricscad_parameters/switch.rs
new file mode 100644
index 0000000000..194a96125c
--- /dev/null
+++ b/src/scene/bricscad_parameters/switch.rs
@@ -0,0 +1,1318 @@
+//! Switching the visibility state a BricsCAD parametric block reference
+//! shows, the way BricsCAD does it, so that BricsCAD keeps the block's
+//! parameters.
+//!
+//! A reference shows the block itself or an anonymous copy of it, and
+//! BricsCAD reads the states a reference shows from the parameter objects of
+//! that copy. When a state is changed in BricsCAD, it starts from the states
+//! the reference's entry in model space lists: a `BmAssemblyParameters`
+//! feature, linked to the reference through a `BDMOBJECT` and a dependency,
+//! that lists every parameter the reference was ever set to with the state it
+//! shows. BricsCAD shares a copy between references that show the same
+//! states.
+//!
+//! Switching here:
+//! 1. works out the states the reference is to show and the parameters its
+//! entry lists;
+//! 2. points the reference at the block when those are the block's own states,
+//! at a copy of the block that shows them when there is one, or at a new
+//! copy: the block's members and all its parameter objects cloned under new
+//! handles, with the states set as BricsCAD sets them;
+//! 3. moves the reference's attributes on or off `*SUPPRESS` with their
+//! definitions in the block it now shows;
+//! 4. writes the reference's entry in model space, creating it, and model
+//! space's own parameter objects when there are none.
+
+use std::collections::{BTreeMap, BTreeSet};
+
+use document::objects::{
+ AssocAction, AssocDependency, AssocEvalValue, AssocEvalVariant, AssociativeData,
+ AssociativeObject, ObjectType,
+};
+use document::{Document, EntityType, Handle};
+use rustc_hash::{FxHashMap, FxHashSet};
+
+use super::record::{self, Body, Properties, Record, Ref, Value};
+use super::{
+ database_entry, features, original_block, record as read_record, shown_block,
+ visibility_parameters,
+};
+use crate::scene::Scene;
+
+/// The layer BricsCAD moves the members a state hides to.
+pub(super) const SUPPRESS_LAYER: &str = "*SUPPRESS";
+
+const UNSUPPORTED: &str = "This BricsCAD parametric block cannot be switched here.";
+const NOT_IN_MODEL_SPACE: &str = "Only a BricsCAD block reference in model space can be switched.";
+const NO_SUCH_STATE: &str = "The block has no such visibility state.";
+
+type Result = std::result::Result;
+
+/// Whether [`Scene::set_bricscad_visibility`] can switch `insert`: a
+/// reference in model space to a BricsCAD parametric block, or to a copy of
+/// one, whose parameter objects read.
+pub(crate) fn can_switch(document: &Document, insert: Handle) -> bool {
+ document.get_entity(insert).is_some_and(|entity| {
+ entity.common().owner_handle == document.header.model_space_block_handle
+ }) && super::master_block(document, insert).is_some()
+}
+
+impl Scene {
+ /// Show `state` of the visibility parameter `parameter` on the reference
+ /// `insert`, as BricsCAD does. `Ok(false)` when the reference shows it
+ /// already. On an error the document is left as it was only when the
+ /// caller works on a copy of it; the property and automation paths do.
+ pub(crate) fn set_bricscad_visibility(
+ &mut self,
+ insert: Handle,
+ parameter: &str,
+ state: &str,
+ ) -> Result {
+ let document = &self.document;
+ if !can_switch(document, insert) {
+ return Err(NOT_IN_MODEL_SPACE);
+ }
+ let shown = shown_block(document, insert).ok_or(UNSUPPORTED)?;
+ let master = original_block(document, shown).unwrap_or(shown);
+ let master_parameters = visibility_parameters(document, master);
+ let shown_parameters = visibility_parameters(document, shown);
+ let names: Vec<&str> = master_parameters.iter().map(|p| p.name.as_str()).collect();
+ if names.is_empty()
+ || shown_parameters
+ .iter()
+ .map(|p| p.name.as_str())
+ .ne(names.iter().copied())
+ {
+ return Err(UNSUPPORTED);
+ }
+ let index = names
+ .iter()
+ .position(|name| *name == parameter)
+ .ok_or(NO_SUCH_STATE)?;
+ if !master_parameters[index].states.iter().any(|s| s == state) {
+ return Err(NO_SUCH_STATE);
+ }
+ let shown_state = |parameters: &[super::VisibilityParameter]| -> Result> {
+ parameters
+ .iter()
+ .map(|p| {
+ p.current
+ .and_then(|current| p.states.get(current).cloned())
+ .ok_or(UNSUPPORTED)
+ })
+ .collect()
+ };
+ let defaults = shown_state(&master_parameters)?;
+ let current = shown_state(&shown_parameters)?;
+ if current[index] == state {
+ return Ok(false);
+ }
+ let mut target = current.clone();
+ target[index] = state.to_string();
+
+ // The entry lists what it listed, what differs from the block, and
+ // the parameter set now, each in the state it shows.
+ let entry = find_entry(document, insert);
+ let mut listed: BTreeSet = entry
+ .as_ref()
+ .and_then(|(_, record)| record.body.properties().get("expr.const"))
+ .and_then(Value::entries)
+ .map(|entries| {
+ entries
+ .iter()
+ .filter_map(|(key, _)| key.text().map(str::to_string))
+ .filter(|key| names.contains(&key.as_str()))
+ .collect()
+ })
+ .unwrap_or_default();
+ for (k, name) in names.iter().enumerate() {
+ if current[k] != defaults[k] {
+ listed.insert(name.to_string());
+ }
+ }
+ listed.insert(parameter.to_string());
+ let overrides: Vec<(String, String)> = listed
+ .iter()
+ .map(|name| {
+ let k = names.iter().position(|n| n == name).unwrap_or(index);
+ (name.clone(), target[k].clone())
+ })
+ .collect();
+ let names: Vec = names.iter().map(|name| name.to_string()).collect();
+
+ let block = if target == defaults {
+ master
+ } else if let Some(copy) = find_copy(&self.document, master, &target) {
+ copy
+ } else {
+ let states: BTreeMap =
+ names.iter().cloned().zip(target.iter().cloned()).collect();
+ self.clone_parametric_copy(master, &states, &listed)?
+ };
+ if block != shown {
+ let name = self
+ .document
+ .block_records
+ .iter()
+ .find(|record| record.handle == block)
+ .map(|record| record.name.clone())
+ .ok_or(UNSUPPORTED)?;
+ self.repoint_representation(insert, shown, block, &name);
+ follow_attribute_definitions(&mut self.document, insert, block);
+ }
+ write_entry(&mut self.document, insert, master, overrides)?;
+ Ok(true)
+ }
+
+ /// A new anonymous copy of the BricsCAD parametric block `master` showing
+ /// `states`, with the parameters in `listed` set on it: the members and
+ /// every object under the block's extension dictionary cloned under new
+ /// handles, then the states applied.
+ pub(super) fn clone_parametric_copy(
+ &mut self,
+ master: Handle,
+ states: &BTreeMap,
+ listed: &BTreeSet,
+ ) -> Result {
+ let document = &self.document;
+ let master_dictionary = document
+ .extension_dictionary_handle(master)
+ .ok_or(UNSUPPORTED)?;
+ let objects = owned_tree(document, master_dictionary)?;
+ let records: FxHashMap = objects
+ .iter()
+ .filter(|handle| {
+ matches!(
+ document.objects.get(handle),
+ Some(ObjectType::Unknown { .. })
+ )
+ })
+ .map(|handle| Some((*handle, read_record(document, *handle)?)))
+ .collect::>()
+ .ok_or(UNSUPPORTED)?;
+ let tag = block_tag(document, master);
+ let master_record = document
+ .block_records
+ .iter()
+ .find(|record| record.handle == master)
+ .ok_or(UNSUPPORTED)?;
+ let master_name = master_record.name.clone();
+ let master_members = crate::scene::block_authoring::members(document, master);
+ let entities: Vec = master_members
+ .iter()
+ .map(|handle| document.get_entity(*handle).cloned())
+ .collect::>()
+ .ok_or(UNSUPPORTED)?;
+ let layers: Vec = entities
+ .iter()
+ .map(|entity| entity.common().layer.clone())
+ .collect();
+ let base = crate::scene::render_graph::block_base_point(document, &master_name);
+ let name = next_anonymous_name(document);
+
+ self.define_block_raw_unbumped(&name, base, entities);
+ let record = self
+ .document
+ .block_records
+ .get_mut(&name)
+ .ok_or(UNSUPPORTED)?;
+ record.flags.anonymous = true;
+ let copy = record.handle;
+ let copy_members = crate::scene::block_authoring::members(&self.document, copy);
+ if copy_members.len() != master_members.len() {
+ return Err(UNSUPPORTED);
+ }
+ self.own_copied_xdicts(master_members.clone(), copy_members.clone());
+
+ let document = &mut self.document;
+ // A block BricsCAD never copied has no tag yet; BricsCAD gives it one
+ // when it makes the first copy.
+ let tag = match tag {
+ Some(tag) => tag,
+ None => give_block_tag(document, master),
+ };
+ let copy_dictionary = document.ensure_extension_dictionary(copy);
+ let mut cloned: FxHashMap = FxHashMap::default();
+ for &handle in &objects {
+ let new = if handle == master_dictionary {
+ copy_dictionary
+ } else {
+ document.allocate_handle()
+ };
+ cloned.insert(handle, new);
+ }
+ let members: FxHashMap = master_members
+ .iter()
+ .copied()
+ .zip(copy_members.iter().copied())
+ .collect();
+ let remap = |handle: Handle| {
+ if handle == master {
+ copy
+ } else {
+ cloned
+ .get(&handle)
+ .or_else(|| members.get(&handle))
+ .copied()
+ .unwrap_or(handle)
+ }
+ };
+ let mut clones = Vec::with_capacity(objects.len());
+ for &handle in &objects {
+ let new = remap(handle);
+ let clone = match document.objects.get(&handle).ok_or(UNSUPPORTED)? {
+ ObjectType::Dictionary(dictionary) => {
+ let mut dictionary = dictionary.clone();
+ dictionary.handle = new;
+ dictionary.owner = remap(dictionary.owner);
+ for (_, entry) in &mut dictionary.entries {
+ *entry = remap(*entry);
+ }
+ for reactor in &mut dictionary.reactors {
+ *reactor = remap(*reactor);
+ }
+ dictionary.xdictionary_handle = dictionary.xdictionary_handle.map(remap);
+ ObjectType::Dictionary(dictionary)
+ }
+ ObjectType::Associative(object) => {
+ let mut object = object.clone();
+ remap_associative(&mut object, &remap)?;
+ ObjectType::Associative(object)
+ }
+ // The block's draw order, member by member.
+ ObjectType::SortEntitiesTable(table) => {
+ let mut order = document::objects::SortEntitiesTable::for_block(copy);
+ order.handle = new;
+ order.owner_handle = remap(table.owner_handle);
+ for entry in table.entries() {
+ order.add_entry(remap(entry.entity_handle), remap(entry.sort_handle));
+ }
+ ObjectType::SortEntitiesTable(order)
+ }
+ ObjectType::Unknown { type_name, .. } => {
+ let mut record = records[&handle].clone();
+ record.handle = new;
+ record.refs_mut(|reference| reference.handle = remap(reference.handle));
+ unknown(type_name, &record)
+ }
+ _ => return Err(UNSUPPORTED),
+ };
+ clones.push((new, clone));
+ }
+ for (handle, object) in clones {
+ document.objects.insert(handle, object);
+ }
+ // The copies' reactors name the clones of the master members'
+ // parameter objects; anything else they named stays with the master.
+ for (original, copy_member) in master_members.iter().zip(©_members) {
+ let reactors: Vec = document
+ .get_entity(*original)
+ .map(|entity| {
+ entity
+ .common()
+ .reactors
+ .iter()
+ .filter_map(|reactor| cloned.get(reactor).copied())
+ .collect()
+ })
+ .unwrap_or_default();
+ if let Some(entity) = document.get_entity_mut(*copy_member) {
+ entity.common_mut().reactors = reactors;
+ }
+ }
+
+ // The copy names the block it was made from, member by member.
+ let manager = database_entry(document, copy, "PERSIDMANAGER").ok_or(UNSUPPORTED)?;
+ let mut record = read_record(document, manager).ok_or(UNSUPPORTED)?;
+ let properties = record.body.properties_mut();
+ properties
+ .0
+ .retain(|(name, _)| !name.starts_with("original."));
+ properties.0.push((
+ "original.block".into(),
+ Value::Object {
+ kind: 1,
+ target: Ref::new(master, 5),
+ },
+ ));
+ properties.0.push((
+ "original.map".into(),
+ Value::Map {
+ key: 7,
+ value: 8,
+ entries: master_members
+ .iter()
+ .zip(©_members)
+ .map(|(original, member)| {
+ (
+ Value::Raw(handle_bytes(*original)),
+ Value::Object {
+ kind: 0,
+ target: Ref::new(*member, 4),
+ },
+ )
+ })
+ .collect(),
+ },
+ ));
+ properties.0.push(("original.tag".into(), Value::Text(tag)));
+ store(document, &record);
+
+ let layers: FxHashMap = copy_members.iter().copied().zip(layers).collect();
+ apply_states(
+ document,
+ copy,
+ ©_members,
+ &layers,
+ states,
+ listed,
+ false,
+ )?;
+ Ok(copy)
+ }
+}
+
+/// Every object owned, directly or further down, by `root`, root first.
+fn owned_tree(document: &Document, root: Handle) -> Result> {
+ let mut children: FxHashMap> = FxHashMap::default();
+ for &handle in document.objects.keys() {
+ if let Some(owner) = document.object_owner(handle) {
+ children.entry(owner).or_default().push(handle);
+ }
+ }
+ let mut seen = FxHashSet::default();
+ let mut order = Vec::new();
+ let mut stack = vec![root];
+ while let Some(handle) = stack.pop() {
+ if handle.is_null() || !seen.insert(handle) {
+ continue;
+ }
+ match document.objects.get(&handle) {
+ Some(
+ ObjectType::Dictionary(_)
+ | ObjectType::Unknown { .. }
+ | ObjectType::SortEntitiesTable(_),
+ ) => {}
+ Some(ObjectType::Associative(AssociativeObject {
+ data:
+ AssociativeData::Network(_)
+ | AssociativeData::Variable(_)
+ | AssociativeData::ValueDependency(_),
+ ..
+ })) => {}
+ _ => return Err(UNSUPPORTED),
+ }
+ order.push(handle);
+ if let Some(owned) = children.get(&handle) {
+ let mut owned = owned.clone();
+ owned.sort_unstable_by_key(|handle| std::cmp::Reverse(*handle));
+ stack.extend(owned);
+ }
+ }
+ Ok(order)
+}
+
+/// Point every handle of an associative network, variable or value dependency
+/// through `remap`.
+fn remap_associative(
+ object: &mut AssociativeObject,
+ remap: &impl Fn(Handle) -> Handle,
+) -> Result<()> {
+ object.handle = remap(object.handle);
+ object.owner = remap(object.owner);
+ for reactor in &mut object.reactors {
+ *reactor = remap(*reactor);
+ }
+ object.xdictionary_handle = object.xdictionary_handle.map(remap);
+ let action = |action: &mut AssocAction| {
+ action.owning_network = remap(action.owning_network);
+ action.action_body = remap(action.action_body);
+ for dependency in &mut action.dependencies {
+ dependency.dependency = remap(dependency.dependency);
+ }
+ for parameter in &mut action.owned_parameters {
+ *parameter = remap(*parameter);
+ }
+ for value in &mut action.values {
+ value.controlled_object_dependency = remap(value.controlled_object_dependency);
+ for variable in &mut value.variables {
+ variable.handle = remap(variable.handle);
+ if let AssocEvalValue::Handle(handle) = &mut variable.value.value {
+ *handle = remap(*handle);
+ }
+ }
+ }
+ };
+ let dependency = |dependency: &mut AssocDependency| {
+ dependency.dependent_on = remap(dependency.dependent_on);
+ dependency.read_dependency = remap(dependency.read_dependency);
+ dependency.node = remap(dependency.node);
+ dependency.dependency_body = remap(dependency.dependency_body);
+ };
+ match &mut object.data {
+ AssociativeData::Network(network) => {
+ action(&mut network.action);
+ for child in &mut network.actions {
+ child.dependency = remap(child.dependency);
+ }
+ for owned in &mut network.owned_actions {
+ *owned = remap(*owned);
+ }
+ }
+ AssociativeData::Variable(variable) => {
+ action(&mut variable.action);
+ for owned in &mut variable.dependencies {
+ owned.dependency = remap(owned.dependency);
+ }
+ if let AssocEvalValue::Handle(handle) = &mut variable.value.value {
+ *handle = remap(*handle);
+ }
+ }
+ AssociativeData::ValueDependency(value) => {
+ dependency(&mut value.dependency);
+ if let AssocEvalValue::Handle(handle) = &mut value.value.value {
+ *handle = remap(*handle);
+ }
+ }
+ _ => return Err(UNSUPPORTED),
+ }
+ Ok(())
+}
+
+/// Set the copy's parameter objects, associative variables and member layers
+/// to `states`, as BricsCAD leaves a copy it made: for each visibility
+/// parameter the state, the values of its table's columns and, for a
+/// parameter in `listed`, the marks BricsCAD sets on an instance's own
+/// parameter; for each suppression its value, status and the layers of the
+/// members it moved to `*SUPPRESS`. With `keep_keys` the key reactors keep
+/// whether they are enabled and the number they hold (model space of a block
+/// drawing, where BricsCAD leaves the keys of parameters it was not asked
+/// about as they are).
+pub(super) fn apply_states(
+ document: &mut Document,
+ copy: Handle,
+ members: &[Handle],
+ layers: &FxHashMap,
+ states: &BTreeMap,
+ listed: &BTreeSet,
+ keep_keys: bool,
+) -> Result<()> {
+ let features = features(document, copy);
+ let mut columns: FxHashMap = FxHashMap::default();
+ let mut suppressions = Vec::new();
+ for &feature in &features {
+ let mut record = read_record(document, feature).ok_or(UNSUPPORTED)?;
+ let properties = record.body.properties();
+ match properties.text("Feature_type") {
+ Some("BdmConfigurationFeature")
+ if properties.text("TableType") == Some("VisibilityStates") => {}
+ Some("BdmSuppressFeature") => {
+ suppressions.push(feature);
+ continue;
+ }
+ _ => continue,
+ }
+ let table = super::properties(
+ document,
+ properties
+ .get("ConfigTable")
+ .and_then(Value::object)
+ .ok_or(UNSUPPORTED)?,
+ )
+ .ok_or(UNSUPPORTED)?;
+ let name = table
+ .text("KeyName")
+ .or_else(|| properties.text("Name"))
+ .ok_or(UNSUPPORTED)?
+ .to_string();
+ let state = states.get(&name).ok_or(UNSUPPORTED)?;
+ let texts = |key: &str| -> Option> {
+ table.get(key)?.items()?.iter().map(Value::text).collect()
+ };
+ let keys = texts("KeyValues").ok_or(UNSUPPORTED)?;
+ let column_names = texts("ColNames").ok_or(UNSUPPORTED)?;
+ let values: Vec = table
+ .get("DblValues")
+ .and_then(Value::items)
+ .and_then(|items| {
+ items
+ .iter()
+ .map(|item| match item {
+ Value::Real(value) => Some(*value),
+ _ => None,
+ })
+ .collect()
+ })
+ .ok_or(UNSUPPORTED)?;
+ let row = keys
+ .iter()
+ .position(|key| key == state)
+ .ok_or(NO_SUCH_STATE)?;
+ let own = listed.contains(&name);
+ let reactors: Vec = properties
+ .get("Reactors")
+ .and_then(Value::items)
+ .map(|items| items.iter().filter_map(Value::object).collect())
+ .unwrap_or_default();
+ record
+ .body
+ .properties_mut()
+ .set("LastKeyValue", Value::Text(state.clone()));
+ store(document, &record);
+
+ for reactor in reactors {
+ let mut variable_reactor = read_record(document, reactor).ok_or(UNSUPPORTED)?;
+ let properties = variable_reactor.body.properties_mut();
+ let variable = properties
+ .get("VarId")
+ .and_then(Value::object)
+ .ok_or(UNSUPPORTED)?;
+ if properties.get("IsKeyVar") == Some(&Value::Flag(true)) {
+ properties.set("String", Value::Text(state.clone()));
+ if !keep_keys {
+ properties.set("IsEnabled", Value::Flag(!own));
+ }
+ if own {
+ properties.set("Value", Value::Real(row as f64));
+ set_variable(
+ document,
+ variable,
+ Some(row.to_string()),
+ AssocEvalVariant {
+ code: 90,
+ value: AssocEvalValue::Long(row as i32),
+ },
+ )?;
+ }
+ } else {
+ let column_name = properties.text("VarName").ok_or(UNSUPPORTED)?.to_string();
+ let column = column_names
+ .iter()
+ .position(|name| *name == column_name)
+ .ok_or(UNSUPPORTED)?;
+ let value = *values
+ .get(row * column_names.len() + column)
+ .ok_or(UNSUPPORTED)?;
+ properties.set("Value", Value::Real(value));
+ set_variable(
+ document,
+ variable,
+ None,
+ AssocEvalVariant {
+ code: 40,
+ value: AssocEvalValue::Real(value),
+ },
+ )?;
+ columns.insert(column_name, value);
+ }
+ store(document, &variable_reactor);
+ }
+ }
+
+ let order: FxHashMap =
+ members.iter().enumerate().map(|(k, h)| (*h, k)).collect();
+ let mut suppressed: FxHashSet = FxHashSet::default();
+ let layer_handle =
+ |document: &Document, name: &str| document.layers.get(name).map(|layer| layer.handle);
+ for feature in suppressions {
+ let mut record = read_record(document, feature).ok_or(UNSUPPORTED)?;
+ let reactors: Vec = record
+ .body
+ .properties()
+ .get("Reactors")
+ .and_then(Value::items)
+ .map(|items| items.iter().filter_map(Value::object).collect())
+ .unwrap_or_default();
+ let mut entities = Vec::new();
+ let mut value = None;
+ for reactor in reactors {
+ let mut reactor_record = read_record(document, reactor).ok_or(UNSUPPORTED)?;
+ let properties = reactor_record.body.properties();
+ if let Some(dependencies) = properties.get("pers_ids").and_then(Value::items) {
+ for dependency in dependencies.iter().filter_map(Value::object) {
+ match read_record(document, dependency).map(|record| record.body) {
+ Some(Body::Dependency { entity, .. }) => entities.push(entity.handle),
+ _ => return Err(UNSUPPORTED),
+ }
+ }
+ } else if let Some(variable) = properties.get("var").and_then(Value::object) {
+ let expression = match document.objects.get(&variable) {
+ Some(ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::Variable(variable),
+ ..
+ })) => variable.expression.clone(),
+ _ => return Err(UNSUPPORTED),
+ };
+ let suppress = evaluate(&expression, &columns).ok_or(UNSUPPORTED)?;
+ reactor_record
+ .body
+ .properties_mut()
+ .set("value", Value::Real(suppress));
+ store(document, &reactor_record);
+ set_variable(
+ document,
+ variable,
+ None,
+ AssocEvalVariant {
+ code: 90,
+ value: AssocEvalValue::Long(suppress as i32),
+ },
+ )?;
+ value = Some(suppress);
+ }
+ }
+ let suppress = value.ok_or(UNSUPPORTED)? != 0.0;
+ entities.sort_by_key(|entity| order.get(entity).copied().unwrap_or(usize::MAX));
+ let properties = record.body.properties_mut();
+ properties.set("Status", Value::Integer(if suppress { 32 } else { 0 }));
+ let Some(Value::Map { entries, .. }) = properties.get_mut("aEntLayerKey") else {
+ return Err(UNSUPPORTED);
+ };
+ entries.clear();
+ if suppress {
+ for entity in &entities {
+ let layer = layers.get(entity).ok_or(UNSUPPORTED)?;
+ let layer = layer_handle(document, layer).ok_or(UNSUPPORTED)?;
+ entries.push((
+ Value::Object {
+ kind: 0,
+ target: Ref::new(*entity, 4),
+ },
+ Value::Object {
+ kind: 1,
+ target: Ref::new(layer, 5),
+ },
+ ));
+ }
+ suppressed.extend(entities);
+ }
+ store(document, &record);
+ }
+
+ if !suppressed.is_empty() {
+ ensure_suppress_layer(document);
+ }
+ for member in members {
+ let layer = if suppressed.contains(member) {
+ SUPPRESS_LAYER.to_string()
+ } else {
+ layers.get(member).cloned().ok_or(UNSUPPORTED)?
+ };
+ if document
+ .get_entity(*member)
+ .is_some_and(|entity| entity.common().layer != layer)
+ {
+ if let Some(entity) = document.get_entity_mut(*member) {
+ entity.common_mut().layer = layer;
+ }
+ }
+ }
+ Ok(())
+}
+
+/// The value of a suppression's expression, such as `1 - look_3` or
+/// `1 - look_13 * look_14`, over the table columns.
+fn evaluate(expression: &str, columns: &FxHashMap) -> Option {
+ const RESULT: &str = "bricscad_suppression";
+ let mut table = crate::scene::named_parameters::ParameterTable::new();
+ for (name, value) in columns {
+ table.set(name, &value.to_string()).ok()?;
+ }
+ table.set(RESULT, expression).ok()?;
+ table.resolve(RESULT).ok().filter(|value| value.is_finite())
+}
+
+/// Set an associative variable and every read of it: BricsCAD keeps each
+/// value dependency at the value of the variable it reads, and takes a
+/// variable whose new value its reads already hold for unchanged, leaving
+/// what depends on it unevaluated.
+pub(super) fn set_variable(
+ document: &mut Document,
+ variable: Handle,
+ expression: Option,
+ value: AssocEvalVariant,
+) -> Result<()> {
+ let Some(ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::Variable(object),
+ reactors,
+ ..
+ })) = document.objects.get_mut(&variable)
+ else {
+ return Err(UNSUPPORTED);
+ };
+ if let Some(expression) = expression {
+ object.expression = expression;
+ }
+ object.value = value.clone();
+ for reactor in reactors.clone() {
+ if let Some(ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::ValueDependency(read),
+ ..
+ })) = document.objects.get_mut(&reactor)
+ {
+ if read.dependency.dependent_on == variable {
+ read.value = value.clone();
+ }
+ }
+ }
+ Ok(())
+}
+
+/// The layer BricsCAD keeps hidden members on: frozen and off.
+fn ensure_suppress_layer(document: &mut Document) {
+ if document.layers.get(SUPPRESS_LAYER).is_some() {
+ return;
+ }
+ let mut layer = document::tables::Layer::new(SUPPRESS_LAYER);
+ layer.flags.frozen = true;
+ layer.flags.off = true;
+ layer.handle = document.allocate_handle();
+ let _ = document.layers.add(layer);
+}
+
+/// A copy of `master`, other than the block itself, that shows `states`.
+fn find_copy(document: &Document, master: Handle, states: &[String]) -> Option {
+ document
+ .block_records
+ .iter()
+ .filter(|record| record.is_anonymous() && record.handle != master)
+ .filter(|record| original_block(document, record.handle) == Some(master))
+ .find(|record| {
+ let parameters = visibility_parameters(document, record.handle);
+ parameters.len() == states.len()
+ && parameters.iter().zip(states).all(|(parameter, state)| {
+ parameter
+ .current
+ .and_then(|current| parameter.states.get(current))
+ == Some(state)
+ })
+ })
+ .map(|record| record.handle)
+}
+
+/// After the reference `insert` was pointed at `block`, an attribute whose
+/// definition there is on `*SUPPRESS` goes there too, and one on `*SUPPRESS`
+/// whose definition is not goes back to the definition's layer, as BricsCAD
+/// keeps them.
+fn follow_attribute_definitions(document: &mut Document, insert: Handle, block: Handle) {
+ let definitions: FxHashMap =
+ crate::scene::block_authoring::members(document, block)
+ .into_iter()
+ .filter_map(|member| match document.get_entity(member) {
+ Some(EntityType::AttributeDefinition(definition)) => Some((
+ definition.tag.to_uppercase(),
+ definition.common.layer.clone(),
+ )),
+ _ => None,
+ })
+ .collect();
+ let needs = match document.get_entity(insert) {
+ Some(EntityType::Insert(reference)) => reference.attributes.iter().any(|attribute| {
+ target_layer(&definitions, &attribute.tag, &attribute.common.layer).is_some()
+ }),
+ _ => false,
+ };
+ if !needs {
+ return;
+ }
+ if let Some(EntityType::Insert(reference)) = document.get_entity_mut(insert) {
+ for attribute in &mut reference.attributes {
+ if let Some(layer) = target_layer(&definitions, &attribute.tag, &attribute.common.layer)
+ {
+ attribute.common.layer = layer;
+ attribute.common.raw_record = None;
+ }
+ }
+ }
+}
+
+fn target_layer(definitions: &FxHashMap, tag: &str, layer: &str) -> Option {
+ let definition = definitions.get(&tag.to_uppercase())?;
+ if definition == SUPPRESS_LAYER && layer != SUPPRESS_LAYER {
+ Some(SUPPRESS_LAYER.to_string())
+ } else if definition != SUPPRESS_LAYER && layer == SUPPRESS_LAYER {
+ Some(definition.clone())
+ } else {
+ None
+ }
+}
+
+/// The reference's entry in model space: the `BmAssemblyParameters` feature
+/// its `BDMOBJECT` leads to, with its record.
+pub(super) fn find_entry(document: &Document, insert: Handle) -> Option<(Handle, Record)> {
+ let reactors = document.get_entity(insert)?.common().reactors.clone();
+ reactors.into_iter().find_map(|reactor| {
+ let Body::Object { properties, .. } = read_record(document, reactor)?.body else {
+ return None;
+ };
+ properties
+ .get("PersIdDependencies")?
+ .items()?
+ .iter()
+ .filter_map(Value::object)
+ .find_map(|dependency| {
+ read_record(document, dependency)?
+ .reactors
+ .iter()
+ .find_map(|reactor| {
+ let feature = read_record(document, reactor.handle)?.owner.handle;
+ let record = read_record(document, feature)?;
+ (record.body.properties().text("Feature_type")
+ == Some("BmAssemblyParameters"))
+ .then_some((feature, record))
+ })
+ })
+ })
+}
+
+/// Write the reference's entry with `overrides`, creating it when there is
+/// none.
+fn write_entry(
+ document: &mut Document,
+ insert: Handle,
+ master: Handle,
+ overrides: Vec<(String, String)>,
+) -> Result<()> {
+ let constants = |entries: Vec<(String, String)>| Value::Map {
+ key: 2,
+ value: 2,
+ entries: entries
+ .into_iter()
+ .map(|(name, state)| (Value::Text(name), Value::Text(state)))
+ .collect(),
+ };
+ if let Some((_, mut record)) = find_entry(document, insert) {
+ if !record
+ .body
+ .properties_mut()
+ .set("expr.const", constants(overrides))
+ {
+ return Err(UNSUPPORTED);
+ }
+ store(document, &record);
+ return Ok(());
+ }
+
+ let template = |class: &str| template_record(document, master, class).ok_or(UNSUPPORTED);
+ let feature_template = template("BDMDBFEATUREDATA")?;
+ let reactor_template = template("BDMDBPERSIDREACTOR")?;
+ let dependency_template = template("BDMDBOBJECTDEPENDENCY")?;
+ let object_template = template("BDMOBJECT")?;
+ let (feature_manager, dependency_manager, constraint_manager) =
+ model_database(document, master)?;
+
+ let names: Vec = features(document, document.header.model_space_block_handle)
+ .into_iter()
+ .filter_map(|feature| {
+ super::properties(document, feature)?
+ .text("Name")
+ .map(str::to_string)
+ })
+ .collect();
+ let base = format!("*{:X}", insert.value());
+ let name = std::iter::once(base.clone())
+ .chain((1..).map(|n| format!("{base}_{n}")))
+ .find(|name| !names.contains(name))
+ .unwrap_or(base);
+ let mut constraint_record = read_record(document, constraint_manager).ok_or(UNSUPPORTED)?;
+ let object_number = match &constraint_record.body {
+ Body::ConstraintManager {
+ counts, children, ..
+ } => {
+ children
+ .iter()
+ .take(usize::try_from(counts[1]).unwrap_or(0))
+ .filter_map(|child| match read_record(document, child.handle)?.body {
+ Body::Object { properties, .. } => properties
+ .text("NAME")?
+ .strip_prefix("Objekt_")?
+ .parse::()
+ .ok(),
+ _ => None,
+ })
+ .max()
+ .unwrap_or(0)
+ + 1
+ }
+ _ => return Err(UNSUPPORTED),
+ };
+
+ let [feature, reactor, dependency, object] = [(); 4].map(|_| document.allocate_handle());
+ let object_lead = match &object_template.body {
+ Body::Object {
+ lead,
+ lead_count,
+ tail,
+ ..
+ } => (*lead, *lead_count, *tail),
+ _ => return Err(UNSUPPORTED),
+ };
+ let new_records = [
+ Record::like(
+ &feature_template,
+ feature,
+ Ref::new(feature_manager, 4),
+ Body::Properties(Properties(vec![
+ ("_ver".into(), Value::Byte(1)),
+ (
+ "Feature_type".into(),
+ Value::Text("BmAssemblyParameters".into()),
+ ),
+ ("Name".into(), Value::Text(name)),
+ (
+ "Reactors".into(),
+ Value::List {
+ element: 8,
+ items: vec![Value::Object {
+ kind: 3,
+ target: Ref::new(reactor, 3),
+ }],
+ },
+ ),
+ ("Status".into(), Value::Integer(0)),
+ ("expr.const".into(), constants(overrides)),
+ ("expr.orig".into(), constants(Vec::new())),
+ (
+ "modifiedParams".into(),
+ Value::List {
+ element: 2,
+ items: Vec::new(),
+ },
+ ),
+ ])),
+ ),
+ Record::like(
+ &reactor_template,
+ reactor,
+ Ref::new(feature, 4),
+ Body::Properties(Properties(vec![
+ ("_ver".into(), Value::Byte(1)),
+ ("mask".into(), Value::Integer(1)),
+ (
+ "pers_ids".into(),
+ Value::List {
+ element: 8,
+ items: vec![Value::Object {
+ kind: 0,
+ target: Ref::new(dependency, 4),
+ }],
+ },
+ ),
+ ("tag".into(), Value::Integer(0)),
+ ])),
+ ),
+ {
+ let mut record = Record::like(
+ &dependency_template,
+ dependency,
+ Ref::new(dependency_manager, 4),
+ Body::Dependency {
+ properties: Properties::default(),
+ tail: 0,
+ entity: Ref::new(insert, 5),
+ },
+ );
+ record.reactors = vec![Ref::new(reactor, 4)];
+ record
+ },
+ Record::like(
+ &object_template,
+ object,
+ Ref::new(constraint_manager, 4),
+ Body::Object {
+ lead: object_lead.0,
+ lead_count: object_lead.1,
+ entity: Ref::new(insert, 4),
+ properties: Properties(vec![
+ (
+ "NAME".into(),
+ Value::Text(format!("Objekt_{object_number}")),
+ ),
+ (
+ "PersIdDependencies".into(),
+ Value::List {
+ element: 8,
+ items: vec![Value::Object {
+ kind: 0,
+ target: Ref::new(dependency, 4),
+ }],
+ },
+ ),
+ ]),
+ tail: object_lead.2,
+ },
+ ),
+ ];
+ let classes = [
+ "BDMDBFEATUREDATA",
+ "BDMDBPERSIDREACTOR",
+ "BDMDBOBJECTDEPENDENCY",
+ "BDMOBJECT",
+ ];
+ for (class, record) in classes.iter().zip(&new_records) {
+ document
+ .objects
+ .insert(record.handle, unknown(class, record));
+ }
+
+ append_object(document, feature_manager, "Features", feature)?;
+ append_object(document, dependency_manager, "deps", dependency)?;
+ let Body::ConstraintManager {
+ counts, children, ..
+ } = &mut constraint_record.body
+ else {
+ return Err(UNSUPPORTED);
+ };
+ let at = usize::try_from(counts[1]).map_err(|_| UNSUPPORTED)?;
+ children.insert(at.min(children.len()), Ref::new(object, 3));
+ counts[1] += 1;
+ store(document, &constraint_record);
+ if let Some(entity) = document.get_entity_mut(insert) {
+ entity.common_mut().reactors.push(object);
+ }
+ Ok(())
+}
+
+/// Append a reference to `target` to the list property `list` of `manager`.
+fn append_object(
+ document: &mut Document,
+ manager: Handle,
+ list: &str,
+ target: Handle,
+) -> Result<()> {
+ let mut record = read_record(document, manager).ok_or(UNSUPPORTED)?;
+ let Some(Value::List { items, .. }) = record.body.properties_mut().get_mut(list) else {
+ return Err(UNSUPPORTED);
+ };
+ items.push(Value::Object {
+ kind: 3,
+ target: Ref::new(target, 3),
+ });
+ store(document, &record);
+ Ok(())
+}
+
+/// Model space's feature manager, dependency manager and constraint manager,
+/// created after those of `master` when model space has none yet.
+fn model_database(document: &mut Document, master: Handle) -> Result<(Handle, Handle, Handle)> {
+ let model = document.header.model_space_block_handle;
+ let entries = |document: &Document, owner: Handle| {
+ Some((
+ database_entry(document, owner, "FEATURE_MANAGER")?,
+ database_entry(document, owner, "PERSIDMANAGER")?,
+ database_entry(document, owner, "BDM_DATABASE")?,
+ ))
+ };
+ if let Some(found) = entries(document, model) {
+ return Ok(found);
+ }
+ let model_dictionary = document.ensure_extension_dictionary(model);
+ let has_database = matches!(
+ document.objects.get(&model_dictionary),
+ Some(ObjectType::Dictionary(dictionary)) if dictionary.get("BDM_DATABASE").is_some()
+ );
+ if has_database {
+ // A database without all three managers is not one this writes into.
+ return Err(UNSUPPORTED);
+ }
+ let master_dictionary = document
+ .extension_dictionary_handle(master)
+ .ok_or(UNSUPPORTED)?;
+ let (master_database, hard_owned) = match document.objects.get(&master_dictionary) {
+ Some(ObjectType::Dictionary(dictionary)) => (
+ dictionary.get("BDM_DATABASE").ok_or(UNSUPPORTED)?,
+ dictionary
+ .hard_owner_entries
+ .iter()
+ .any(|key| key.eq_ignore_ascii_case("BDM_DATABASE")),
+ ),
+ _ => return Err(UNSUPPORTED),
+ };
+ let Some(ObjectType::Dictionary(template)) = document.objects.get(&master_database).cloned()
+ else {
+ return Err(UNSUPPORTED);
+ };
+ let (feature_template, dependency_template, constraint_template) =
+ entries(document, master).ok_or(UNSUPPORTED)?;
+ let database = document.allocate_handle();
+ let mut created = Vec::new();
+ let mut handles = FxHashMap::default();
+ for (key, template_handle) in [
+ ("FEATURE_MANAGER", feature_template),
+ ("PERSIDMANAGER", dependency_template),
+ ("BDM_DATABASE", constraint_template),
+ ] {
+ let mut record = read_record(document, template_handle).ok_or(UNSUPPORTED)?;
+ let handle = document.allocate_handle();
+ record.handle = handle;
+ record.owner.handle = database;
+ for reactor in &mut record.reactors {
+ reactor.handle = database;
+ }
+ match &mut record.body {
+ Body::Properties(properties) => {
+ properties
+ .0
+ .retain(|(name, _)| !name.starts_with("original."));
+ for list in ["Features", "Contexts", "deps"] {
+ if let Some(Value::List { items, .. }) = properties.get_mut(list) {
+ items.clear();
+ }
+ }
+ }
+ Body::ConstraintManager {
+ counts, children, ..
+ } => {
+ counts[1] = 0;
+ counts[3] = 0;
+ children.clear();
+ }
+ _ => return Err(UNSUPPORTED),
+ }
+ let class = match key {
+ "FEATURE_MANAGER" => "BDMDBFEATUREMANAGER",
+ "PERSIDMANAGER" => "BdmDbPersIdManager",
+ _ => "BDMDBCONSTRAINTMANAGER",
+ };
+ created.push((handle, unknown(class, &record)));
+ handles.insert(key, handle);
+ }
+ let mut dictionary = template;
+ dictionary.handle = database;
+ dictionary.owner = model_dictionary;
+ dictionary.reactors = vec![model_dictionary];
+ dictionary.xdictionary_handle = None;
+ for (key, entry) in &mut dictionary.entries {
+ *entry = *handles.get(key.as_str()).ok_or(UNSUPPORTED)?;
+ }
+ document
+ .objects
+ .insert(database, ObjectType::Dictionary(dictionary));
+ for (handle, object) in created {
+ document.objects.insert(handle, object);
+ }
+ if let Some(ObjectType::Dictionary(dictionary)) = document.objects.get_mut(&model_dictionary) {
+ dictionary.add_entry("BDM_DATABASE", database);
+ if hard_owned {
+ dictionary.hard_owner_entries.push("BDM_DATABASE".into());
+ }
+ }
+ entries(document, model).ok_or(UNSUPPORTED)
+}
+
+/// A record of `class` to make new ones like: one under `master`'s extension
+/// dictionary, or any in the drawing.
+fn template_record(document: &Document, master: Handle, class: &str) -> Option {
+ let tree: FxHashSet = document
+ .extension_dictionary_handle(master)
+ .and_then(|root| owned_tree(document, root).ok())
+ .map(|tree| tree.into_iter().collect())
+ .unwrap_or_default();
+ let mut candidates: Vec = document
+ .objects
+ .iter()
+ .filter_map(|(handle, object)| match object {
+ ObjectType::Unknown { type_name, .. } if type_name == class => Some(*handle),
+ _ => None,
+ })
+ .collect();
+ candidates.sort_by_key(|handle| (!tree.contains(handle), *handle));
+ candidates
+ .into_iter()
+ .find_map(|handle| read_record(document, handle))
+}
+
+/// The tag BricsCAD gives a parametric block, kept in its extended data and
+/// named by every copy (`original.tag`).
+fn block_tag(document: &Document, block: Handle) -> Option {
+ const NAME: &[u8] = b"ParametricBlockGUID";
+ document
+ .object_xdata(block)?
+ .records()
+ .iter()
+ .filter(|record| record.application_name == "BDM_DB")
+ .flat_map(|record| &record.values)
+ .find_map(|value| {
+ let document::xdata::XDataValue::BinaryData(bytes) = value else {
+ return None;
+ };
+ let at = bytes
+ .windows(NAME.len())
+ .position(|window| window == NAME)?
+ + NAME.len();
+ // A type byte (2: text), the length and the characters.
+ if *bytes.get(at)? != 2 {
+ return None;
+ }
+ let length = usize::from(u16::from_le_bytes([
+ *bytes.get(at + 1)?,
+ *bytes.get(at + 2)?,
+ ]));
+ let text = bytes.get(at + 3..at + 3 + length)?;
+ String::from_utf8(text.to_vec()).ok()
+ })
+}
+
+/// Give `block` a new tag the way BricsCAD stores it, and return it.
+fn give_block_tag(document: &mut Document, block: Handle) -> String {
+ const NAME: &[u8] = b"ParametricBlockGUID";
+ let tag = crate::scene::block_authoring::new_guid().to_lowercase();
+ let mut bytes = vec![1, 0, 0, 0];
+ bytes.extend((NAME.len() as u16).to_le_bytes());
+ bytes.extend(NAME);
+ bytes.push(2);
+ bytes.extend((tag.len() as u16).to_le_bytes());
+ bytes.extend(tag.as_bytes());
+ crate::scene::block_authoring::ensure_app_id(document, "BDM_DB");
+ let mut record = document::xdata::ExtendedDataRecord::new("BDM_DB");
+ record.add_value(document::xdata::XDataValue::BinaryData(bytes));
+ document.set_object_xdata_record(block, record);
+ tag
+}
+
+/// The handle as BricsCAD stores it in a raw value: its bytes, most
+/// significant first, without leading zeros.
+fn handle_bytes(handle: Handle) -> Vec {
+ handle
+ .value()
+ .to_be_bytes()
+ .into_iter()
+ .skip_while(|byte| *byte == 0)
+ .collect()
+}
+
+/// The next free name of the form `*U`.
+fn next_anonymous_name(document: &Document) -> String {
+ let next = document
+ .block_records
+ .iter()
+ .filter_map(|record| record.name.strip_prefix("*U")?.parse::().ok())
+ .max()
+ .map_or(1, |n| n + 1);
+ format!("*U{next}")
+}
+
+/// The raw object for `record`.
+pub(super) fn unknown(class: &str, record: &Record) -> ObjectType {
+ let (data, handle_bits) = record::encode(record);
+ ObjectType::Unknown {
+ type_name: class.to_string(),
+ handle: record.handle,
+ owner: record.owner.handle,
+ raw_dxf_codes: None,
+ raw_dwg_data: Some(data),
+ raw_dwg_handle_bits: handle_bits,
+ raw_dwg_version: Some(record.version),
+ }
+}
+
+/// Store a changed record over the object it was read from.
+pub(super) fn store(document: &mut Document, record: &Record) {
+ let class = match document.objects.get(&record.handle) {
+ Some(ObjectType::Unknown { type_name, .. }) => type_name.clone(),
+ _ => return,
+ };
+ document
+ .objects
+ .insert(record.handle, unknown(&class, record));
+}
diff --git a/src/scene/bricscad_parameters/switch_tests.rs b/src/scene/bricscad_parameters/switch_tests.rs
new file mode 100644
index 0000000000..660ea5796d
--- /dev/null
+++ b/src/scene/bricscad_parameters/switch_tests.rs
@@ -0,0 +1,507 @@
+//! Switching on the BricsCAD drawing in `tests/fixtures/bricscad` (see its
+//! README): EE shows the block in On/Shown, 146 the copy *U2 in Off/Shown and
+//! 19E the copy *U3 in Off/Hidden; 146 and 19E have entries in model space.
+
+use super::record::{Body, Value};
+use super::*;
+use crate::scene::Scene;
+use std::collections::{BTreeMap, BTreeSet};
+
+const MASTER: &str = "ocs-bricscad-visibility-block";
+
+fn opened() -> Scene {
+ let path = concat!(
+ env!("CARGO_MANIFEST_DIR"),
+ "/tests/fixtures/bricscad/visibility-states.dwg"
+ );
+ let bytes = std::fs::read(path).expect("read the fixture");
+ let mut scene = Scene::new();
+ scene.document =
+ crate::io::load_bytes_finalized(std::path::Path::new("visibility-states.dwg"), bytes)
+ .expect("open the fixture");
+ scene.load_named_parameters_from_document();
+ scene.load_parametric_constraints_from_document();
+ scene
+}
+
+fn reference(value: u64) -> Handle {
+ Handle::from(value)
+}
+
+fn block_of(document: &Document, insert: u64) -> String {
+ match document.get_entity(reference(insert)) {
+ Some(EntityType::Insert(insert)) => insert.block_name.clone(),
+ other => panic!("{other:?}"),
+ }
+}
+
+/// Each parameter and the state the reference shows.
+fn shown(document: &Document, insert: u64) -> Vec<(String, String)> {
+ reference_parameters(document, reference(insert))
+ .into_iter()
+ .map(|parameter| {
+ let state = parameter.states[parameter.current.unwrap()].clone();
+ (parameter.name, state)
+ })
+ .collect()
+}
+
+fn pairs(list: &[(&str, &str)]) -> Vec<(String, String)> {
+ list.iter()
+ .map(|(a, b)| (a.to_string(), b.to_string()))
+ .collect()
+}
+
+/// The parameters the reference's entry in model space lists.
+fn entry(document: &Document, insert: u64) -> Option> {
+ let (_, record) = super::switch::find_entry(document, reference(insert))?;
+ Some(
+ record
+ .body
+ .properties()
+ .get("expr.const")?
+ .entries()?
+ .iter()
+ .map(|(key, value)| {
+ (
+ key.text().unwrap().to_string(),
+ value.text().unwrap().to_string(),
+ )
+ })
+ .collect(),
+ )
+}
+
+/// The references in the BricsCAD objects of `document` that name an object
+/// the drawing does not have, as (holder, target).
+fn dangling_references(document: &Document) -> BTreeSet<(Handle, Handle)> {
+ let mut dangling = BTreeSet::new();
+ for (handle, object) in &document.objects {
+ if !matches!(object, ObjectType::Unknown { type_name, .. } if type_name.to_ascii_uppercase().starts_with("BDM"))
+ {
+ continue;
+ }
+ let mut record = record(document, *handle).expect("a BricsCAD object decodes");
+ record.refs_mut(|reference| {
+ let target = reference.handle;
+ let known = target.is_null()
+ || document.objects.contains_key(&target)
+ || document.get_entity(target).is_some()
+ || document.block_records.iter().any(|r| r.handle == target)
+ || document.layers.iter().any(|layer| layer.handle == target);
+ if !known {
+ dangling.insert((*handle, target));
+ }
+ });
+ }
+ dangling
+}
+
+/// No reference in the BricsCAD objects names an object the drawing lacks,
+/// apart from those BricsCAD itself left in the fixture: its global constraint
+/// manager still lists child managers it purged.
+fn assert_no_dangling_references(document: &Document) {
+ let left_by_bricscad = dangling_references(&opened().document);
+ let dangling = dangling_references(document);
+ let new: Vec<_> = dangling.difference(&left_by_bricscad).collect();
+ assert!(
+ new.is_empty(),
+ "references to objects the drawing lacks: {new:?}"
+ );
+}
+
+#[test]
+fn a_state_another_copy_shows_shares_that_copy_and_gives_the_reference_an_entry() {
+ let mut scene = opened();
+ assert_eq!(entry(&scene.document, 0xEE), None);
+ assert!(scene
+ .set_bricscad_visibility(reference(0xEE), "LAMP", "Off")
+ .unwrap());
+ let document = &scene.document;
+ assert_eq!(
+ block_of(document, 0xEE),
+ "*U2",
+ "BricsCAD shares copies too"
+ );
+ assert_eq!(
+ shown(document, 0xEE),
+ pairs(&[("LAMP", "Off"), ("LABEL", "Shown")])
+ );
+ assert_eq!(entry(document, 0xEE), Some(pairs(&[("LAMP", "Off")])));
+ assert_eq!(
+ shown(document, 0x146),
+ pairs(&[("LAMP", "Off"), ("LABEL", "Shown")])
+ );
+ assert_no_dangling_references(document);
+}
+
+#[test]
+fn the_block_s_own_states_show_the_block_and_the_entry_keeps_the_parameter() {
+ let mut scene = opened();
+ assert!(scene
+ .set_bricscad_visibility(reference(0x146), "LAMP", "On")
+ .unwrap());
+ let document = &scene.document;
+ assert_eq!(block_of(document, 0x146), MASTER);
+ assert_eq!(
+ shown(document, 0x146),
+ pairs(&[("LAMP", "On"), ("LABEL", "Shown")])
+ );
+ // BricsCAD keeps a parameter in the entry once set, also in the block's
+ // own state.
+ assert_eq!(entry(document, 0x146), Some(pairs(&[("LAMP", "On")])));
+}
+
+#[test]
+fn a_state_no_block_shows_gets_a_new_copy() {
+ let mut scene = opened();
+ let records = scene.document.block_records.iter().count();
+ assert!(scene
+ .set_bricscad_visibility(reference(0xEE), "LABEL", "Hidden")
+ .unwrap());
+ let document = &scene.document;
+ assert_eq!(document.block_records.iter().count(), records + 1);
+ let copy = block_of(document, 0xEE);
+ assert_eq!(copy, "*U4");
+ let copy = document.block_records.get(©).unwrap().handle;
+ let master = document.block_records.get(MASTER).unwrap().handle;
+ assert_eq!(original_block(document, copy), Some(master));
+ assert_eq!(
+ shown(document, 0xEE),
+ pairs(&[("LAMP", "On"), ("LABEL", "Hidden")])
+ );
+ assert_eq!(entry(document, 0xEE), Some(pairs(&[("LABEL", "Hidden")])));
+ let layers: Vec = crate::scene::block_authoring::members(document, copy)
+ .into_iter()
+ .map(|member| document.get_entity(member).unwrap().common().layer.clone())
+ .collect();
+ assert_eq!(
+ layers,
+ ["0", "0", "0", "0", "*SUPPRESS"],
+ "only the text is hidden"
+ );
+ // The block and the other references are left alone.
+ assert_eq!(
+ shown(document, 0x146),
+ pairs(&[("LAMP", "Off"), ("LABEL", "Shown")])
+ );
+ assert_eq!(
+ visibility_parameters(document, master)
+ .iter()
+ .map(|p| p.current)
+ .collect::>(),
+ [Some(0), Some(0)]
+ );
+ assert_no_dangling_references(document);
+}
+
+/// A property value with references written as the kind, code and class of
+/// what they name, and members as their place in the block.
+fn normalized(document: &Document, members: &[Handle], value: &Value) -> String {
+ match value {
+ Value::Object { kind, target } => {
+ let what = members
+ .iter()
+ .position(|member| *member == target.handle)
+ .map(|index| format!("member {index}"))
+ .or_else(|| {
+ document
+ .objects
+ .get(&target.handle)
+ .map(|object| match object {
+ ObjectType::Unknown { type_name, .. } => type_name.clone(),
+ ObjectType::Associative(object) => object.dxf_name.clone(),
+ other => format!("{:?}", std::mem::discriminant(other)),
+ })
+ })
+ .or_else(|| {
+ document
+ .layers
+ .iter()
+ .find(|layer| layer.handle == target.handle)
+ .map(|layer| format!("layer {}", layer.name))
+ })
+ .or_else(|| {
+ document
+ .block_records
+ .iter()
+ .find(|record| record.handle == target.handle)
+ .map(|record| format!("block {}", record.name))
+ })
+ .unwrap_or_else(|| format!("{:?}", target.handle));
+ format!("ref({kind},{},{what})", target.code)
+ }
+ Value::List { element, items } => format!(
+ "list {element} [{}]",
+ items
+ .iter()
+ .map(|item| normalized(document, members, item))
+ .collect::>()
+ .join(", ")
+ ),
+ Value::Map {
+ key,
+ value,
+ entries,
+ } => format!(
+ "map {key} {value} [{}]",
+ entries
+ .iter()
+ .map(|(k, v)| format!(
+ "{} => {}",
+ normalized(document, members, k),
+ normalized(document, members, v)
+ ))
+ .collect::>()
+ .join(", ")
+ ),
+ Value::Raw(bytes) => {
+ // A raw handle of a member of the block the copy was made from.
+ let handle = Handle::from(bytes.iter().fold(0u64, |v, b| v << 8 | u64::from(*b)));
+ let master = document.block_records.get(MASTER).unwrap().handle;
+ let index = crate::scene::block_authoring::members(document, master)
+ .iter()
+ .position(|member| *member == handle);
+ format!("raw member {index:?}")
+ }
+ other => format!("{other:?}"),
+ }
+}
+
+/// Every BricsCAD object under `block`'s extension dictionary, in the order of
+/// a walk through its feature and other managers, each as its class and
+/// normalized properties.
+fn parameter_objects(document: &Document, block: Handle) -> Vec {
+ let members = crate::scene::block_authoring::members(document, block);
+ let mut out = Vec::new();
+ let mut seen = std::collections::HashSet::new();
+ let mut stack: Vec = ["BDM_DATABASE", "FEATURE_MANAGER", "PERSIDMANAGER"]
+ .iter()
+ .filter_map(|key| database_entry(document, block, key))
+ .collect();
+ stack.reverse();
+ while let Some(handle) = stack.pop() {
+ if !seen.insert(handle) {
+ continue;
+ }
+ let Some(record) = record(document, handle) else {
+ continue;
+ };
+ let class = match document.objects.get(&handle) {
+ Some(ObjectType::Unknown { type_name, .. }) => type_name.clone(),
+ _ => continue,
+ };
+ let mut children = Vec::new();
+ let properties = match &record.body {
+ Body::Properties(properties) => properties.clone(),
+ Body::ConstraintManager {
+ counts,
+ children: owned,
+ settings,
+ } => {
+ children.extend(owned.iter().map(|r| r.handle));
+ out.push(format!("{class} counts {counts:?}"));
+ settings.clone()
+ }
+ Body::Object {
+ entity, properties, ..
+ } => {
+ out.push(format!(
+ "{class} entity {}",
+ normalized(
+ document,
+ &members,
+ &Value::Object {
+ kind: 0,
+ target: *entity
+ }
+ )
+ ));
+ properties.clone()
+ }
+ Body::Dependency {
+ entity, properties, ..
+ } => {
+ out.push(format!(
+ "{class} entity {}",
+ normalized(
+ document,
+ &members,
+ &Value::Object {
+ kind: 0,
+ target: *entity
+ }
+ )
+ ));
+ properties.clone()
+ }
+ };
+ for (name, value) in &properties.0 {
+ out.push(format!(
+ "{class}.{name} = {}",
+ normalized(document, &members, value)
+ ));
+ let mut value = value.clone();
+ let mut collect = |value: &Value| {
+ if let Value::Object { target, .. } = value {
+ children.push(target.handle);
+ }
+ };
+ walk(&mut value, &mut collect);
+ }
+ stack.extend(children.into_iter().rev());
+ }
+ out
+}
+
+fn walk(value: &mut Value, visit: &mut impl FnMut(&Value)) {
+ visit(value);
+ match value {
+ Value::List { items, .. } => items.iter_mut().for_each(|item| walk(item, visit)),
+ Value::Map { entries, .. } => entries.iter_mut().for_each(|(k, v)| {
+ walk(k, visit);
+ walk(v, visit);
+ }),
+ _ => {}
+ }
+}
+
+#[test]
+fn a_new_copy_holds_what_bricscad_s_own_copy_in_the_same_states_holds() {
+ let mut scene = opened();
+ let master = scene.document.block_records.get(MASTER).unwrap().handle;
+ let bricscad = scene.document.block_records.get("*U3").unwrap().handle;
+ let states: BTreeMap = [("LAMP", "Off"), ("LABEL", "Hidden")]
+ .iter()
+ .map(|(k, v)| (k.to_string(), v.to_string()))
+ .collect();
+ let listed: BTreeSet = ["LAMP", "LABEL"].iter().map(|s| s.to_string()).collect();
+ let copy = scene
+ .clone_parametric_copy(master, &states, &listed)
+ .unwrap();
+ let ours = parameter_objects(&scene.document, copy);
+ let theirs = parameter_objects(&scene.document, bricscad);
+ assert!(ours.len() > 40, "{ours:#?}");
+ // The key variables' numbers follow no rule BricsCAD keeps: the same
+ // state carries 0 in one of its copies and 1 in another.
+ let differences: Vec<(&String, &String)> = ours
+ .iter()
+ .zip(&theirs)
+ .filter(|(a, b)| a != b)
+ .filter(|(a, _)| !a.starts_with("BDMDBCONFIGVARREACTOR.Value"))
+ .collect();
+ assert_eq!(ours.len(), theirs.len(), "{ours:#?}\n{theirs:#?}");
+ assert!(differences.is_empty(), "{differences:#?}");
+ // Member layers too.
+ let layers = |block: Handle| -> Vec {
+ crate::scene::block_authoring::members(&scene.document, block)
+ .into_iter()
+ .map(|m| scene.document.get_entity(m).unwrap().common().layer.clone())
+ .collect()
+ };
+ assert_eq!(layers(copy), layers(bricscad));
+}
+
+#[test]
+fn the_switched_drawing_keeps_its_parameters_through_a_dwg_save() {
+ let mut scene = opened();
+ scene
+ .set_bricscad_visibility(reference(0xEE), "LABEL", "Hidden")
+ .unwrap();
+ scene
+ .set_bricscad_visibility(reference(0x19E), "LAMP", "On")
+ .unwrap();
+ scene.sync_native_parametric_graph();
+ let saved = crate::io::save_to_bytes(&scene.document, "dwg", scene.document.version)
+ .expect("save as DWG");
+ let reopened = crate::io::load_bytes_finalized(std::path::Path::new("saved.dwg"), saved)
+ .expect("open the saved DWG");
+ assert_eq!(
+ shown(&reopened, 0xEE),
+ pairs(&[("LAMP", "On"), ("LABEL", "Hidden")])
+ );
+ assert_eq!(
+ shown(&reopened, 0x146),
+ pairs(&[("LAMP", "Off"), ("LABEL", "Shown")])
+ );
+ assert_eq!(
+ shown(&reopened, 0x19E),
+ pairs(&[("LAMP", "On"), ("LABEL", "Hidden")])
+ );
+ assert_eq!(
+ block_of(&reopened, 0x19E),
+ block_of(&reopened, 0xEE),
+ "shared"
+ );
+ assert_eq!(
+ entry(&reopened, 0x19E),
+ Some(pairs(&[("LABEL", "Hidden"), ("LAMP", "On")]))
+ );
+ assert_no_dangling_references(&reopened);
+}
+
+#[test]
+fn an_unknown_parameter_or_state_is_refused_and_a_shown_state_changes_nothing() {
+ let mut scene = opened();
+ let before = scene.document.clone();
+ assert!(scene
+ .set_bricscad_visibility(reference(0xEE), "NOPE", "On")
+ .is_err());
+ assert!(scene
+ .set_bricscad_visibility(reference(0xEE), "LAMP", "Dim")
+ .is_err());
+ assert_eq!(
+ scene.set_bricscad_visibility(reference(0xEE), "LAMP", "On"),
+ Ok(false)
+ );
+ assert!(scene.document == before);
+}
+
+/// BricsCAD keeps each read of a variable at the variable's value, and takes a
+/// variable whose reads already hold its new value for unchanged: a stale
+/// read would keep it from evaluating what depends on the variable.
+#[test]
+fn each_read_of_a_variable_holds_the_variable_s_value_after_a_switch() {
+ use document::objects::{AssociativeData, AssociativeObject};
+ let mut scene = opened();
+ assert!(scene
+ .set_bricscad_visibility(reference(0xEE), "LABEL", "Hidden")
+ .unwrap());
+ let document = &scene.document;
+ let copy = document
+ .block_records
+ .get(&block_of(document, 0xEE))
+ .unwrap()
+ .handle;
+ // The copy's network sits in its extension dictionary, behind a
+ // dictionary of the same name.
+ let entry = |dictionary: Handle| match document.objects.get(&dictionary) {
+ Some(ObjectType::Dictionary(dictionary)) => dictionary.get("ACAD_ASSOCNETWORK"),
+ _ => None,
+ };
+ let mut network = entry(document.extension_dictionary_handle(copy).unwrap()).unwrap();
+ while let Some(inner) = entry(network) {
+ network = inner;
+ }
+ let mut reads = 0;
+ for object in document.objects.values() {
+ let ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::ValueDependency(read),
+ ..
+ }) = object
+ else {
+ continue;
+ };
+ let Some(ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::Variable(variable),
+ owner,
+ ..
+ })) = document.objects.get(&read.dependency.dependent_on)
+ else {
+ panic!("a read of something other than a variable");
+ };
+ assert_eq!(read.value, variable.value, "{}", variable.name);
+ reads += usize::from(*owner == network);
+ }
+ assert!(reads > 0, "the copy's variables are read");
+}
diff --git a/src/scene/bricscad_parameters/tests.rs b/src/scene/bricscad_parameters/tests.rs
new file mode 100644
index 0000000000..d876386121
--- /dev/null
+++ b/src/scene/bricscad_parameters/tests.rs
@@ -0,0 +1,141 @@
+use super::*;
+use document::DxfVersion;
+
+/// The BricsCAD drawing in `tests/fixtures/bricscad` (see its README).
+fn fixture() -> Document {
+ let path = concat!(
+ env!("CARGO_MANIFEST_DIR"),
+ "/tests/fixtures/bricscad/visibility-states.dwg"
+ );
+ let bytes = std::fs::read(path).expect("read the fixture");
+ crate::io::load_bytes_finalized(std::path::Path::new("visibility-states.dwg"), bytes)
+ .expect("open the fixture")
+}
+
+fn block(document: &Document, name: &str) -> Handle {
+ document.block_records.get(name).unwrap().handle
+}
+
+/// The block reference with handle `value`.
+fn reference(value: u64) -> Handle {
+ Handle::from(value)
+}
+
+/// Each parameter as its name and the state it shows.
+fn shown(parameters: &[VisibilityParameter]) -> Vec<(&str, &str)> {
+ parameters
+ .iter()
+ .map(|parameter| {
+ (
+ parameter.name.as_str(),
+ parameter
+ .current
+ .map_or("?", |index| parameter.states[index].as_str()),
+ )
+ })
+ .collect()
+}
+
+#[test]
+fn the_definition_names_its_parameters_their_states_and_the_ones_it_shows() {
+ let document = fixture();
+ let parameters =
+ visibility_parameters(&document, block(&document, "ocs-bricscad-visibility-block"));
+ assert_eq!(
+ parameters,
+ vec![
+ VisibilityParameter {
+ name: "LAMP".into(),
+ states: vec!["On".into(), "Off".into()],
+ current: Some(0),
+ feature: Handle::from(0x16Fu64),
+ },
+ VisibilityParameter {
+ name: "LABEL".into(),
+ states: vec!["Shown".into(), "Hidden".into()],
+ current: Some(0),
+ feature: Handle::from(0x176u64),
+ },
+ ]
+ );
+}
+
+#[test]
+fn each_reference_shows_the_states_it_was_set_to() {
+ let document = fixture();
+ assert_eq!(
+ shown(&reference_parameters(&document, reference(0xEE))),
+ [("LAMP", "On"), ("LABEL", "Shown")]
+ );
+ assert_eq!(
+ shown(&reference_parameters(&document, reference(0x146))),
+ [("LAMP", "Off"), ("LABEL", "Shown")]
+ );
+ assert_eq!(
+ shown(&reference_parameters(&document, reference(0x19E))),
+ [("LAMP", "Off"), ("LABEL", "Hidden")]
+ );
+}
+
+#[test]
+fn a_copy_names_the_block_it_was_made_from() {
+ let document = fixture();
+ let definition = block(&document, "ocs-bricscad-visibility-block");
+ for copy in ["*U2", "*U3"] {
+ assert_eq!(
+ original_block(&document, block(&document, copy)),
+ Some(definition),
+ "{copy}"
+ );
+ }
+ assert_eq!(original_block(&document, definition), None);
+}
+
+#[test]
+fn other_blocks_and_references_have_no_parameters() {
+ let document = fixture();
+ let model = document.header.model_space_block_handle;
+ assert!(visibility_parameters(&document, model).is_empty());
+ assert_eq!(original_block(&document, model), None);
+ let line = document
+ .entities()
+ .find(|entity| matches!(entity, EntityType::Line(_)))
+ .unwrap()
+ .common()
+ .handle;
+ assert!(reference_parameters(&document, line).is_empty());
+}
+
+#[test]
+fn a_cut_record_decodes_to_nothing_rather_than_a_wrong_answer() {
+ let document = fixture();
+ let mut records = 0;
+ for object in document.objects.values() {
+ let ObjectType::Unknown {
+ type_name,
+ raw_dwg_data: Some(data),
+ raw_dwg_handle_bits,
+ raw_dwg_version: Some(version),
+ ..
+ } = object
+ else {
+ continue;
+ };
+ if type_name != "BDMDBCONFIGURATIONTABLE" {
+ continue;
+ }
+ let whole = record::decode(type_name, data, *raw_dwg_handle_bits, *version)
+ .expect("the whole record");
+ assert!(whole.body.properties().get("KeyValues").is_some());
+ records += 1;
+ for length in 0..data.len() {
+ // Shorter by whole bytes: the streams no longer line up.
+ let _ = record::decode(type_name, &data[..length], *raw_dwg_handle_bits, *version);
+ }
+ assert_eq!(
+ record::decode(type_name, data, *raw_dwg_handle_bits, DxfVersion::AC1021),
+ None
+ );
+ }
+ assert_eq!(records, 6, "two tables in each of the three blocks");
+}
diff --git a/src/scene/dwg_native_constraints.rs b/src/scene/dwg_native_constraints.rs
index 02365a1a42..010a74a961 100644
--- a/src/scene/dwg_native_constraints.rs
+++ b/src/scene/dwg_native_constraints.rs
@@ -1466,7 +1466,7 @@ const ASSOC_CLASSES: &[(&str, &str, i32)] = &[
),
];
-fn ensure_associative_classes_registered(document: &mut Document) {
+pub(super) fn ensure_associative_classes_registered(document: &mut Document) {
for (dxf_name, cpp_class_name, maintenance_version) in ASSOC_CLASSES {
if document.classes.get_by_name(dxf_name).is_some() {
continue;
@@ -4194,38 +4194,7 @@ impl Scene {
}
pub(crate) fn load_named_parameters_from_document(&mut self) {
- self.named_parameters = ParameterTable::new();
- let mut variables: Vec<_> = self
- .document
- .objects
- .values()
- .filter_map(|object| match object {
- ObjectType::Associative(AssociativeObject {
- handle,
- data: AssociativeData::Variable(variable),
- ..
- }) => Some((*handle, variable)),
- _ => None,
- })
- .collect();
- variables.sort_by_key(|(handle, _)| handle.value());
- let model_network = native_scope_network_handle(
- &self.document,
- self.document.header.model_space_block_handle,
- );
- for (_, variable) in variables {
- if model_network.is_none_or(|network| variable.action.owning_network != network) {
- continue;
- }
- let source = if variable.expression.trim().is_empty() {
- numeric_value(&variable.value).map(|value| value.to_string())
- } else {
- Some(variable.expression.clone())
- };
- if let Some(source) = source {
- let _ = self.named_parameters.set(&variable.name, &source);
- }
- }
+ self.named_parameters = model_network_parameters(&self.document);
}
pub(crate) fn load_parametric_constraints_from_document(&mut self) {
@@ -4300,6 +4269,8 @@ impl Scene {
.map(|&owner| native_scope_network_handle(&self.document, owner).is_some())
.collect()
};
+ let raw_dependents = networks_raw_objects_depend_on(&self.document);
+ let mut kept_networks = Vec::new();
let mut scopes = Vec::new();
for (owner, existing) in owners.into_iter().zip(existing_networks) {
let runtime = self
@@ -4307,6 +4278,18 @@ impl Scene {
.iter()
.find(|set| set.scope.owner_handle(&self.document) == owner)
.cloned();
+ if existing {
+ if let Some(network) = stored_network_to_keep(
+ &self.document,
+ owner,
+ runtime.as_ref(),
+ &self.named_parameters,
+ &raw_dependents,
+ ) {
+ kept_networks.push(network);
+ continue;
+ }
+ }
let set = match runtime {
Some(set) => Some(set),
None if existing => {
@@ -4355,6 +4338,7 @@ impl Scene {
);
let root_network_handle = self.document.allocate_handle();
let mut child_networks = Vec::new();
+ let rebuilt_scopes = scopes.len();
for (index, (owner, set, variables, groups, foreign)) in scopes.into_iter().enumerate() {
let parameters = if set.local_parameters.is_empty() {
&self.named_parameters
@@ -4376,6 +4360,19 @@ impl Scene {
child_networks.push(handle);
}
}
+ // The kept networks go under the new root after the rebuilt ones,
+ // unchanged apart from where they sit in it.
+ for (offset, network) in kept_networks.into_iter().enumerate() {
+ if let Some(ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::Network(kept),
+ ..
+ })) = self.document.objects.get_mut(&network)
+ {
+ kept.action.owning_network = root_network_handle;
+ kept.action.action_index = (rebuilt_scopes + offset) as i32 + 1;
+ child_networks.push(network);
+ }
+ }
if child_networks.is_empty() {
return;
}
@@ -4431,63 +4428,189 @@ impl Scene {
let mut hasher = DefaultHasher::new();
hash_parameter_table(&self.named_parameters, &mut hasher);
for set in &self.parametric_constraints {
- set.scope.hash(&mut hasher);
- for constraint in &set.constraints {
- constraint.id.hash(&mut hasher);
- (constraint.kind as u16).hash(&mut hasher);
- constraint.refs.hash(&mut hasher);
- match &constraint.driving_param {
- None => 0u8.hash(&mut hasher),
- Some(DrivingValue::Literal(value)) => {
- 1u8.hash(&mut hasher);
- value.to_bits().hash(&mut hasher);
- }
- Some(DrivingValue::Named(name)) => {
- 2u8.hash(&mut hasher);
- name.hash(&mut hasher);
- }
- }
- constraint.enabled.hash(&mut hasher);
- match constraint.native_origin {
- None => 0u8.hash(&mut hasher),
- Some(origin) => {
- 1u8.hash(&mut hasher);
- origin.group.hash(&mut hasher);
- origin.node.hash(&mut hasher);
- }
- }
- constraint.rigid_points.len().hash(&mut hasher);
- for (reference, point) in &constraint.rigid_points {
- reference.hash(&mut hasher);
- hash_vector(point, &mut hasher);
- }
- constraint.distance_direction_type.hash(&mut hasher);
- match constraint.distance_direction {
- None => 0u8.hash(&mut hasher),
- Some(direction) => {
- 1u8.hash(&mut hasher);
- hash_vector(&direction, &mut hasher);
- }
- }
- match constraint.axis_direction {
- None => 0u8.hash(&mut hasher),
- Some(direction) => {
- 1u8.hash(&mut hasher);
- hash_vector(&direction, &mut hasher);
- }
- }
- constraint.angle_sector.hash(&mut hasher);
+ hash_constraint_set(set, &mut hasher);
+ }
+ hasher.finish()
+ }
+}
+
+/// Hashes one scope's share of the model `constraint_model_fingerprint`
+/// covers. Dimension links are hashed in id order, so two sets with the same
+/// links hash alike whatever order their maps hold them in.
+fn hash_constraint_set(set: &ParametricConstraintSet, hasher: &mut DefaultHasher) {
+ set.scope.hash(hasher);
+ for constraint in &set.constraints {
+ constraint.id.hash(hasher);
+ (constraint.kind as u16).hash(hasher);
+ constraint.refs.hash(hasher);
+ match &constraint.driving_param {
+ None => 0u8.hash(hasher),
+ Some(DrivingValue::Literal(value)) => {
+ 1u8.hash(hasher);
+ value.to_bits().hash(hasher);
}
- hash_parameter_table(&set.local_parameters, &mut hasher);
- set.dimensions.len().hash(&mut hasher);
- for (id, dimension) in &set.dimensions {
- id.hash(&mut hasher);
- dimension.hash(&mut hasher);
+ Some(DrivingValue::Named(name)) => {
+ 2u8.hash(hasher);
+ name.hash(hasher);
}
- set.retained_standard_groups.hash(&mut hasher);
}
- hasher.finish()
+ constraint.enabled.hash(hasher);
+ match constraint.native_origin {
+ None => 0u8.hash(hasher),
+ Some(origin) => {
+ 1u8.hash(hasher);
+ origin.group.hash(hasher);
+ origin.node.hash(hasher);
+ }
+ }
+ constraint.rigid_points.len().hash(hasher);
+ for (reference, point) in &constraint.rigid_points {
+ reference.hash(hasher);
+ hash_vector(point, hasher);
+ }
+ constraint.distance_direction_type.hash(hasher);
+ match constraint.distance_direction {
+ None => 0u8.hash(hasher),
+ Some(direction) => {
+ 1u8.hash(hasher);
+ hash_vector(&direction, hasher);
+ }
+ }
+ match constraint.axis_direction {
+ None => 0u8.hash(hasher),
+ Some(direction) => {
+ 1u8.hash(hasher);
+ hash_vector(&direction, hasher);
+ }
+ }
+ constraint.angle_sector.hash(hasher);
+ }
+ hash_parameter_table(&set.local_parameters, hasher);
+ let mut dimensions: Vec<_> = set.dimensions.iter().collect();
+ dimensions.sort_unstable_by_key(|(id, _)| **id);
+ dimensions.len().hash(hasher);
+ for (id, dimension) in dimensions {
+ id.hash(hasher);
+ dimension.hash(hasher);
+ }
+ set.retained_standard_groups.hash(hasher);
+}
+
+fn constraint_set_hash(set: &ParametricConstraintSet) -> u64 {
+ let mut hasher = DefaultHasher::new();
+ hash_constraint_set(set, &mut hasher);
+ hasher.finish()
+}
+
+/// The networks whose variables an object kept only as its raw record lists
+/// as a reactor. Such an object reaches the variables by handle and cannot be
+/// re-pointed, so rebuilding the network under new handles would leave it
+/// pointing at erased objects. BricsCAD keeps the visibility states and other
+/// parameters of its parametric blocks this way: its own objects, which this
+/// program reads as raw records, read and drive the block's variables.
+fn networks_raw_objects_depend_on(document: &Document) -> FxHashSet {
+ document
+ .objects
+ .values()
+ .filter_map(|object| match object {
+ ObjectType::Associative(AssociativeObject {
+ reactors,
+ data: AssociativeData::Variable(variable),
+ ..
+ }) if reactors.iter().any(|reactor| {
+ matches!(
+ document.objects.get(reactor),
+ Some(ObjectType::Unknown { .. })
+ )
+ }) =>
+ {
+ Some(variable.action.owning_network)
+ }
+ _ => None,
+ })
+ .collect()
+}
+
+/// The stored network of `owner` when it is written back as it was read: raw
+/// objects depend on it (see `networks_raw_objects_depend_on`) and the
+/// editor's model of the scope still equals the one the network holds. For
+/// model space that includes the drawing's parameter table, which is read
+/// from the model-space network. A scope the user changed is rebuilt as
+/// before.
+fn stored_network_to_keep(
+ document: &Document,
+ owner: Handle,
+ runtime: Option<&ParametricConstraintSet>,
+ named_parameters: &ParameterTable,
+ raw_dependents: &FxHashSet,
+) -> Option {
+ if raw_dependents.is_empty() {
+ return None;
+ }
+ let network = native_scope_network_handle(document, owner)?;
+ if !raw_dependents.contains(&network) {
+ return None;
+ }
+ let mut parameters = if owner == document.header.model_space_block_handle {
+ let loaded = loaded_named_parameters(document);
+ if has_pending_surfaces(document) || *named_parameters != loaded {
+ return None;
+ }
+ loaded
+ } else {
+ // A block scope reads its parameters into a table of its own.
+ ParameterTable::new()
+ };
+ let Some(runtime) = runtime else {
+ return Some(network);
+ };
+ let stored = native_constraint_set(document, owner, &mut parameters)?;
+ (constraint_set_hash(runtime) == constraint_set_hash(&stored)).then_some(network)
+}
+
+/// The drawing's parameter table as opening the drawing builds it: the
+/// variables of the model-space network, then whatever reading each scope's
+/// constraints adopts into it.
+fn loaded_named_parameters(document: &Document) -> ParameterTable {
+ let mut parameters = model_network_parameters(document);
+ for record in document.block_records.iter() {
+ native_constraint_set(document, record.handle, &mut parameters);
+ }
+ parameters
+}
+
+/// The named variables of the model-space network as a parameter table.
+fn model_network_parameters(document: &Document) -> ParameterTable {
+ let mut parameters = ParameterTable::new();
+ let Some(model_network) =
+ native_scope_network_handle(document, document.header.model_space_block_handle)
+ else {
+ return parameters;
+ };
+ let mut variables: Vec<_> = document
+ .objects
+ .values()
+ .filter_map(|object| match object {
+ ObjectType::Associative(AssociativeObject {
+ handle,
+ data: AssociativeData::Variable(variable),
+ ..
+ }) if variable.action.owning_network == model_network => Some((*handle, variable)),
+ _ => None,
+ })
+ .collect();
+ variables.sort_by_key(|(handle, _)| handle.value());
+ for (_, variable) in variables {
+ let source = if variable.expression.trim().is_empty() {
+ numeric_value(&variable.value).map(|value| value.to_string())
+ } else {
+ Some(variable.expression.clone())
+ };
+ if let Some(source) = source {
+ let _ = parameters.set(&variable.name, &source);
+ }
}
+ parameters
}
/// Hashes a parameter table in insertion order: each parameter's name,
@@ -4508,6 +4631,9 @@ fn hash_vector(vector: &Vector3, hasher: &mut DefaultHasher) {
vector.z.to_bits().hash(hasher);
}
+#[cfg(test)]
+mod raw_dependents_tests;
+
#[cfg(test)]
mod tests {
use super::super::parametric_constraints::{
diff --git a/src/scene/dwg_native_constraints/raw_dependents_tests.rs b/src/scene/dwg_native_constraints/raw_dependents_tests.rs
new file mode 100644
index 0000000000..6f578ef12d
--- /dev/null
+++ b/src/scene/dwg_native_constraints/raw_dependents_tests.rs
@@ -0,0 +1,303 @@
+//! A network that objects kept only as raw records depend on is written back
+//! with its handles while the editor has not changed its scope.
+//!
+//! BricsCAD keeps the visibility states of its parametric blocks in objects of
+//! its own classes. They are read here as raw records and reach the block's
+//! associative variables by handle, so a rebuild under new handles leaves them
+//! pointing at erased variables and BricsCAD drops the block's parameters.
+
+use super::*;
+use document::entities::Line;
+
+/// The objects `bind_raw_network` adds.
+struct Bound {
+ network: Handle,
+ variable: Handle,
+ raw: Handle,
+}
+
+/// Give `owner` a network with one variable, `look_1` = 1, that lists a raw
+/// object as its reactor, the way BricsCAD's variables list the objects that
+/// read them.
+fn bind_raw_network(document: &mut Document, owner: Handle) -> Bound {
+ let dictionary = document.ensure_extension_dictionary(owner);
+ let [network, variable, raw] = [(); 3].map(|_| document.allocate_handle());
+ document.objects.insert(
+ raw,
+ ObjectType::Unknown {
+ type_name: "BDMDBCONFIGVARREACTOR".to_string(),
+ handle: raw,
+ owner: dictionary,
+ raw_dxf_codes: None,
+ raw_dwg_data: Some(vec![0; 8]),
+ raw_dwg_handle_bits: 0,
+ raw_dwg_version: None,
+ },
+ );
+ document.objects.insert(
+ network,
+ ObjectType::Associative(AssociativeObject {
+ handle: network,
+ owner: dictionary,
+ reactors: vec![dictionary],
+ dxf_name: "ACDBASSOCNETWORK".to_string(),
+ cpp_class_name: "AcDbAssocNetwork".to_string(),
+ data: AssociativeData::Network(AssocNetwork {
+ action: AssocAction {
+ class_version: 2,
+ ..Default::default()
+ },
+ network_action_index: 1,
+ actions: vec![AssocActionDependency {
+ is_owned: true,
+ dependency: variable,
+ }],
+ ..Default::default()
+ }),
+ ..Default::default()
+ }),
+ );
+ document.objects.insert(
+ variable,
+ ObjectType::Associative(AssociativeObject {
+ handle: variable,
+ owner: network,
+ reactors: vec![raw],
+ dxf_name: "ACDBASSOCVARIABLE".to_string(),
+ cpp_class_name: "AcDbAssocVariable".to_string(),
+ data: AssociativeData::Variable(AssocVariable {
+ action: AssocAction {
+ class_version: 2,
+ owning_network: network,
+ action_index: 1,
+ ..Default::default()
+ },
+ class_version: 2,
+ name: "look_1".to_string(),
+ evaluator: "AcDbCalc:1.0".to_string(),
+ value: AssocEvalVariant {
+ code: 40,
+ value: AssocEvalValue::Real(1.0),
+ },
+ ..Default::default()
+ }),
+ ..Default::default()
+ }),
+ );
+ if let Some(ObjectType::Dictionary(dictionary)) = document.objects.get_mut(&dictionary) {
+ dictionary.add_entry(NETWORK_DICTIONARY_KEY, network);
+ }
+ Bound {
+ network,
+ variable,
+ raw,
+ }
+}
+
+/// A scene with one block definition holding a line.
+fn block_scene() -> (Scene, Handle) {
+ let mut scene = Scene::new();
+ scene.define_block_raw(
+ "states",
+ Vector3::ZERO,
+ vec![EntityType::Line(Line::from_points(
+ Vector3::ZERO,
+ Vector3::UNIT_X,
+ ))],
+ );
+ let block = scene.document.block_records.get("states").unwrap().handle;
+ (scene, block)
+}
+
+/// Read the drawing's parameters and constraints as opening a file does.
+fn read_as_opened(scene: &mut Scene) {
+ scene.load_named_parameters_from_document();
+ scene.load_parametric_constraints_from_document();
+}
+
+fn variable_value(document: &Document, network: Handle, name: &str) -> Option {
+ document.objects.values().find_map(|object| match object {
+ ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::Variable(variable),
+ ..
+ }) if variable.action.owning_network == network && variable.name == name => {
+ numeric_value(&variable.value)
+ }
+ _ => None,
+ })
+}
+
+#[test]
+fn a_block_network_raw_objects_depend_on_keeps_its_handles() {
+ let (mut scene, block) = block_scene();
+ let bound = bind_raw_network(&mut scene.document, block);
+ read_as_opened(&mut scene);
+ let network = scene.document.objects.get(&bound.network).cloned();
+ let variable = scene.document.objects.get(&bound.variable).cloned();
+
+ scene.sync_native_parametric_graph();
+
+ assert_eq!(
+ native_scope_network_handle(&scene.document, block),
+ Some(bound.network),
+ "the block keeps its network"
+ );
+ assert_eq!(scene.document.objects.get(&bound.network).cloned(), network);
+ assert_eq!(
+ scene.document.objects.get(&bound.variable).cloned(),
+ variable,
+ "the variable the raw object reads is written back as it was read"
+ );
+ assert!(matches!(
+ scene.document.objects.get(&bound.raw),
+ Some(ObjectType::Unknown { .. })
+ ));
+}
+
+#[test]
+fn a_model_space_network_raw_objects_depend_on_keeps_its_handles() {
+ // A drawing that is itself a BricsCAD parametric block keeps its
+ // parameters in the model-space network, which is also where the
+ // drawing's own parameter table is read from.
+ let mut scene = Scene::new();
+ let model = scene.document.header.model_space_block_handle;
+ let bound = bind_raw_network(&mut scene.document, model);
+ read_as_opened(&mut scene);
+ assert!(
+ scene.named_parameters.get("look_1").is_some(),
+ "opening reads the variable into the drawing's parameters"
+ );
+ let variable = scene.document.objects.get(&bound.variable).cloned();
+
+ scene.sync_native_parametric_graph();
+
+ assert_eq!(
+ native_scope_network_handle(&scene.document, model),
+ Some(bound.network)
+ );
+ assert_eq!(
+ scene.document.objects.get(&bound.variable).cloned(),
+ variable
+ );
+}
+
+#[test]
+fn a_parameter_changed_in_such_a_scope_is_still_written() {
+ let (mut scene, block) = block_scene();
+ let bound = bind_raw_network(&mut scene.document, block);
+ read_as_opened(&mut scene);
+ scene
+ .parametric_constraint_set_mut(ParametricScope::Block(block))
+ .local_parameters
+ .set("look_1", "0")
+ .unwrap();
+
+ scene.sync_native_parametric_graph();
+
+ let network =
+ native_scope_network_handle(&scene.document, block).expect("the block still has a network");
+ assert_ne!(network, bound.network, "a changed scope is rebuilt");
+ assert_eq!(
+ variable_value(&scene.document, network, "look_1"),
+ Some(0.0)
+ );
+}
+
+#[test]
+fn a_changed_drawing_parameter_rebuilds_the_model_space_network() {
+ let mut scene = Scene::new();
+ let model = scene.document.header.model_space_block_handle;
+ let bound = bind_raw_network(&mut scene.document, model);
+ read_as_opened(&mut scene);
+ scene.named_parameters.set("look_1", "0").unwrap();
+
+ scene.sync_native_parametric_graph();
+
+ let network = native_scope_network_handle(&scene.document, model)
+ .expect("model space still has a network");
+ assert_ne!(network, bound.network, "a changed scope is rebuilt");
+ assert_eq!(
+ variable_value(&scene.document, network, "look_1"),
+ Some(0.0)
+ );
+}
+
+#[test]
+fn a_bricscad_parametric_block_keeps_the_variables_its_objects_read_through_a_dwg_save() {
+ // tests/fixtures/bricscad/README.md describes the drawing.
+ let path = concat!(
+ env!("CARGO_MANIFEST_DIR"),
+ "/tests/fixtures/bricscad/visibility-states.dwg"
+ );
+ let bytes = std::fs::read(path).expect("read the fixture");
+ let mut scene = Scene::new();
+ scene.document =
+ crate::io::load_bytes_finalized(std::path::Path::new("visibility-states.dwg"), bytes)
+ .expect("open the fixture");
+ read_as_opened(&mut scene);
+
+ // Each variable with its name, network and the objects listed as its
+ // reactors: BricsCAD's objects, and the value dependency of a variable
+ // another one's expression reads.
+ let variables = |document: &Document| {
+ let mut rows: Vec<(Handle, String, Handle, Vec)> = document
+ .objects
+ .values()
+ .filter_map(|object| match object {
+ ObjectType::Associative(AssociativeObject {
+ handle,
+ reactors,
+ data: AssociativeData::Variable(variable),
+ ..
+ }) => Some((
+ *handle,
+ variable.name.clone(),
+ variable.action.owning_network,
+ reactors.clone(),
+ )),
+ _ => None,
+ })
+ .collect();
+ rows.sort_by_key(|row| row.0);
+ rows
+ };
+ let value_dependencies = |document: &Document| {
+ document
+ .objects
+ .values()
+ .filter(|object| {
+ matches!(
+ object,
+ ObjectType::Associative(AssociativeObject {
+ data: AssociativeData::ValueDependency(_),
+ ..
+ })
+ )
+ })
+ .count()
+ };
+ let before = variables(&scene.document);
+ assert_eq!(
+ before.len(),
+ 18,
+ "six variables in each of the three blocks"
+ );
+ assert_eq!(value_dependencies(&scene.document), 6);
+
+ scene.sync_native_parametric_graph();
+ let saved = crate::io::save_to_bytes(&scene.document, "dwg", scene.document.version)
+ .expect("save as DWG");
+ let reopened = crate::io::load_bytes_finalized(std::path::Path::new("saved.dwg"), saved)
+ .expect("open the saved DWG");
+
+ assert_eq!(variables(&reopened), before);
+ assert_eq!(value_dependencies(&reopened), 6);
+ for (handle, name, _, reactors) in &before {
+ for reactor in reactors {
+ assert!(
+ reopened.objects.contains_key(reactor),
+ "{name} ({handle:?}) lists {reactor:?}, which the saved drawing lost"
+ );
+ }
+ }
+}
diff --git a/src/scene/mod.rs b/src/scene/mod.rs
index 41e5a9a332..79430524e6 100644
--- a/src/scene/mod.rs
+++ b/src/scene/mod.rs
@@ -26,6 +26,7 @@ pub(crate) mod block_point_parameter;
pub(crate) mod block_properties_table;
pub mod block_service;
pub mod block_visibility;
+pub(crate) mod bricscad_parameters;
pub mod cache;
pub mod compare;
pub mod convert;
diff --git a/src/scene/model/object.rs b/src/scene/model/object.rs
index 849142ac86..98da238b9e 100644
--- a/src/scene/model/object.rs
+++ b/src/scene/model/object.rs
@@ -22,6 +22,9 @@ pub enum BlockParameterComponent {
Angle,
Flip,
Visibility(u64),
+ // A BricsCAD parametric block's visibility parameter, with a hash of its
+ // name and states.
+ Bricscad(u64),
TableRow(u64),
LookupOutput { column: usize, revision: u64 },
}
diff --git a/src/ui/dock.rs b/src/ui/dock.rs
index 76eb0eec44..ec458c5d15 100644
--- a/src/ui/dock.rs
+++ b/src/ui/dock.rs
@@ -133,6 +133,8 @@ pub enum PanelId {
PointCloudManager,
/// Block counts (COUNTLIST).
Count,
+ /// Visibility states of a BricsCAD parametric block (VISIBILITYSTATESPANELOPEN).
+ BricscadVisibility,
/// The open sheet sets: subsets and sheets.
SheetSetManager,
/// The Layer Manager (LAYERS).
@@ -151,7 +153,7 @@ pub enum PanelId {
impl PanelId {
/// Every panel, in the order the pallet menu lists them.
- pub const ALL: [PanelId; 17] = [
+ pub const ALL: [PanelId; 18] = [
PanelId::Properties,
PanelId::GraphicAttributes,
PanelId::BlockPalette,
@@ -163,6 +165,7 @@ impl PanelId {
PanelId::NodeGraph,
PanelId::PointCloudManager,
PanelId::Count,
+ PanelId::BricscadVisibility,
PanelId::SheetSetManager,
PanelId::Layers,
PanelId::Laywalk,
@@ -185,6 +188,7 @@ impl PanelId {
PanelId::NodeGraph => "Node Graph",
PanelId::PointCloudManager => "Point Cloud Manager",
PanelId::Count => "Count",
+ PanelId::BricscadVisibility => "Visibility States",
PanelId::SheetSetManager => "Sheet Set Manager",
PanelId::Layers => "Layer Manager",
PanelId::Laywalk => "Layer Walk",
@@ -211,6 +215,7 @@ impl PanelId {
PanelId::NodeGraph => crate::ui::icons::NODE_GRAPH,
PanelId::PointCloudManager => include_bytes!("../../assets/icons/pc_attach.svg"),
PanelId::Count => include_bytes!("../../assets/icons/data_extract.svg"),
+ PanelId::BricscadVisibility => include_bytes!("../../assets/icons/ui/eye.svg"),
PanelId::SheetSetManager => include_bytes!("../../assets/icons/sheetset.svg"),
PanelId::Layers => include_bytes!("../../assets/icons/layers/panel.svg"),
PanelId::Laywalk => include_bytes!("../../assets/icons/layers/laywalk.svg"),
@@ -235,6 +240,7 @@ impl PanelId {
PanelId::NodeGraph => 220.0,
PanelId::PointCloudManager => 280.0,
PanelId::Count => 280.0,
+ PanelId::BricscadVisibility => 280.0,
PanelId::SheetSetManager => 280.0,
PanelId::Layers => 560.0,
PanelId::Laywalk => 420.0,
diff --git a/src/ui/ribbon/keytips.rs b/src/ui/ribbon/keytips.rs
index ef61c7db19..4673882e93 100644
--- a/src/ui/ribbon/keytips.rs
+++ b/src/ui/ribbon/keytips.rs
@@ -477,6 +477,7 @@ const CODES: &[(&str, &str, &str)] = &[
("parametric", "DCHIDEALL", "HD"),
("parametric", "DELCONSTRAINT", "DE"),
("parametric", "PARAMETERS", "PM"),
+ ("parametric", "VISIBILITYSTATESPANELOPEN", "VS"),
// Model (the reference Solid tab).
("model", "MODEL_PRIMITIVES", "SS"),
("MODEL_PRIMITIVES", "BOX", "BO"),
diff --git a/src/ui/window/bricscad_visibility.rs b/src/ui/window/bricscad_visibility.rs
new file mode 100644
index 0000000000..3794052deb
--- /dev/null
+++ b/src/ui/window/bricscad_visibility.rs
@@ -0,0 +1,430 @@
+//! The Visibility States palette (VISIBILITYSTATESPANELOPEN): the visibility
+//! parameters of a BricsCAD parametric block in model space of the block's
+//! own drawing, edited the way `VISIBILITYSTATES` edits them.
+//!
+//! The overview lists each parameter with its states; a click on a state
+//! shows it, the arrow opens the state's page. A state's page lists every
+//! object the parameter rules with whether it shows in that state, and adds
+//! or removes objects. Every change goes through the command's own edit
+//! (`scene::bricscad_parameters::author`), one undo step each.
+
+use crate::app::Message;
+use crate::scene::bricscad_parameters::ParameterView;
+use crate::ui::dock::PanelId;
+use crate::ui::kit;
+use crate::ui::kit::field_style;
+use crate::ui::style::kit_metrics as km;
+use document::Handle;
+use iced::widget::{column, container, row, text_input, Space};
+use iced::{Element, Fill, Length, Padding};
+use rustc_hash::FxHashMap;
+use std::cell::RefCell;
+use std::rc::Rc;
+
+const ADD_ICON: &[u8] = include_bytes!("../../../assets/icons/ui/plus.svg");
+const OPEN_ICON: &[u8] = include_bytes!("../../../assets/icons/ui/tri_right.svg");
+const BACK_ICON: &[u8] = include_bytes!("../../../assets/icons/ui/tri_left.svg");
+const UP_ICON: &[u8] = include_bytes!("../../../assets/icons/ui/tri_up.svg");
+const DOWN_ICON: &[u8] = include_bytes!("../../../assets/icons/ui/tri_down.svg");
+const SHOWN_ICON: &[u8] = include_bytes!("../../../assets/icons/ui/eye.svg");
+const HIDDEN_ICON: &[u8] = include_bytes!("../../../assets/icons/ui/eye_off.svg");
+const REMOVE_ICON: &[u8] = include_bytes!("../../../assets/icons/ui/close.svg");
+const PICK_ICON: &[u8] = include_bytes!("../../../assets/icons/blocks/select_objects.svg");
+const WARNING_ICON: &[u8] = include_bytes!("../../../assets/icons/ui/warning_triangle.svg");
+
+/// The palette's own state; the parameters come from the drawing.
+#[derive(Debug, Clone, Default)]
+pub struct VisibilityPanel {
+ pub show: bool,
+ /// The state whose page is open: parameter and state.
+ pub page: Option<(String, String)>,
+ /// A parameter being added: its name and its first state.
+ pub new_parameter: Option<(String, String)>,
+ /// A state being added: the parameter and the name typed.
+ pub new_state: Option<(String, String)>,
+ /// Folded parameters (names in upper case).
+ pub folded: Vec,
+ /// What the drawing holds, read at (document id, edit revision, language).
+ pub cache: RefCell)>>,
+}
+
+/// A drawing's visibility parameters as the palette shows them.
+#[derive(Debug, Default)]
+pub struct Model {
+ /// `None` when they cannot be edited here.
+ pub parameters: Option>,
+ /// Each ruled object's line: type, layer when shown, handle.
+ pub labels: FxHashMap,
+}
+
+#[derive(Debug, Clone)]
+pub enum VisMsg {
+ /// Show the state (parameter, state).
+ Select(String, String),
+ /// Open the state's page.
+ Open(String, String),
+ /// Move the state one place up (`true`) or down in the parameter's list.
+ Move(String, String, bool),
+ Back,
+ Fold(String),
+ NewParameter,
+ NewParameterName(String),
+ NewParameterState(String),
+ /// Pick the objects the new parameter starts with.
+ NewParameterPick,
+ NewState(String),
+ NewStateName(String),
+ NewStateCommit,
+ Cancel,
+ /// Show or hide an object in the open state.
+ Show(Handle, bool),
+ /// The parameter no longer rules the object.
+ Remove(Handle),
+ /// Pick objects for the open state.
+ AddObjects,
+ /// Select the object in the drawing.
+ Highlight(Handle),
+}
+
+fn msg(m: VisMsg) -> Message {
+ Message::BricscadVisibility(m)
+}
+
+fn icon<'a>(bytes: &'static [u8]) -> Element<'a, Message> {
+ crate::ui::icons::semantic(bytes, km::ROW_ICON)
+}
+
+/// Read what `document`'s model space holds for the palette.
+pub fn read(document: &document::Document) -> Model {
+ let owner = document.header.model_space_block_handle;
+ let parameters = crate::scene::bricscad_parameters::parameter_views(document, owner);
+ let layers = crate::scene::bricscad_parameters::shown_layers(document, owner);
+ let mut labels = FxHashMap::default();
+ for parameter in parameters.iter().flatten() {
+ for (entity, _) in ¶meter.objects {
+ labels.entry(*entity).or_insert_with(|| {
+ let kind = document
+ .get_entity(*entity)
+ .map(|e| crate::t!(crate::entities::names::ui_name(e)).into_owned())
+ .unwrap_or_default();
+ let layer = layers.get(entity).cloned().unwrap_or_default();
+ format!("{kind} · {layer} · {:X}", entity.value())
+ });
+ }
+ }
+ Model { parameters, labels }
+}
+
+/// `None` outside model space.
+pub fn view<'a>(
+ panel: &'a VisibilityPanel,
+ model: Option