mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-29 17:53:59 +01:00
Fixes #3055. ## What Inside an MSPACE viewport an object on a layer frozen in that viewport (VPLAYER, VP Freeze) is not drawn, but it could still be picked, window-selected and edited through the viewport, and a selected one kept its grips. `Drawing::is_visible` has no viewport, and selection and grips asked only that. Three questions now take the active viewport into account: - `select::selectable(d, e, frozen)`: what a selection can take. `frozen` is `DocState::viewport_frozen()`, the layers frozen in the active MSPACE viewport (empty in paper space and on the Model tab). The selection functions have `_in` variants that take it (`pick_in`, `pick_all_in`, `select_window_in`, `select_fence_in`, `select_polygon_in`, `select_group_in`, `SelectMode::select_in`); the existing functions keep their signatures and select as before. - `DocState::shows(e)`: what the view being edited shows, `is_visible` plus the active viewport. Grips ask it where #3048 made them ask `is_visible`. - `Session::selection()`: the selection as the view being edited has it, without the model-space objects the active viewport does not draw (`DocState::shown_selection`). The stored selection, `DocState::selection`, keeps them. **Selecting.** Every selection made in the space being edited passes the active viewport's frozen layers: - idle clicks and windows, "Select objects" (a pick, the implied window, W, C, BOX, F, WP, CP, ALL, G, and L and P, which take the last object the viewport draws and the part of the Previous set it draws), selection cycling, and prompts that pick one object; - `select`, `selectall`, `selectsimilar`, and the group members a pick brings (PICKSTYLE); - the commands that select for themselves: STRETCH (JSON and typed, with its own All, Last and Previous and its multiline vertex rule), TRIM and EXTEND by fence and by crossing window; - AutoLISP `ssget` (W, C, F, WP, CP, a point, P, L) and `entsel`; - in the UI, the rollover highlight and the hatch under the cursor that a double-click edits. The object under the cursor and selection cycling's badge are worked out again when the active viewport's frozen layers change under a pointer that does not move. **Already selected.** An object that is selected when its layer is frozen in the active viewport stays in the stored selection until the selection is replaced or cleared, and counts as selected again once the layer is thawed there. Until then `Session::selection()` leaves it out, and with it everything that starts from the selection: the selection made before a command (PICKFIRST), a JSON command that names no objects, Delete, the grip edits that cover the selection, AutoLISP's implied selection (`ssget`, `ssget "I"`, `ssgetfirst`), the palettes, and what the session reports as the selection (`summary`, `drawing.inspect`). Two UI functions read the stored selection themselves and now read `shown_selection` too: the hatch editor's edit mode and BEDIT's choice between editor and dialog. The selection highlight inside the active viewport leaves the object out as well. Adding to the selection or removing from it (a click, a window, `select` with `add` or with nothing to select with, QSELECT appending) starts from the stored selection (`Session::stored_selection()`), so such an object is not dropped while the selection changes around it. A command that takes the selection, or a new selection, replaces it as before. `Session::selection()` gives the stored selection unchanged wherever the active viewport hides none of the selected objects: in paper space, on the Model tab, and in a viewport that freezes no layer. The UI asks for the selection several times a frame, so `DocState::drawn_in_viewport` does not look every selected object up: a few handles are looked up one by one, and beyond that it passes over model space once. **Grips.** Static grip painting and hit testing, hot grips (`click_grip`), the grip edit's targets and the typed GRIP command (`griphot.rs`), and dynamic grips ask `shows`. The dynamic-grip cache key now holds the active viewport's frozen layers: entering another viewport changes which references are shown without changing the drawing revision, so the key did not change. The grip code asks for itself, as it does for `is_visible` since #3048, so it does not depend on who hands it the objects. A viewport's frozen layers hide model-space objects only, never an object on the sheet. Layer names are compared the way the renderer compares them. Outside a viewport, and in a viewport that freezes no layer, nothing changes. ## Test The tests build two viewports on one layout, one of which freezes a layer. Most take the same path through both: through the viewport that freezes the layer the object on it is left out, through the other one it is taken as before. The ones about an object that is already selected freeze and thaw its layer in the viewport being edited. `crates/engine/tests/it/viewport_frozen_selection.rs`, 22 tests: - selecting: a pick, window / crossing / fence, idle clicks and windows, selection cycling, every answer to "Select objects" (with ERASE), group members, `selectall` and `selectsimilar`, STRETCH (JSON; typed crossing window, All, a pick, Last, Previous; the multiline vertex rule), TRIM by fence and by crossing window, a prompt for one object (BREAK), LEADER's Copy, AutoLISP `ssget` and `entsel`; - already selected: a typed command with PICKFIRST, a JSON command without handles and Delete; Previous and Last; the grip edits that cover the selection; what the session reports, with paper space and the Model tab unchanged; adding to and removing from the selection; a small and a large selection (the two paths of `drawn_in_viewport`, in a drawing whose draw order is not the order of its handles); - grips: a shared grip, the grips of an object whose layer is frozen and thawed again while it is selected, and what the edited view shows (model-space objects only, never an object on the sheet). `crates/ui-egui`, 9 unit tests (hot grips, the grip and the hatch under the cursor, the viewport highlight, dynamic grips and their cache key, BEDIT's choice, the hatch editor's edit mode, selection cycling's badge under a resting pointer) and `tests/viewport_frozen_grips.rs`, 3 tests (no grips painted for a selected object the viewport does not draw; the rollover highlight; the highlight under a resting pointer while the layer is frozen and thawed). EXTEND runs TRIM's selection code and has no test of its own. Without the change these tests fail, checked call by call with a temporary switch that is not in this PR: each of the 60 calls of `viewport_frozen`, `shows`, `hidden_in_viewport`, `drawn_in_viewport`, `shown_selection`, `last_in` and `stored_selection` outside tests was put back to the old behaviour on its own. 51 of them made at least one test fail directly; 5 grip checks that sit behind `Session::selection()` did so with the getter switched back as well; the other 4 are calls inside `DocState` that the same tests reach through their callers. Each path of `drawn_in_viewport`, and its sort, fails a test when switched off. Of the 42 calls of `Session::selection()`, 10 have a test that fails when that one call reads the stored selection; the other 32 receive the same list and have no test of their own. The second commit's two conditions (the hover and the badge under a resting pointer) each have a test that fails without them. ## What ran The seven steps of `cargo xtask ci`, one by one, on this branch at6754b960(main atddfa833bplus its two commits): fmt, clippy (workspace, all targets, `-D warnings`), test (3725 passed, 0 failed, 26 ignored; the doctest step ran, the workspace has no doctests), the i18n report, assets, layers and wasm. All pass. ## Not in this PR - A selected object whose layer is turned off or frozen for the whole drawing is still taken by a command that starts from the selection, as before (ran: ERASE and MOVE typed and as JSON, and Delete, edit it). The issue asks to keep the drawing-wide behaviour, so this PR leaves it alone. - A command that is given object handles (`handles` in JSON, an entity name from AutoLISP) acts on them as before, whatever the viewport draws. QSELECT and `ssget "X"` look at the whole drawing; what they put in the stored selection is then left out like any other selected object the viewport does not draw. - `ssget "L"` takes the last object of any space, as before; inside a viewport it now passes over the objects that viewport does not draw. - Object snap, hatch boundary detection, the implied cutting edges of TRIM and EXTEND, constraint inference, and the Z that ID and DIST read from an object under the point are not selections and are unchanged. - A block reference on a layer the viewport draws, with parts on a layer frozen in the viewport: the parts are not drawn, but the hit geometry of a reference is built without the viewport, so a pick where such a part would be still finds the reference. Ran oneaae189fwith a test that is not in the PR: a pick, a crossing window and a fence on such a part select the reference, and a window around the drawn part alone does not; with the layer frozen for the whole drawing it is the other way round. It needs extents that know the viewport, which `crates/doc` does not have, so it is left for its own change. - Visibility that changes while an interactive command is already waiting, or while a grip list is open, is #3056. ## Compared with AutoCAD 2022 Observed as a black box, in a drawing made there for this and driven by a script: two lines, one of them on a layer frozen (VPLAYER) in one of two layout viewports. No file from it is in this PR. Inside the viewport that freezes the layer, the same there and here: a pick, a window, a crossing window, a fence and a crossing polygon (`ssget`), ALL, Last, a crossing window and a fence at "Select objects", `ssget "L"`, select all, and STRETCH's crossing window leave the object out; `ssget "X"` returns it; a command that is given the object itself (its entity name there, `handles` here) changes it. Through the other viewport the pick, the windows, the fence, ALL, Last and STRETCH took it. Different, where the issue asks for more ("cannot be edited through that viewport, including when they were already selected"): - An object selected through the other viewport stays in the implied selection when the viewport that freezes its layer becomes the active one (`ssgetfirst`, `ssget "I"`), and ERASE typed there erased it. Here the commands leave it out. - Previous: `ssget "P"` returned the set made through the other viewport whole, and CHPROP with Previous changed the object. Here Previous takes the part of that set the viewport draws. A comment on the issue asks which of the two is wanted. This PR follows the issue as written; if AutoCAD's behaviour is preferred for these two cases, I will change them here. Not observed there: grips (a script cannot read them), and freezing the layer while objects are selected (VPLAYER is a command and cleared the selection). ## Parity rows U5 (grips) and F15 (viewports) in docs/gaps.md. No docs edited. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Selection, picking, hover highlighting, and grip interactions now respect layers frozen in the active model-space viewport. * Selection reports and editing tools show only objects visible in the active viewport, while stored selections retain hidden objects. * Window, crossing, fence, point, and other selection modes now apply viewport visibility consistently. * **Bug Fixes** * Changing viewports or freezing and thawing layers now updates selection highlights, hover targets, and grips to match what the active viewport displays. * Selection commands and object inspection now consistently reflect viewport visibility. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
261 lines
10 KiB
Rust
261 lines
10 KiB
Rust
//! Selection tools: SELECTSIMILAR (objects like the selected ones, per SELECTSIMILARMODE) and
|
|
//! object isolation — ISOLATEOBJECTS, HIDEOBJECTS, UNISOLATEOBJECTS.
|
|
//!
|
|
//! Isolation is temporary (OBJECTISOLATIONMODE 0): hidden objects are kept in
|
|
//! [`Drawing::hidden_objects`], which display, selection, snapping and plotting skip and which
|
|
//! is never written to a file. Hiding and showing are undoable like any other change.
|
|
|
|
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle};
|
|
use serde_json::{Value, json};
|
|
|
|
use super::machines::{SelOutcome, SelectPhase, SelectRun};
|
|
use super::{CommandSpec, bad, targets};
|
|
|
|
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
|
|
|
|
/// Most objects one call looks at (a hostile drawing can be huge).
|
|
const MAX_SCAN: usize = 2_000_000;
|
|
|
|
pub fn specs() -> Vec<CommandSpec> {
|
|
vec![
|
|
CommandSpec::new("selectsimilar", "Select Similar", run_selectsimilar)
|
|
.params(
|
|
"{handles? (default the selection), mode?: SELECTSIMILARMODE bits (1 colour, 2 layer, 4 linetype, 8 linetype scale, \
|
|
16 lineweight, 32 plot style, 64 object style, 128 name; default the variable, 130)} → selects every visible object \
|
|
in the current space of the same type with those properties: {selected, handles}",
|
|
)
|
|
.noundo()
|
|
.interactive(|_| Ok(Box::new(SelectSimilarM::default()))),
|
|
CommandSpec::new("isolateobjects", "Isolate Objects", run_isolate)
|
|
.menu(&["Tools", "Isolate", "Isolate Objects"])
|
|
.params("{handles? (default the selection)} → hides every other object of the current space for this session: {hidden}")
|
|
.interactive(|_| Ok(Box::new(SelectRun::new("isolateobjects", "ISOLATEOBJECTS")))),
|
|
CommandSpec::new("hideobjects", "Hide Objects", run_hide)
|
|
.menu(&["Tools", "Isolate", "Hide Objects"])
|
|
.params("{handles? (default the selection)} → hides these objects for this session: {hidden}")
|
|
.interactive(|_| Ok(Box::new(SelectRun::new("hideobjects", "HIDEOBJECTS")))),
|
|
CommandSpec::new("unisolateobjects", "End Object Isolation", run_unisolate)
|
|
.menu(&["Tools", "Isolate", "End Object Isolation"])
|
|
.params("{} → shows every object ISOLATEOBJECTS or HIDEOBJECTS hid: {shown}"),
|
|
]
|
|
}
|
|
|
|
// ---------------- SELECTSIMILAR ----------------
|
|
|
|
/// SELECTSIMILARMODE bits.
|
|
const COLOR: u32 = 1;
|
|
const LAYER: u32 = 2;
|
|
const LINETYPE: u32 = 4;
|
|
const LTSCALE: u32 = 8;
|
|
const LINEWEIGHT: u32 = 16;
|
|
const PLOT_STYLE: u32 = 32;
|
|
const OBJECT_STYLE: u32 = 64;
|
|
const NAME: u32 = 128;
|
|
|
|
/// The style an object is drawn with: text, dimension, leader, multileader or table style, or a
|
|
/// hatch pattern.
|
|
fn object_style(e: &Entity) -> Option<&str> {
|
|
Some(match &e.kind {
|
|
EntityKind::Text(t) => &t.style,
|
|
EntityKind::MText(t) => &t.style,
|
|
EntityKind::AttDef(a) => &a.text.style,
|
|
EntityKind::Dimension(d) => &d.style,
|
|
EntityKind::Leader(l) => &l.style,
|
|
EntityKind::MLeader(m) => &m.style,
|
|
EntityKind::Table(t) => &t.style,
|
|
EntityKind::Hatch(h) => &h.pattern,
|
|
_ => return None,
|
|
})
|
|
}
|
|
|
|
/// The name an object references: a block reference's block, a raster image's definition.
|
|
fn object_name(e: &Entity) -> Option<&str> {
|
|
match &e.kind {
|
|
EntityKind::Insert(i) => Some(&i.block),
|
|
EntityKind::Image(i) => Some(if i.name.is_empty() { &i.path } else { &i.name }),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
fn same_text(a: Option<&str>, b: Option<&str>) -> bool {
|
|
match (a, b) {
|
|
(Some(a), Some(b)) => a.eq_ignore_ascii_case(b),
|
|
(None, None) => true,
|
|
_ => false,
|
|
}
|
|
}
|
|
|
|
/// Is `e` like `r`: the same object type and, for each bit of `mode`, the same property?
|
|
pub(crate) fn similar(e: &Entity, r: &Entity, mode: u32) -> bool {
|
|
let (a, b) = (&e.common, &r.common);
|
|
e.kind.dxf_name().eq_ignore_ascii_case(r.kind.dxf_name())
|
|
&& (mode & COLOR == 0 || a.color == b.color)
|
|
&& (mode & LAYER == 0 || a.layer.eq_ignore_ascii_case(&b.layer))
|
|
&& (mode & LINETYPE == 0 || a.linetype.eq_ignore_ascii_case(&b.linetype))
|
|
&& (mode & LTSCALE == 0 || (a.ltscale - b.ltscale).abs() <= 1e-9 * a.ltscale.abs().max(b.ltscale.abs()).max(1.0))
|
|
&& (mode & LINEWEIGHT == 0 || a.lineweight == b.lineweight)
|
|
&& (mode & PLOT_STYLE == 0 || a.plot_style.eq_ignore_ascii_case(&b.plot_style))
|
|
&& (mode & OBJECT_STYLE == 0 || same_text(object_style(e), object_style(r)))
|
|
&& (mode & NAME == 0 || same_text(object_name(e), object_name(r)))
|
|
}
|
|
|
|
/// The objects of the current space like any of `refs` that a selection can take there: visible,
|
|
/// and inside an MSPACE viewport not on a layer frozen in it.
|
|
fn similar_objects(s: &Session, d: &Drawing, refs: &[Handle], mode: u32) -> Vec<Handle> {
|
|
let refs: Vec<&Entity> = refs.iter().filter_map(|h| d.entity(*h).map(|e| e.as_ref())).collect();
|
|
if refs.is_empty() {
|
|
return Vec::new();
|
|
}
|
|
let Some(store) = d.space(&s.space()) else { return Vec::new() };
|
|
let frozen = s.viewport_frozen();
|
|
store
|
|
.iter()
|
|
.take(MAX_SCAN)
|
|
.filter(|e| crate::select::selectable(d, e, frozen) && refs.iter().any(|r| similar(e, r, mode)))
|
|
.map(|e| e.handle)
|
|
.collect()
|
|
}
|
|
|
|
fn mode_param(s: &Session, p: &Value) -> Result<u32> {
|
|
match p.get("mode") {
|
|
None | Some(Value::Null) => Ok(s.settings.selectsimilarmode),
|
|
Some(v) => v
|
|
.as_u64()
|
|
.filter(|m| *m <= 255)
|
|
.map(|m| m as u32)
|
|
.ok_or_else(|| bad("selectsimilar", "`mode` must be a SELECTSIMILARMODE bit code from 0 to 255")),
|
|
}
|
|
}
|
|
|
|
fn run_selectsimilar(s: &mut Session, p: &Value) -> Result<Value> {
|
|
let refs = targets(s, p)?;
|
|
let mode = mode_param(s, p)?;
|
|
if refs.is_empty() {
|
|
return Err(bad("selectsimilar", "select objects to match"));
|
|
}
|
|
let found = similar_objects(s, s.doc()?, &refs, mode);
|
|
if found.is_empty() {
|
|
return Err(bad("selectsimilar", "none of the given objects exist in the current space"));
|
|
}
|
|
s.set_selection(found);
|
|
let sel = s.selection();
|
|
let n = sel.len();
|
|
Ok(json!({ "selected": n, "handles": sel.iter().map(|h| h.hex()).collect::<Vec<_>>(), "message": format!("{n} found") }))
|
|
}
|
|
|
|
/// SELECTSIMILAR typed: "Select objects or [SEttings]:"; Enter selects the similar objects.
|
|
/// SEttings asks for the SELECTSIMILARMODE bit code (the command line has no dialog).
|
|
#[derive(Default)]
|
|
struct SelectSimilarM {
|
|
sel: SelectPhase,
|
|
settings: bool,
|
|
}
|
|
|
|
impl SelectSimilarM {
|
|
fn finish(&self, s: &mut Session, hs: &[Handle]) -> Result<Step> {
|
|
let r = run_selectsimilar(s, &json!({ "handles": hs.iter().map(|h| h.hex()).collect::<Vec<_>>() }))?;
|
|
if let Some(m) = r.get("message").and_then(Value::as_str) {
|
|
s.echo(m.to_string());
|
|
}
|
|
Ok(Step::Done)
|
|
}
|
|
}
|
|
|
|
impl Interactive for SelectSimilarM {
|
|
fn name(&self) -> &'static str {
|
|
"SELECTSIMILAR"
|
|
}
|
|
fn begin(&mut self, s: &mut Session) -> Result<Step> {
|
|
self.sel = SelectPhase::begin(s);
|
|
if self.sel.done {
|
|
let hs = self.sel.picked.clone();
|
|
return self.finish(s, &hs);
|
|
}
|
|
Ok(Step::Continue)
|
|
}
|
|
fn prompt(&self, s: &Session) -> Prompt {
|
|
if self.settings {
|
|
return Prompt::new("Enter properties to match (SELECTSIMILARMODE bit code)", Accept::NUMBER)
|
|
.default(s.settings.selectsimilarmode.to_string());
|
|
}
|
|
self.sel.prompt().kw(&["SEttings"])
|
|
}
|
|
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
|
|
if self.settings {
|
|
match &i {
|
|
Input::Enter => {}
|
|
Input::Text(t) | Input::Keyword(t) => crate::sysvars::set(s, "SELECTSIMILARMODE", &json!(t.trim()))?,
|
|
_ => return Ok(Step::Continue),
|
|
}
|
|
self.settings = false;
|
|
return Ok(Step::Continue);
|
|
}
|
|
if let Input::Keyword(k) | Input::Text(k) = &i
|
|
&& k.trim().eq_ignore_ascii_case("settings")
|
|
{
|
|
self.settings = true;
|
|
return Ok(Step::Continue);
|
|
}
|
|
match self.sel.feed(s, &i)? {
|
|
SelOutcome::More => Ok(Step::Continue),
|
|
SelOutcome::Empty => Ok(Step::Done),
|
|
SelOutcome::Done(hs) => self.finish(s, &hs),
|
|
}
|
|
}
|
|
}
|
|
|
|
// ---------------- isolation ----------------
|
|
|
|
/// Hide `hs` (objects that exist and aren't hidden yet); returns how many were hidden.
|
|
fn hide(s: &mut Session, hs: Vec<Handle>) -> Result<usize> {
|
|
let d = s.doc()?;
|
|
let hs: Vec<Handle> = hs.into_iter().filter(|h| d.entity(*h).is_some() && !d.is_hidden_object(*h)).collect();
|
|
if !hs.is_empty() {
|
|
s.doc_mut()?.hidden_objects.extend(hs.iter().copied());
|
|
}
|
|
// Hidden objects can't stay selected.
|
|
s.set_selection(Vec::new());
|
|
Ok(hs.len())
|
|
}
|
|
|
|
fn hidden_message(n: usize) -> String {
|
|
if n == 1 { "1 object hidden".to_string() } else { format!("{n} objects hidden") }
|
|
}
|
|
|
|
fn run_isolate(s: &mut Session, p: &Value) -> Result<Value> {
|
|
let keep = targets(s, p)?;
|
|
if keep.is_empty() {
|
|
return Err(bad("isolateobjects", "select objects to isolate"));
|
|
}
|
|
let d = s.doc()?;
|
|
if !keep.iter().any(|h| d.entity(*h).is_some()) {
|
|
return Err(bad("isolateobjects", "none of the given objects exist"));
|
|
}
|
|
let keep_set: std::collections::HashSet<Handle> = keep.iter().copied().collect();
|
|
let others: Vec<Handle> = d
|
|
.space(&s.space())
|
|
.map(|st| st.iter().take(MAX_SCAN).filter(|e| !keep_set.contains(&e.handle)).map(|e| e.handle).collect())
|
|
.unwrap_or_default();
|
|
let n = hide(s, others)?;
|
|
Ok(json!({ "hidden": n, "message": hidden_message(n) }))
|
|
}
|
|
|
|
fn run_hide(s: &mut Session, p: &Value) -> Result<Value> {
|
|
let hs = targets(s, p)?;
|
|
if hs.is_empty() {
|
|
return Err(bad("hideobjects", "select objects to hide"));
|
|
}
|
|
let n = hide(s, hs)?;
|
|
Ok(json!({ "hidden": n, "message": hidden_message(n) }))
|
|
}
|
|
|
|
fn run_unisolate(s: &mut Session, _p: &Value) -> Result<Value> {
|
|
let n = s.doc()?.hidden_objects.len();
|
|
if n == 0 {
|
|
return Ok(json!({ "shown": 0, "message": "No objects are isolated or hidden." }));
|
|
}
|
|
s.doc_mut()?.hidden_objects.clear();
|
|
let msg = if n == 1 { "1 object shown".to_string() } else { format!("{n} objects shown") };
|
|
Ok(json!({ "shown": n, "message": msg }))
|
|
}
|