Stand-up offer: a note only when the part seems to lie on its back (#7717) (#7718)

* claim: #7717

* Stand-up offer: a note only when the part seems to lie on its back (#7717)

* Stand-up note: an unclear shape still gets the note

* Stand-up note: a Don't ask again button, as the dialog has

* Control protocol: the stand-up settings in the sorted ui.prefs list (#7717)

* Stand-up note: the control import test asks as before (#7717)

The test checks the caller's `up`, so it sets the setting to Ask and every
file from another program still gets the offer.
This commit is contained in:
raykholo authored and GitHub committed 2026-10-28 19:40:25 +00:00
1 parent a95f30f186
commit e2935aff95
11 files changed
+643 -35

No files matched your search

+72
View File
@@ -0,0 +1,72 @@
{
"en": {
"Did this assembly open the wrong way up?": "Did this assembly open the wrong way up?",
"Did this part open the wrong way up?": "Did this part open the wrong way up?",
"Stand this assembly up?": "Stand this assembly up?",
"prefs.stand_up_unknown": "For files from unknown programs",
"prefs.stand_up_unknown.ask": "Ask in a dialog",
"prefs.stand_up_unknown.note": "Show a note",
"prefs.stand_up_unknown.off": "Don't offer",
"prefs.stand_up_unknown_note": "How the offer is made when the file's header names no program known to save Y up. A note is shown only when the file seems to lie on its back; Ask in a dialog asks about every such file, as before."
},
"de": {
"Did this assembly open the wrong way up?": "Wurde diese Baugruppe falsch herum geöffnet?",
"Did this part open the wrong way up?": "Wurde dieses Teil falsch herum geöffnet?",
"Stand this assembly up?": "Diese Baugruppe aufrichten?",
"prefs.stand_up_unknown": "Für Dateien aus unbekannten Programmen",
"prefs.stand_up_unknown.ask": "In einem Dialog fragen",
"prefs.stand_up_unknown.note": "Einen Hinweis zeigen",
"prefs.stand_up_unknown.off": "Nicht anbieten",
"prefs.stand_up_unknown_note": "Wie das Aufrichten angeboten wird, wenn der Dateikopf kein Programm nennt, das bekanntlich mit Y nach oben speichert. Ein Hinweis erscheint nur, wenn die Datei auf dem Rücken zu liegen scheint; „In einem Dialog fragen“ fragt wie bisher bei jeder solchen Datei."
},
"ar": {
"Did this assembly open the wrong way up?": "هل فُتحت هذه المجموعة مقلوبة الاتجاه؟",
"Did this part open the wrong way up?": "هل فُتحت هذه القطعة مقلوبة الاتجاه؟",
"Stand this assembly up?": "إيقاف هذه المجموعة قائمة؟",
"prefs.stand_up_unknown": "للملفات من برامج غير معروفة",
"prefs.stand_up_unknown.ask": "السؤال في مربع حوار",
"prefs.stand_up_unknown.note": "عرض ملاحظة",
"prefs.stand_up_unknown.off": "عدم العرض",
"prefs.stand_up_unknown_note": "طريقة العرض عندما لا يذكر رأس الملف برنامجًا معروفًا بحفظ المحور Y للأعلى. تظهر الملاحظة فقط عندما يبدو أن الملف ملقى على ظهره؛ أما «السؤال في مربع حوار» فيسأل عن كل ملف كهذا، كما كان سابقًا."
},
"he": {
"Did this assembly open the wrong way up?": "האם המכלול הזה נפתח הפוך?",
"Did this part open the wrong way up?": "האם החלק הזה נפתח הפוך?",
"Stand this assembly up?": "להעמיד את המכלול הזה?",
"prefs.stand_up_unknown": "לקבצים מתוכנות לא מוכרות",
"prefs.stand_up_unknown.ask": "לשאול בתיבת דו־שיח",
"prefs.stand_up_unknown.note": "להציג הערה",
"prefs.stand_up_unknown.off": "לא להציע",
"prefs.stand_up_unknown_note": "איך ההצעה מוצגת כשכותרת הקובץ לא מציינת תוכנה שידוע שהיא שומרת עם Y למעלה. הערה מוצגת רק כשנראה שהקובץ שוכב על גבו; ״לשאול בתיבת דו־שיח״ שואל על כל קובץ כזה, כמו קודם."
},
"ja": {
"Did this assembly open the wrong way up?": "このアセンブリは逆向きに開かれましたか?",
"Did this part open the wrong way up?": "このパーツは逆向きに開かれましたか?",
"Stand this assembly up?": "このアセンブリを正立させますか?",
"prefs.stand_up_unknown": "不明なプログラムのファイル",
"prefs.stand_up_unknown.ask": "ダイアログで確認",
"prefs.stand_up_unknown.note": "メモを表示",
"prefs.stand_up_unknown.off": "確認しない",
"prefs.stand_up_unknown_note": "ファイルのヘッダーに Y 上向きで保存することが知られているプログラム名がない場合の確認方法です。メモはファイルが横倒しに見える場合にのみ表示されます。「ダイアログで確認」は従来どおり、このようなファイルすべてについて確認します。"
},
"vi": {
"Did this assembly open the wrong way up?": "Cụm lắp ráp này có bị mở sai hướng không?",
"Did this part open the wrong way up?": "Chi tiết này có bị mở sai hướng không?",
"Stand this assembly up?": "Dựng đứng cụm lắp ráp này lên?",
"prefs.stand_up_unknown": "Với tệp từ chương trình không xác định",
"prefs.stand_up_unknown.ask": "Hỏi trong hộp thoại",
"prefs.stand_up_unknown.note": "Hiện ghi chú",
"prefs.stand_up_unknown.off": "Không gợi ý",
"prefs.stand_up_unknown_note": "Cách gợi ý khi phần đầu tệp không nêu chương trình nào được biết là lưu với trục Y hướng lên. Ghi chú chỉ hiện khi tệp có vẻ đang nằm ngửa; “Hỏi trong hộp thoại” sẽ hỏi với mọi tệp như vậy, như trước đây."
},
"zh": {
"Did this assembly open the wrong way up?": "此装配是否以错误的方向打开?",
"Did this part open the wrong way up?": "此零件是否以错误的方向打开?",
"Stand this assembly up?": "立起此装配?",
"prefs.stand_up_unknown": "来自未知程序的文件",
"prefs.stand_up_unknown.ask": "在对话框中询问",
"prefs.stand_up_unknown.note": "显示提示",
"prefs.stand_up_unknown.off": "不提供",
"prefs.stand_up_unknown_note": "当文件头未注明已知以 Y 轴向上保存的程序时,如何提供立起选项。仅当文件看起来平躺时才显示提示;“在对话框中询问”会像以前一样对每个此类文件进行询问。"
}
}
+3
View File
@@ -389,6 +389,9 @@ fn a_control_import_passes_up_and_names_on() {
// The reply, the part's height and whether the offer is up, for an import by this window.
let import = |params: serde_json::Value| {
let mut w = Win::new();
// This test is about the caller's `up`, not the note's lying-on-its-back guess (#7717): every
// file from another program gets the offer, as before.
w.app.preferences.stand_up_unknown = crate::prefs::StandUpUnknown::Ask;
let (tx, rx) = std::sync::mpsc::channel();
w.app.control_rx = Some(rx);
let (req, reply_rx) = crate::control::ControlRequest::new("engine.execute", json!({"command": "file.insert_step", "params": params.clone()}));
+11
View File
@@ -576,6 +576,14 @@ pub struct SolveApp {
pub stand_up_occurrence: Option<u64>,
/// The file's header names an exporter that saves Y up (SolidWorks): the offer says so.
pub stand_up_reason: bool,
/// The file brought more than one body or a component tree: the offer says "assembly".
pub stand_up_assembly: bool,
/// The offer is the small note over the view, not the dialog (a file from a program not known
/// to save Y up, Preferences › Design, #7717).
pub stand_up_note: bool,
/// When the note was first drawn (the window's clock), or since the pointer was last on it; it
/// goes after `stand_up::NOTE_SECONDS`.
pub stand_up_note_since: Option<f64>,
/// The anti-aliasing sample counts the scene colour/depth formats support (empty without a GPU).
pub msaa_supported: Vec<u32>,
/// The startup check selected 1x; Graphics explains the workaround.
@@ -745,6 +753,9 @@ impl SolveApp {
stand_up: None,
stand_up_occurrence: None,
stand_up_reason: false,
stand_up_assembly: false,
stand_up_note: false,
stand_up_note_since: None,
msaa_supported: Vec::new(),
msaa_compatibility: false,
graphics_fallback: None,
+58 -5
View File
@@ -562,6 +562,48 @@ fn same_orientation(a: Camera, b: Camera) -> bool {
ar.dot(br) > near && au.dot(bu) > near && ab.dot(bb) > near
}
/// How the offer to stand a file up is made when its header names no program known to save Y up
/// (Preferences: "For files from unknown programs", #7717). A file from SolidWorks is asked in the
/// dialog (only the note when it already stands on Z, unless this is Ask); SolidCraft's own files
/// are never offered.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StandUpUnknown {
/// The "Stand this part up?" dialog for every file from another program, without looking at
/// how it rests, as before #7717 (a SolidWorks file too).
Ask,
/// No offer: the context menu's Turn Up Axis still stands the file up.
Off,
/// A small note over the view, only when the file seems to lie on its back, that goes by
/// itself and never blocks input (the default). A saved value this version doesn't know reads
/// as this.
#[default]
#[serde(other)]
Note,
}
impl StandUpUnknown {
pub const ALL: [Self; 3] = [Self::Ask, Self::Note, Self::Off];
/// The choice as `ui.prefs` and the saved preferences spell it.
pub fn id(self) -> &'static str {
match self {
Self::Ask => "ask",
Self::Note => "note",
Self::Off => "off",
}
}
/// The message id of the choice's label.
pub fn label_id(self) -> &'static str {
match self {
Self::Ask => "prefs.stand_up_unknown.ask",
Self::Note => "prefs.stand_up_unknown.note",
Self::Off => "prefs.stand_up_unknown.off",
}
}
}
/// Which program reads the 3D mouse on Linux when both spacenavd and the device itself (hidraw)
/// are there (Preferences: "3D mouse driver"). Read by the app's reader, not by this crate.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
@@ -956,6 +998,9 @@ preference_settings! {
up_axis: String = "z".into(), PAGE_DESIGN;
/// After a STEP or IGES file opens, offer to stand a Y-up part up (`stand_up`).
offer_stand_up: bool = true, PAGE_DESIGN => check("Offer to stand up Y-up files", "After a STEP or IGES file opens with Z up, offer a quarter turn about X");
/// How the offer is made for a file whose header names no program known to save Y up: a note
/// over the view (the default), the dialog, or nothing (#7717).
stand_up_unknown: StandUpUnknown = StandUpUnknown::default(), PAGE_DESIGN;
/// Extrude: with a profile picked, a face, vertex or parallel plane picked off its plane
/// switches the extent to To Object (off: picks only add profiles, as before).
extrude_auto_to_object: bool = false, PAGE_DESIGN => check("Extrude to a picked target", "In Extrude, with a profile picked, picking a face, vertex or parallel plane off its plane switches the extent to To Object");
@@ -2575,14 +2620,14 @@ fn button_job_picker(
}
/// The control channel's `ui.prefs`: `open` (a page name) opens the dialog there, `button`
/// presses OK, Cancel, Apply or Restore Defaults, `stand_up: true` answers the stand-up offer
/// (`false` leaves the file as it is, like "Leave it"), `theme_import` (a theme file's JSON or
/// presses OK, Cancel, Apply or Restore Defaults, `stand_up: true` answers the stand-up offer,
/// dialog or note (`false` leaves the file as it is, like "Leave it"), `theme_import` (a theme file's JSON or
/// text) adds a theme and turns it on, `theme_remove` (an id) removes an imported one and
/// `theme_export: true` returns the theme on now as `theme_file`, `theme_follow` (a path, or
/// `""` to stop) follows a theme file on the desktop (#7573); any other keys set preferences.
/// `open: "Interface/Navigation bar"` opens Interface and scrolls to its bar editor.
/// Returns them all, the open page, the offer, the theme ids and the followed file
/// (`theme_followed`, `theme_follow_error`).
/// Returns them all, the open page, the offer (and whether it is the note), the theme ids and the
/// followed file (`theme_followed`, `theme_follow_error`).
pub fn control(app: &mut SolveApp, p: &serde_json::Value) -> Result<serde_json::Value, String> {
let mut rest = p.as_object().cloned().unwrap_or_default();
if let Some(page) = rest.remove("open") {
@@ -2629,6 +2674,7 @@ pub fn control(app: &mut SolveApp, p: &serde_json::Value) -> Result<serde_json::
if let Some(o) = out.as_object_mut() {
o.insert("dialog".into(), json!(app.prefs_window.open.then(|| PAGES.get(app.prefs_window.section).copied().unwrap_or_default())));
o.insert("stand_up_offer".into(), json!(app.stand_up));
o.insert("stand_up_note".into(), json!(app.stand_up.is_some() && app.stand_up_note));
o.insert("dark".into(), json!(app.ui.dark));
o.insert("viewport_dark".into(), json!(app.viewport_dark()));
o.insert("theme_ids".into(), json!(theme_choices(app).into_iter().map(|(id, _)| id).collect::<Vec<_>>()));
@@ -2905,6 +2951,11 @@ pub fn set(app: &mut SolveApp, p: &serde_json::Value) -> Result<serde_json::Valu
if let Some(value) = p.get("navigation_bar") {
crate::navigation_bar::validate(value)?;
}
if let Some(v) = p.get("stand_up_unknown")
&& !StandUpUnknown::ALL.iter().any(|c| v.as_str() == Some(c.id()))
{
return Err("`stand_up_unknown` must be ask, note or off".into());
}
let new: Prefs = migrate(serde_json::from_value(cur).map_err(|e| e.to_string())?);
if !UNITS.contains(&new.default_units.as_str()) {
return Err(format!("units must be one of {}", UNITS.join(", ")));
@@ -5878,9 +5929,11 @@ mod tests {
let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default());
app.open_path(&path);
assert!(app.stand_up.is_none(), "SolidCraft's own exports already have Z up");
// Another originating system keeps the offer.
// Another originating system is offered (asked in the dialog, without looking at how the
// flat box rests).
let text = std::fs::read_to_string(&path).unwrap();
std::fs::write(&path, text.replace("'SolidCraft','SolidCraft'", "'SolidCraft','Example CAD'")).unwrap();
app.preferences.stand_up_unknown = StandUpUnknown::Ask;
app.open_path(&path);
let offered = app.stand_up.clone().unwrap_or_default();
assert_eq!(offered.len(), 1, "the file's body is offered");
+22
View File
@@ -54,6 +54,28 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
);
setting::offer_stand_up(app, ui);
ui_kit::text(ui, app.tr("prefs.stand_up_note"), ui_kit::Text::Hint("stand_up"));
// How a file from a program not known to save Y up is offered (#7717).
let offered = app.preferences.offer_stand_up;
ui_kit::settings_block_hint(
ui,
app.tr("prefs.stand_up_unknown"),
app.tr("prefs.stand_up_unknown_note"),
t.space_24 * 8.0 + t.space_8,
|ui| {
ui.add_enabled_ui(offered, |ui| {
let unknown = &mut app.preferences.stand_up_unknown;
ui_kit::settings_control_width(ui, t.space_24 * 7.0 + t.space_12, |ui| {
ui_kit::dropdown_menu(ui, "pref_stand_up_unknown", crate::i18n::tr(unknown.label_id()), |ui| {
for choice in StandUpUnknown::ALL {
if ui_kit::list_picker(ui, choice.label_id(), crate::i18n::tr(choice.label_id()), *unknown == choice).clicked() {
*unknown = choice;
}
}
});
});
});
},
);
setting::extrude_auto_to_object(app, ui);
setting::hide_origin(app, ui);
ui_kit::text(ui, app.tr("ui.hide_origin_note"), ui_kit::Text::Hint("hide_origin"));
+224 -9
View File
@@ -3,15 +3,149 @@
//! offers to stand it up: a quarter turn about X (Y → Z) of the component the file came in as
//! (#1386), so an assembly's parts and instances turn together, in one step that can be undone.
//! Preferences › Design › "Offer to stand up Y-up files" turns the offer off; with Y up as the
//! default orientation it isn't needed. The file is never turned without asking: a header that
//! names an exporter known to save Y up (SolidWorks) only adds a reason line to the offer, since
//! such a file may have been saved Z up. The context menu's "Turn Up Axis" fixes it any time.
//! default orientation it isn't needed. The file is never turned without asking.
//!
//! How it asks depends on the program the header names and on how the bodies rest (#7717):
//! `estimate` weighs their flat area facing down Z against their flat area across Y. A file from
//! an exporter known to save Y up (SolidWorks) gets the "Stand this part up?" dialog with a
//! reason line, or only the note below when its bodies clearly stand on Z already. A file from
//! any other program is often upright already, so by default it gets a small note over the view
//! ("Did this part open the wrong way up?"), which goes by itself after `NOTE_SECONDS` and never
//! blocks input, and only when its bodies seem to lie on their back; Preferences › Design ›
//! "For files from unknown programs" picks the dialog (always, as before) or no offer instead. SolidCraft's own files are never offered.
//! Either says "assembly" when the file brought more than one body or a component tree. The
//! context menu's "Turn Up Axis" fixes it any time.
use serde_json::json;
use crate::SolveApp;
use crate::prefs::StandUpUnknown;
use crate::ui_kit;
/// How long the note stays up when nobody is pointing at it, in seconds.
pub const NOTE_SECONDS: f64 = 10.0;
// Which way a just-opened file seems to stand (`upright`). A part rests on its flat faces: the
// planar area facing down Z (a Z-up file's base) is weighed against the larger of the planar
// areas facing down Y and up Y (a Y-up file's base, or its top when it was saved upside down),
// from the bodies' display triangles.
/// A flat face counts toward a direction when its normal is within this many degrees of it.
pub const FACING_DEGREES: f64 = 10.0;
/// A face counts as flat when every triangle's normal is within this many degrees of its first.
pub const PLANAR_DEGREES: f64 = 1.0;
/// One axis wins when its flat area (or, as the tie-breaker, the box's thinness) is at least this
/// many times the other's; anything closer is unclear.
pub const DOMINANCE: f64 = 1.5;
/// At most this many bodies are looked at, so a huge assembly isn't meshed all at once here.
pub const MAX_BODIES: usize = 64;
/// At most this many triangles are looked at in all; a larger mesh is sampled evenly.
pub const MAX_TRIANGLES: usize = 200_000;
/// Which axis a file's bodies seem to have up.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Upright {
/// They rest on faces across Y: the file has Y up and lies on its back here.
Y,
/// They rest on faces facing down Z: already the right way up.
Z,
/// Nothing says either clearly.
Unclear,
}
/// The flat area of `mesh` facing down Z, facing down Y and facing up Y, looking at no more than
/// `budget` triangles.
pub fn flat_areas(mesh: &solidcraft_engine::geom::Mesh, budget: usize) -> [f64; 3] {
use solidcraft_engine::geom::Vec3;
struct Face {
first: Vec3,
area: f64,
flat: bool,
}
let count = mesh.triangles.len();
if count == 0 || budget == 0 {
return [0.0; 3];
}
let stride = count.div_ceil(budget).max(1);
let planar = PLANAR_DEGREES.to_radians().cos();
let mut faces: std::collections::HashMap<u32, Face> = std::collections::HashMap::new();
for (i, tri) in mesh.triangles.iter().enumerate().step_by(stride) {
let corner = |k: usize| tri.get(k).and_then(|&v| mesh.positions.get(v as usize)).copied();
let (Some(a), Some(b), Some(c)) = (corner(0), corner(1), corner(2)) else { continue };
let u = Vec3::new(b.x - a.x, b.y - a.y, b.z - a.z);
let v = Vec3::new(c.x - a.x, c.y - a.y, c.z - a.z);
let n = u.cross(v);
let len = n.len();
if !len.is_finite() || len <= 0.0 {
continue;
}
let unit = Vec3::new(n.x / len, n.y / len, n.z / len);
let id = mesh.tri_face.get(i).copied().unwrap_or(u32::MAX);
let face = faces.entry(id).or_insert(Face { first: unit, area: 0.0, flat: true });
face.area += len * 0.5;
face.flat &= face.first.dot(unit) >= planar;
}
let facing = FACING_DEGREES.to_radians().cos();
let mut areas = [0.0; 3];
for face in faces.values().filter(|f| f.flat && f.area.is_finite()) {
let n = face.first;
for (i, d) in [-n.z, -n.y, n.y].into_iter().enumerate() {
if d >= facing
&& let Some(a) = areas.get_mut(i)
{
*a += face.area;
}
}
}
areas
}
/// Which axis is up, from the flat area facing down Z and the larger of those facing down and up
/// Y (`flat_areas`) and, when they are close, the box's size along X, Y and Z: a part lies on its
/// broad side, so the thin axis is up.
pub fn upright(z_down: f64, y_either: f64, size: [f64; 3]) -> Upright {
if !(z_down.is_finite() && y_either.is_finite()) {
return Upright::Unclear;
}
if y_either > 0.0 && y_either >= DOMINANCE * z_down {
return Upright::Y;
}
if z_down > 0.0 && z_down >= DOMINANCE * y_either {
return Upright::Z;
}
let [x, y, z] = size;
if [x, y, z].iter().all(|v| v.is_finite() && *v >= 0.0) {
if y * DOMINANCE <= z && y <= x {
return Upright::Y;
}
if z * DOMINANCE <= y && z <= x {
return Upright::Z;
}
}
Upright::Unclear
}
/// Which axis the bodies named `bodies` in the current design seem to have up. Looks at most
/// `MAX_BODIES` bodies and `MAX_TRIANGLES` triangles; a body that can't be meshed adds nothing.
pub fn estimate(app: &SolveApp, bodies: &[String]) -> Upright {
let world = app.session.world_state();
let mut areas = [0.0_f64; 3];
let mut bounds = solidcraft_engine::geom::Aabb3::EMPTY;
let mut budget = MAX_TRIANGLES;
for body in world.bodies.iter().filter(|b| bodies.contains(&b.name)).take(MAX_BODIES) {
let mesh = body.mesh();
for (sum, area) in areas.iter_mut().zip(flat_areas(&mesh, budget)) {
*sum += area;
}
budget = budget.saturating_sub(mesh.triangles.len().min(budget));
let b = mesh.bounds();
bounds.extend([b.min, b.max]);
}
let size = [bounds.max.x - bounds.min.x, bounds.max.y - bounds.min.y, bounds.max.z - bounds.min.z];
let [z_down, y_down, y_up] = areas;
upright(z_down, y_down.max(y_up), size)
}
/// The bodies a just-opened file brought (`before`: body names before it opened, none for a
/// new design), and the import's component placement from the command's `result`: offer to
/// stand them up.
@@ -33,8 +167,24 @@ pub fn offer(app: &mut SolveApp, path: &str, before: &[String], result: Option<&
if !app.preferences.offer_stand_up {
return;
}
// A header naming a Y-up exporter adds the reason; the file is never turned without asking.
app.stand_up_reason = text("exporter_up") == Some("y");
// A header naming a Y-up exporter asks in the dialog, with the reason, unless the bodies
// clearly stand on Z already (it may have been saved Z up): then only the note. The file is
// never turned without asking. Any other program gets what Preferences › Design says: the
// note unless the bodies clearly stand on Z (an unclear shape still gets it, so a Y-up file
// is never left without an offer), the dialog always, or nothing. Ask is the behaviour from
// before #7717 for every file: the dialog, without looking.
let known_y_up = text("exporter_up") == Some("y");
let note = match app.preferences.stand_up_unknown {
StandUpUnknown::Ask => false,
_ if known_y_up => estimate(app, &bodies) == Upright::Z,
StandUpUnknown::Note if estimate(app, &bodies) != Upright::Z => true,
StandUpUnknown::Note | StandUpUnknown::Off => return,
};
let subcomponents = result.and_then(|r| r.get("subcomponents")).and_then(serde_json::Value::as_u64).unwrap_or(0);
app.stand_up_reason = known_y_up;
app.stand_up_assembly = bodies.len() > 1 || subcomponents > 0;
app.stand_up_note = note;
app.stand_up_note_since = None;
app.stand_up = Some(bodies);
app.stand_up_occurrence = occurrence;
}
@@ -42,6 +192,9 @@ pub fn offer(app: &mut SolveApp, path: &str, before: &[String], result: Option<&
/// Turn the offered bodies a quarter turn about X (Y up becomes Z up).
pub fn stand_up(app: &mut SolveApp) -> Result<(), String> {
app.stand_up_reason = false;
app.stand_up_assembly = false;
app.stand_up_note = false;
app.stand_up_note_since = None;
let Some(bodies) = app.stand_up.take() else { return Err("no file is waiting to be stood up".into()) };
match app.stand_up_occurrence.take() {
// The import's component turns about its parent's origin, contents and all, even when it
@@ -56,19 +209,81 @@ pub fn stand_up(app: &mut SolveApp) -> Result<(), String> {
Ok(())
}
/// Dismiss the offer and keep the file as it opened ("Leave it"); the preference stays on.
/// Dismiss the offer and keep the file as it opened ("Leave it", or the note's Close); the
/// preference stays on.
pub fn leave(app: &mut SolveApp) {
app.stand_up = None;
app.stand_up_reason = false;
app.stand_up_occurrence = None;
app.stand_up_assembly = false;
app.stand_up_note = false;
app.stand_up_note_since = None;
}
/// The offer, under the toolbar.
/// The offer is waiting as the note (drawn by the shared toast). No side effects.
pub(crate) fn note_pending(app: &SolveApp) -> bool {
app.stand_up_note && app.stand_up.is_some()
}
/// The note due this frame, as its text, for the shared toast (`viewport::transient_messages`) to
/// draw with the buttons `note_labels`. Its clock starts the first frame it is drawn; after
/// `NOTE_SECONDS` without the pointer on it (`note_keep`) it goes, leaving the file as it opened.
pub(crate) fn note_due(app: &mut SolveApp, ctx: &egui::Context) -> Option<String> {
if !note_pending(app) {
return None;
}
let now = ctx.input(|i| i.time);
let since = *app.stand_up_note_since.get_or_insert(now);
let shown = now - since;
if !shown.is_finite() || shown >= NOTE_SECONDS {
leave(app);
return None;
}
let text = if app.stand_up_assembly { "Did this assembly open the wrong way up?" } else { "Did this part open the wrong way up?" };
Some(crate::i18n::tr_label(text).to_string())
}
/// The handles of the note's buttons, in order: the quarter turn, turning the offer off, then the
/// dismissal. They are published for scripts; `stand_up:stand` and `stand_up:never` are the
/// dialog's handles too.
pub const NOTE_HANDLES: [&str; 3] = ["stand_up:stand", "stand_up:never", "stand_up:dismiss"];
/// The note's button labels, in the order of `NOTE_HANDLES`.
pub(crate) fn note_labels() -> [String; 3] {
[crate::i18n::tr_label("Stand it up").to_string(), crate::i18n::tr_label("Don't ask again").to_string(), crate::i18n::tr("ui.close").to_string()]
}
/// The note was drawn at `rect`: a pointer on it keeps it from going.
pub(crate) fn note_keep(app: &mut SolveApp, ctx: &egui::Context, rect: egui::Rect) {
if ctx.input(|i| i.pointer.hover_pos()).is_some_and(|pos| rect.contains(pos)) {
app.stand_up_note_since = Some(ctx.input(|i| i.time));
}
}
/// The note's button `index` (of `NOTE_HANDLES`) was clicked.
pub(crate) fn note_act(app: &mut SolveApp, index: usize) {
match index {
0 => {
if let Err(e) = stand_up(app) {
app.set_status(e, true);
}
}
// As the dialog's Don't ask again: Preferences › Design turns the offer back on.
1 => {
leave(app);
app.preferences.offer_stand_up = false;
}
_ => leave(app),
}
}
/// The offer, under the toolbar, unless it is the note.
pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
if app.stand_up.is_none() {
if app.stand_up.is_none() || app.stand_up_note {
return;
}
let (closed, action) = ui_kit::Window::new(egui::Id::new("sc_stand_up"), "move", crate::i18n::tr_label("Stand this part up?"))
let title = if app.stand_up_assembly { "Stand this assembly up?" } else { "Stand this part up?" };
let (closed, action) = ui_kit::Window::new(egui::Id::new("sc_stand_up"), "move", crate::i18n::tr_label(title))
.anchor(egui::Align2::CENTER_TOP, egui::vec2(0.0, 140.0))
.actions("Stand it up", "Leave it", Some("Don't ask again"))
.show(ctx, true, |ui| {
+37 -7
View File
@@ -4661,8 +4661,8 @@ fn agent_chip(app: &mut SolveApp, ui: &egui::Ui, view: Rect, taken: &[Rect]) ->
/// How long a status message stays in the view (milliseconds).
const STATUS_TOAST_MS: f64 = 6000.0;
/// A single visual pattern for ongoing work, the existing six-second status and the 3D mouse
/// calibration offer, stacked from the bottom of the free view. Returns the toasts' rects.
/// A single visual pattern for ongoing work, the existing six-second status, the 3D mouse
/// calibration offer and the stand-up note, stacked from the bottom of the free view. Returns the toasts' rects.
fn transient_messages(app: &mut SolveApp, ui: &egui::Ui, viewport: Rect) -> Vec<Rect> {
// Nothing to show or time: an idle window skips the layout. The offer is checked too, as its clock
// runs from the frames `due` sees.
@@ -4670,6 +4670,7 @@ fn transient_messages(app: &mut SolveApp, ui: &egui::Ui, viewport: Rect) -> Vec<
&& app.computing_since().is_none()
&& app.agent_computing().is_none()
&& crate::space_mouse_offer::offerable(app).is_none()
&& !crate::stand_up::note_pending(app)
{
return Vec::new();
}
@@ -4681,11 +4682,32 @@ fn transient_messages(app: &mut SolveApp, ui: &egui::Ui, viewport: Rect) -> Vec<
}
let view = crate::shell::content_rect(app, viewport);
let mut free = crate::viewport_layout::free_rect(view, &obstacles).shrink(t.space_8);
// The note offering to stand up a file just opened from a program not known to save Y up
// (#7717): the shared toast with its buttons, which go by themselves and never block input.
if let Some(text) = crate::stand_up::note_due(app, ui.ctx()) {
let labels = crate::stand_up::note_labels();
let actions =
[(labels[0].as_str(), ToastKind::Primary), (labels[1].as_str(), ToastKind::Secondary), (labels[2].as_str(), ToastKind::Dismiss)];
if let Some((r, clicked, buttons)) = paint_toast_with(ui, free, text, ToastLead::Dot(false), &actions) {
crate::scenario::publish_rect("toast:stand_up", r);
for (handle, button) in crate::stand_up::NOTE_HANDLES.iter().zip(&buttons) {
crate::scenario::publish_handle(handle, button.center());
}
obstacles.push(r);
free.max.y = r.top() - t.space_8;
shown.push(r);
crate::stand_up::note_keep(app, ui.ctx(), r);
if let Some(index) = clicked {
crate::stand_up::note_act(app, index);
}
}
ui.ctx().request_repaint_after(std::time::Duration::from_millis(500));
}
// The 3D mouse calibration offer: text and actions from its module, drawn by the shared toast.
if let Some(offer) = crate::space_mouse_offer::due(app, ui.ctx()) {
let labels: Vec<String> = offer.actions.iter().map(|action| crate::i18n::tr(action.label()).to_string()).collect();
let labels: Vec<(&str, ToastKind)> = labels.iter().map(String::as_str).zip(offer.actions.iter().map(|action| action.kind())).collect();
if let Some((r, clicked)) = paint_toast_with(ui, free, crate::i18n::tr("ui.3d_mouse_offer").to_string(), ToastLead::Dot(false), &labels) {
if let Some((r, clicked, _)) = paint_toast_with(ui, free, crate::i18n::tr("ui.3d_mouse_offer").to_string(), ToastLead::Dot(false), &labels) {
crate::scenario::publish_rect("toast:space_mouse_offer", r);
obstacles.push(r);
free.max.y = r.top() - t.space_8;
@@ -4794,15 +4816,21 @@ enum ToastLead {
fn paint_toast(ui: &egui::Ui, free: Rect, text: String, error: bool, computing: bool) -> Option<Rect> {
let lead = if computing { ToastLead::Spinner } else { ToastLead::Dot(error) };
paint_toast_with(ui, free, text, lead, &[]).map(|(rect, _)| rect)
paint_toast_with(ui, free, text, lead, &[]).map(|(rect, _, _)| rect)
}
/// The one toast painter: its text in a card at the bottom centre of `free`, led by a dot or a
/// spinner, and, below the text, a wrapping row of buttons (`actions`, kit buttons). Returns the
/// card's rect and which button was clicked, if any. With no actions the card is exactly the status
/// card's rect, which button was clicked, if any, and where each button is (for handles). With no actions the card is exactly the status
/// and computing toast it always was. The buttons are not live while an issue report holds CAD
/// input; none is laid outside the card, whose width is bounded by `free`.
fn paint_toast_with(ui: &egui::Ui, free: Rect, text: String, lead: ToastLead, actions: &[(&str, ToastKind)]) -> Option<(Rect, Option<usize>)> {
fn paint_toast_with(
ui: &egui::Ui,
free: Rect,
text: String,
lead: ToastLead,
actions: &[(&str, ToastKind)],
) -> Option<(Rect, Option<usize>, Vec<Rect>)> {
if !free.is_finite() || !free.is_positive() || free.width() <= 40.0 {
return None;
}
@@ -4844,6 +4872,7 @@ fn paint_toast_with(ui: &egui::Ui, free: Rect, text: String, lead: ToastLead, ac
let text_top = r.min + vec2(28.0, 8.0);
painter.galley(text_top, galley.clone(), t.text);
let mut clicked = None;
let mut buttons = Vec::with_capacity(actions.len());
let origin = text_top + vec2(0.0, galley.size().y + gap);
for (index, ((label, kind), spot)) in actions.iter().zip(&spots).enumerate() {
let at = spot.translate(origin.to_vec2());
@@ -4864,8 +4893,9 @@ fn paint_toast_with(ui: &egui::Ui, free: Rect, text: String, lead: ToastLead, ac
if response.clicked() {
clicked = Some(index);
}
buttons.push(response.rect);
}
Some((r, clicked))
Some((r, clicked, buttons))
}
/// A click without a command: select the candidate (replacing the selection, or adding /
@@ -408,7 +408,7 @@ fn toast_buttons_wrap_inside_the_card_and_are_dead_behind_an_issue_report() {
seen
};
run(vec![]);
let (card, _) = run(vec![]).unwrap_or_else(|| panic!("width {width}: no card"));
let (card, _, _) = run(vec![]).unwrap_or_else(|| panic!("width {width}: no card"));
assert!(free.contains_rect(card), "width {width}: {card:?}");
let mut hits = Vec::new();
for step_x in 1..12 {
@@ -427,7 +427,7 @@ fn toast_buttons_wrap_inside_the_card_and_are_dead_behind_an_issue_report() {
pressed: false,
modifiers: Default::default(),
}]);
if let Some((_, Some(index))) = clicked {
if let Some((_, Some(index), _)) = clicked {
hits.push(index);
}
}
+209 -8
View File
@@ -1,22 +1,48 @@
//! The "Stand this part up?" offer can be answered by handle (#1905): its buttons are published
//! as `stand_up:stand`, `stand_up:leave` and `stand_up:never`, it stays up through a camera move
//! and a command until answered, and `ui.prefs {"stand_up": false}` leaves the file as it is.
//! A file from a program not known to save Y up gets a small note instead by default (#7717),
//! with `stand_up:stand`, `stand_up:never` and `stand_up:dismiss`; Preferences picks the dialog or nothing.
use serde_json::json;
use solidcraft_ui_egui::prefs::StandUpUnknown;
use solidcraft_ui_egui::scenario::Harness;
/// A harness with a 10 × 40 × 5 mm box (Y up) just opened from STEP: the offer is up.
/// A harness with a 10 × 40 × 5 mm box (Y up) just opened from STEP, from a program not known to
/// save Y up, with Preferences set to ask in the dialog: the dialog is up.
fn opened() -> Harness {
let h = opened_from("'Example CAD','Example CAD'", |_| {});
let h = opened_from("'Example CAD','Example CAD'", |h| h.app.preferences.stand_up_unknown = StandUpUnknown::Ask);
assert_eq!(h.app.stand_up.as_ref().map(Vec::len), Some(1), "the file's body is offered");
assert!(!h.app.stand_up_note, "in the dialog");
h
}
/// The same box, its FILE_NAME naming `programs` (preprocessor, originating system), opened
/// after `prepare` has set the app up.
fn opened_from(programs: &str, prepare: impl FnOnce(&mut Harness)) -> Harness {
opened_boxes([10.0, 40.0, 5.0], &[[0.0, 0.0, 0.0]], programs, prepare)
}
/// A 40 × 40 × 10 mm plate resting on its broad face: the right way up (Z up).
const UPRIGHT: [f64; 3] = [40.0, 40.0, 10.0];
/// The same plate as a Y-up program saves it: resting on its broad face across Y, so here it
/// stands on its edge, 40 mm tall (lying on its back); stood up it is 10 mm tall.
const ON_ITS_BACK: [f64; 3] = [40.0, 10.0, 40.0];
/// One box of `size` (X, Y, Z), exported with FILE_NAME naming `programs`, opened after
/// `prepare`.
fn opened_box(size: [f64; 3], programs: &str, prepare: impl FnOnce(&mut Harness)) -> Harness {
opened_boxes(size, &[[0.0, 0.0, 0.0]], programs, prepare)
}
/// Boxes of `size` (X, Y, Z) with their corners at `corners`, each its own body, exported to STEP
/// with FILE_NAME naming `programs`, opened after `prepare` has set the app up.
fn opened_boxes(size: [f64; 3], corners: &[[f64; 3]], programs: &str, prepare: impl FnOnce(&mut Harness)) -> Harness {
let mut src = Harness::new();
let path = src.dir.join("tall_in_y.step").to_string_lossy().into_owned();
src.app.run("solid.box", json!({"length": 10, "width": 40, "height": 5})).unwrap();
for corner in corners {
let [length, width, height] = size;
src.app.run("solid.box", json!({"length": length, "width": width, "height": height, "corner": corner, "operation": "new_body"})).unwrap();
}
src.app.run("file.export", json!({"path": path})).unwrap();
// Another program's file: SolidCraft's own exports already have Z up (#5150).
let text = std::fs::read_to_string(&path).unwrap();
@@ -82,24 +108,25 @@ fn prefs_stand_up_false_leaves_the_offer() {
#[test]
fn a_solidworks_header_shows_the_offer_and_does_not_turn_the_file() {
let h = opened_from("'SolidWorks 2021','SolidWorks 2021'", |_| {});
let h = opened_box(ON_ITS_BACK, "'SolidWorks 2021','SolidWorks 2021'", |_| {});
assert_eq!(h.app.stand_up.as_ref().map(Vec::len), Some(1), "offered");
assert!(h.app.stand_up_reason, "with the reason line");
assert!(!h.app.stand_up_note, "in the dialog");
assert!(!h.app.status_undo, "nothing was turned");
assert!((height(&h) - 5.0).abs() < 1e-6, "not turned: {}", height(&h));
assert!((height(&h) - 40.0).abs() < 1e-6, "not turned: {}", height(&h));
// An unknown exporter gets the offer without the reason.
assert!(!opened().app.stand_up_reason);
}
#[test]
fn stand_it_up_from_a_solidworks_offer_turns_once_and_undo_restores() {
let mut h = opened_from("'SolidWorks 2021','SolidWorks 2021'", |_| {});
let mut h = opened_box(ON_ITS_BACK, "'SolidWorks 2021','SolidWorks 2021'", |_| {});
h.run(&json!([{"click": {"handle": "stand_up:stand"}}])).unwrap();
h.frames(3);
assert!((height(&h) - 40.0).abs() < 1e-6, "stood up: {}", height(&h));
assert!((height(&h) - 10.0).abs() < 1e-6, "stood up: {}", height(&h));
assert!(!h.app.stand_up_reason);
h.app.run("edit.undo", json!({})).unwrap();
assert!((height(&h) - 5.0).abs() < 1e-6, "undone: {}", height(&h));
assert!((height(&h) - 40.0).abs() < 1e-6, "undone: {}", height(&h));
}
#[test]
@@ -206,3 +233,177 @@ fn a_sketch_on_the_stood_up_components_own_xy_is_turned_once() {
assert!((back.y + 1.0).abs() < 1e-3, "looks at it from -Y: {back:?}");
assert!(near(b.min, [200.0, -15.0, 0.0]) && near(b.max, [220.0, 0.0, 10.0]), "{b:?}");
}
/// Whether `text` was painted in the last frame (the note is painted, not a widget).
fn painted(h: &Harness, text: &str) -> bool {
fn has(shape: &egui::Shape, text: &str) -> bool {
match shape {
egui::Shape::Text(t) => t.galley.job.text == text,
egui::Shape::Vec(shapes) => shapes.iter().any(|s| has(s, text)),
_ => false,
}
}
h.shapes.iter().any(|c| has(&c.shape, text))
}
const UNKNOWN: &str = "'Example CAD','Example CAD'";
const SOLIDWORKS: &str = "'SolidWorks 2021','SolidWorks 2021'";
#[test]
fn an_unknown_exporter_lying_on_its_back_gets_the_note_not_the_dialog() {
let mut h = opened_box(ON_ITS_BACK, UNKNOWN, |_| {});
assert_eq!(h.app.stand_up.as_ref().map(Vec::len), Some(1), "offered");
assert!(h.app.stand_up_note, "as the note");
assert!(painted(&h, "Did this part open the wrong way up?"));
assert!(h.widget("Stand this part up?").is_none(), "no dialog");
for name in ["stand_up:stand", "stand_up:never", "stand_up:dismiss"] {
assert!(h.at(&json!({"handle": name})).is_ok(), "{name} is published");
}
assert!(h.at(&json!({"handle": "stand_up:leave"})).is_err(), "the dialog's buttons are not");
// It doesn't hold anything up: the view and commands work while it shows.
h.run(&json!([{"camera": {"yaw": 0.6, "pitch": 0.4}}, {"call": "engine.execute", "params": {"command": "solid.box", "params": {"length": 1, "width": 1, "height": 1, "corner": [100, 0, 0]}}}]))
.unwrap();
h.frames(3);
assert!(h.app.stand_up.is_some(), "still offered");
assert!((height(&h) - 40.0).abs() < 1e-6, "not turned: {}", height(&h));
let r = h.call("ui.prefs", json!({}));
assert_eq!(r["result"]["stand_up_note"], json!(true), "{r}");
assert_eq!(r["result"]["stand_up_unknown"], json!("note"), "{r}");
}
#[test]
fn an_upright_file_from_an_unknown_exporter_gets_nothing() {
for (size, what) in [(UPRIGHT, "a plate on its face"), ([10.0, 40.0, 5.0], "a slab on its face")] {
let h = opened_box(size, UNKNOWN, |_| {});
assert!(h.app.stand_up.is_none(), "{what}: no offer");
assert!(!painted(&h, "Did this part open the wrong way up?"), "{what}");
}
// Nor an upright assembly of them.
let h = opened_boxes(UPRIGHT, &[[0.0, 0.0, 0.0], [60.0, 0.0, 0.0]], UNKNOWN, |_| {});
assert!(h.app.stand_up.is_none(), "upright assembly: no offer");
}
#[test]
fn an_unclear_file_from_an_unknown_exporter_still_gets_the_note() {
// A cube says nothing about which way is up; a Y-up file is never left without an offer.
let h = opened_box([40.0, 40.0, 40.0], UNKNOWN, |_| {});
assert!(h.app.stand_up.is_some() && h.app.stand_up_note, "a cube gets the note");
}
#[test]
fn which_way_is_up_weighs_flat_area_then_the_box() {
use solidcraft_ui_egui::stand_up::{Upright, upright};
assert_eq!(upright(1600.0, 400.0, [40.0, 10.0, 40.0]), Upright::Z, "a broad base facing down Z");
assert_eq!(upright(400.0, 1600.0, [40.0, 40.0, 10.0]), Upright::Y, "broad faces across Y");
// Close areas: the box decides; the thin axis is up.
assert_eq!(upright(100.0, 120.0, [40.0, 5.0, 40.0]), Upright::Y);
assert_eq!(upright(120.0, 100.0, [40.0, 40.0, 5.0]), Upright::Z);
assert_eq!(upright(100.0, 120.0, [40.0, 40.0, 40.0]), Upright::Unclear, "a cube says nothing");
assert_eq!(upright(0.0, 0.0, [f64::NAN, 1.0, 1.0]), Upright::Unclear);
assert_eq!(upright(f64::INFINITY, 1.0, [1.0, 1.0, 1.0]), Upright::Unclear);
}
#[test]
fn the_notes_stand_it_up_turns_once_and_undo_restores() {
let mut h = opened_box(ON_ITS_BACK, UNKNOWN, |_| {});
h.run(&json!([{"click": {"handle": "stand_up:stand"}}])).unwrap();
h.frames(3);
assert!(h.app.stand_up.is_none() && !h.app.stand_up_note, "the note is gone");
assert!(!painted(&h, "Did this part open the wrong way up?"));
assert!((height(&h) - 10.0).abs() < 1e-6, "stood up: {}", height(&h));
h.app.run("edit.undo", json!({})).unwrap();
assert!((height(&h) - 40.0).abs() < 1e-6, "one undo step: {}", height(&h));
}
#[test]
fn the_notes_dont_ask_again_turns_the_offer_off() {
let mut h = opened_box(ON_ITS_BACK, UNKNOWN, |_| {});
h.run(&json!([{"click": {"handle": "stand_up:never"}}])).unwrap();
h.frames(3);
assert!(h.app.stand_up.is_none(), "closed");
assert!(!h.app.preferences.offer_stand_up, "the offer is off, as the dialog's Don't ask again");
assert!((height(&h) - 40.0).abs() < 1e-6, "not turned: {}", height(&h));
}
#[test]
fn the_note_closes_on_dismiss_and_by_itself() {
let mut h = opened_box(ON_ITS_BACK, UNKNOWN, |_| {});
h.run(&json!([{"click": {"handle": "stand_up:dismiss"}}])).unwrap();
h.frames(3);
assert!(h.app.stand_up.is_none(), "dismissed");
assert!(h.app.preferences.offer_stand_up, "the preference stays");
assert!((height(&h) - 40.0).abs() < 1e-6, "not turned: {}", height(&h));
assert!(h.at(&json!({"handle": "stand_up:stand"})).is_err(), "the note is gone");
let mut h = opened_box(ON_ITS_BACK, UNKNOWN, |_| {});
let since = h.app.stand_up_note_since.expect("the note's clock started when it was drawn");
h.frames(30);
assert!(h.app.stand_up.is_some(), "half a second on, still up");
// As if it had been up for the whole time without the pointer on it.
h.app.stand_up_note_since = Some(since - solidcraft_ui_egui::stand_up::NOTE_SECONDS);
h.frames(2);
assert!(h.app.stand_up.is_none(), "gone by itself");
assert!(!painted(&h, "Did this part open the wrong way up?"));
assert!((height(&h) - 40.0).abs() < 1e-6, "not turned: {}", height(&h));
}
#[test]
fn the_unknown_programs_preference_picks_the_dialog_or_nothing() {
// Ask: the dialog, as before, whichever way the file rests.
let mut h = opened();
assert!(h.widget("Stand this part up?").is_some(), "the dialog");
assert!(!painted(&h, "Did this part open the wrong way up?"), "no note");
assert!(h.at(&json!({"handle": "stand_up:dismiss"})).is_err());
let ask = |h: &mut Harness| h.app.preferences.stand_up_unknown = StandUpUnknown::Ask;
assert!(opened_box(UPRIGHT, UNKNOWN, ask).app.stand_up.is_some(), "asked about an upright file too");
// Don't offer: nothing, and a SolidWorks file still gets the dialog.
let off = |h: &mut Harness| h.app.preferences.stand_up_unknown = StandUpUnknown::Off;
assert!(opened_box(ON_ITS_BACK, UNKNOWN, off).app.stand_up.is_none());
let h = opened_box(ON_ITS_BACK, SOLIDWORKS, off);
assert!(h.app.stand_up.is_some() && !h.app.stand_up_note && h.app.stand_up_reason);
// Set through the control channel; a choice it doesn't know is refused.
let mut h = Harness::new();
let r = h.call("ui.prefs", json!({"stand_up_unknown": "ask"}));
assert_eq!(r["result"]["stand_up_unknown"], json!("ask"), "{r}");
assert_eq!(h.app.preferences.stand_up_unknown, StandUpUnknown::Ask);
let r = h.call("ui.prefs", json!({"stand_up_unknown": "sometimes"}));
assert_eq!(r["ok"], json!(false), "refused: {r}");
assert_eq!(h.app.preferences.stand_up_unknown, StandUpUnknown::Ask);
// The default is the note, and preferences saved before the choice existed read as it.
let old: solidcraft_ui_egui::prefs::Prefs = serde_json::from_str(r#"{"offer_stand_up": true}"#).unwrap();
assert_eq!(old.stand_up_unknown, StandUpUnknown::Note);
}
#[test]
fn a_solidworks_file_gets_the_dialog_or_the_note_when_upright() {
// Lying on its back: the dialog.
let mut h = opened_box(ON_ITS_BACK, SOLIDWORKS, |_| {});
assert!(!h.app.stand_up_note, "not the note");
assert!(h.widget("Stand this part up?").is_some(), "the dialog");
assert!(!painted(&h, "Did this part open the wrong way up?"));
for name in ["stand_up:stand", "stand_up:leave", "stand_up:never"] {
assert!(h.at(&json!({"handle": name})).is_ok(), "{name} is published");
}
// Already upright (saved Z up): only the note.
let h = opened_box(UPRIGHT, SOLIDWORKS, |_| {});
assert!(h.app.stand_up.is_some() && h.app.stand_up_note, "the note");
assert!(h.widget("Stand this part up?").is_none(), "no dialog");
assert!(painted(&h, "Did this part open the wrong way up?"));
// Ask in a dialog keeps the behaviour from before: the dialog, without looking.
let h = opened_box(UPRIGHT, SOLIDWORKS, |h| h.app.preferences.stand_up_unknown = StandUpUnknown::Ask);
assert!(h.app.stand_up.is_some() && !h.app.stand_up_note, "the dialog");
}
#[test]
fn a_file_with_several_bodies_is_an_assembly() {
let two = [[0.0, 0.0, 0.0], [60.0, 0.0, 0.0]];
let h = opened_boxes(ON_ITS_BACK, &two, UNKNOWN, |_| {});
assert_eq!(h.app.stand_up.as_ref().map(Vec::len), Some(2));
assert!(h.app.stand_up_assembly);
assert!(painted(&h, "Did this assembly open the wrong way up?"), "the note says assembly");
let h = opened_boxes(ON_ITS_BACK, &two, SOLIDWORKS, |_| {});
assert!(h.widget("Stand this assembly up?").is_some(), "the dialog says assembly");
assert!(h.widget("Stand this part up?").is_none());
// One body is a part.
assert!(!opened_box(ON_ITS_BACK, UNKNOWN, |_| {}).app.stand_up_assembly);
}
+4 -3
View File
@@ -305,7 +305,7 @@ labels; `prefs:measure_axis_distances` identifies the checkbox.
| `ui.home` | `open?`: bool; `sample?`: index | the start page: show or hide it, open a built-in sample (once built); returns `open` and the recent designs |
| `ui.shortcut` | `command`, `key?`, `replace?` | a command's key, or rebinds it (`""` clears; a key another command uses is refused unless `replace`) |
| `ui.help` | `item?`: `about`, `shortcuts` (read only), `report` (opens a report draft for review), `crashes` (the Crash Reports window) | the version, commit, build date and diagnostic text |
| `ui.prefs` | any of the [`ui.prefs` settings](#uiprefs-settings) below; also `open`, `button` and `stand_up` (listed there) | sets preferences (kept between runs), returns them all plus `dialog` (the open page or null), `dark`, `viewport_dark` (whether the 3D view is dark), `stand_up_offer`, `theme_followed` and `theme_follow_error` |
| `ui.prefs` | any of the [`ui.prefs` settings](#uiprefs-settings) below; also `open`, `button` and `stand_up` (listed there) | sets preferences (kept between runs), returns them all plus `dialog` (the open page or null), `dark`, `viewport_dark` (whether the 3D view is dark), `stand_up_offer` (the offered bodies, or null), `stand_up_note` (whether that offer is the note), `theme_followed` and `theme_follow_error` |
| `ui.capture` | `action?`: `capture`, `revert`, `cancel` | answers the Capture Position question (asked when a command starts or the design is saved while components were moved without capturing); without `action`, what waits |
| `ui.window` | `action`: minimize, maximize, restore, toggle, close | what the title bar's caption buttons do (on Windows and Linux the application bar is the title bar); close asks about unsaved designs first |
| `ui.agent_cursor` | `show` (bool), `speed`: a number from 1 to 5 (times the normal speed) or `"instant"` (no animation: the command runs at once and the pointer jumps to where it acted), `follow_camera` (bool); all optional | the settings. While the cursor is shown, `engine.execute` first glides to the command's toolbar button and to each pick, then runs and replies; later requests wait their turn. The pointer shows the command's localized name, including commands inside a closed toolbar group; an animated batch names each command it visits. It also follows the pointer input sent with `ui.move`, `ui.click`, `ui.drag` and `ui.scroll`, as each event reaches the app, and a press leaves a ripple. `"animate": false` on a call skips it |
@@ -357,6 +357,7 @@ One setting per line, sorted by name. A change that adds a setting adds its own
- `sketch_exit_view` (`keep` (default: the view stays where it is when a sketch ends), `previous` (back to the view from before the sketch), `unless_rotated` (back unless the sketch view was turned))
- `sketch_tab_always` (default false: the SKETCH tab stays in the ribbon right after MODEL while no sketch is open; a tool in its CREATE or REFERENCE section then opens Create Sketch, on the selected plane or planar face or else on the plane picked next, and starts in the new sketch, #7904)
- `smooth_wheel_zoom` (default true)
- `stand_up_unknown` (`note` (default: a file whose header names no program known to save Y up and whose bodies seem to lie on their back (their flat area across Y outweighs their flat area facing down Z) gets a small note over the view, "Did this part open the wrong way up?", with Stand it up, Don't ask again and Close as the handles `stand_up:stand`, `stand_up:never` and `stand_up:dismiss`; it goes by itself after 10 seconds and never blocks input), `ask` (the "Stand this part up?" dialog for every file from another program, SolidWorks too, without looking at how it rests, as before #7717), `off` (no offer); otherwise a SolidWorks file gets the dialog, or the note when its bodies clearly stand on Z already)
- `status_bar` (default false: a thin bar along the window's bottom edge, below History, handle `status:bar`: what is being edited (`status:editing`), the open sketch's state in its colour (`status:sketch`) and the design's units (`status:units`, a click opens the Units menu, whose rows run `document.units`); the sketch's state then leaves the view's top-left corner, #7243)
- `step_values` (default false: Up/Down and the wheel step a plain number in a focused value field)
- `theme` (`dark`, `light`, `system` or a theme file's id: a built-in one such as `gruvbox-dark`, or an imported one; the reply's `theme_ids` lists them)
@@ -379,8 +380,8 @@ Other `ui.prefs` parameters:
- `open` (a page: General, Interface, Design, Navigation, Keyboard Shortcuts, Sketch, Graphics, AI, Plugins; Shortcuts, Assistant and Sketch & selection are aliases, and the former Selection page opens Sketch) opens the Preferences dialog there
- `button`: `ok`, `cancel`, `apply`, `defaults`
- `stand_up: true` stands up a just-opened Y-up file, `stand_up: false` leaves it as it is ("Leave it": the offer closes and `offer_stand_up` stays on)
- the offer's buttons are the handles `stand_up:stand`, `stand_up:leave` and `stand_up:never`
- `stand_up: true` stands up a just-opened Y-up file, `stand_up: false` leaves it as it is ("Leave it": the offer, dialog or note, closes and `offer_stand_up` stays on)
- the dialog's buttons are the handles `stand_up:stand`, `stand_up:leave` and `stand_up:never`
`ui.workspace {workspace?: "design" | "render"}` reads or changes the active workspace.
Entering Render requires finishing the current modelling operation; returning restores
+1 -1
View File
@@ -45,7 +45,7 @@ the supporting ellipse in the middle.
Files from different systems differ in which way is up and in what they call their solids. `doc.open`, `file.insert_step` and the MCP `open` tool take two options for STEP and IGES files; without them a file comes in as written.
- **`up`**: `"z"` (the default) keeps the file's axes. Many systems write Y up, so such a part lies on its back in SolidCraft's Z-up space. `"up": "y"` turns the import's component a quarter turn about X (+90°: Y becomes Z), as the window's "Stand it up" offer does, so an assembly's parts and instances turn together. The import and the turn are one undo step, the reply names the turned occurrence as `stand_up`, and only the file's component turns, not what is already in the design. The window offers to stand a part up after a STEP file opens unless the call said which way is up (`up: "z"` as well as `"y"`) or the file came from SolidCraft, which already writes Z up. A STEP reply's `system` is the originating system the file's header names (`SolidCraft` for SolidCraft's own exports). A header that names SolidWorks (in FILE_NAME's originating system or preprocessor version, or in FILE_DESCRIPTION; for IGES, the start of the global section's native system ID, which becomes the originating system) says the file has Y up: the reply carries `exporter` (`SolidWorks`) and `exporter_up` (`y`), and the window's offer then says so ("Exported by SolidWorks, which usually saves Y up"). A file is never turned without asking, because the exporter may have saved it Z up; a component's right-click menu has Turn Up Axis (Y up → Z up, Z up → Y up: a quarter turn about X, one undo step) for fixing it any time. SolidCraft's own files say `z` and are left alone; any other exporter is unknown, so the offer stays.
- **`up`**: `"z"` (the default) keeps the file's axes. Many systems write Y up, so such a part lies on its back in SolidCraft's Z-up space. `"up": "y"` turns the import's component a quarter turn about X (+90°: Y becomes Z), as the window's "Stand it up" offer does, so an assembly's parts and instances turn together. The import and the turn are one undo step, the reply names the turned occurrence as `stand_up`, and only the file's component turns, not what is already in the design. The window offers to stand a part up after a STEP file opens unless the call said which way is up (`up: "z"` as well as `"y"`) or the file came from SolidCraft, which already writes Z up. A STEP reply's `system` is the originating system the file's header names (`SolidCraft` for SolidCraft's own exports). A header that names SolidWorks (in FILE_NAME's originating system or preprocessor version, or in FILE_DESCRIPTION; for IGES, the start of the global section's native system ID, which becomes the originating system) says the file has Y up: the reply carries `exporter` (`SolidWorks`) and `exporter_up` (`y`), and the window asks in the "Stand this part up?" dialog, which says so ("Exported by SolidWorks, which usually saves Y up"). A file is never turned without asking, because the exporter may have saved it Z up; a component's right-click menu has Turn Up Axis (Y up → Z up, Z up → Y up: a quarter turn about X, one undo step) for fixing it any time. SolidCraft's own files say `z` and are left alone. Any other exporter is unknown, and such files are often upright already, so by default the window first looks at how the bodies rest: a part rests on its flat faces, so the flat area facing down Z is weighed against the larger flat area facing down or up Y (faces within 10° of the direction; one side must have at least 1.5 times the other's, else the thinner of the box's Y and Z sizes decides). Unless the file clearly stands upright, the window shows a small note over the view ("Did this part open the wrong way up?" with Stand it up and Close) that goes by itself after 10 seconds and never blocks input; a file that clearly stands upright gets nothing, and an unclear shape still gets the note. A SolidWorks file whose bodies clearly stand on Z already gets the note instead of the dialog, since it may have been saved Z up. Preferences › Design › "For files from unknown programs" picks the dialog for every file from another program, SolidWorks too, without looking at how it rests (Ask in a dialog, as before) or no offer (Don't offer) instead. The dialog and the note say "assembly" when the file brought more than one body or a component tree.
- **`names`**: `"auto"` (the default) keeps meaningful solid names and replaces placeholders such as `Body1` or `Body 2 (3)` with the nearest named product, then the occurrence name if no product is named. `"solid"` keeps the solid's name; `"product"` chooses the part's name; `"instance"` chooses the assembly occurrence (`Post-2`), falling back to the product. If the chosen name is missing, the solid's name remains. Repeated names are numbered (`Post`, `Post (2)`). Names are stored with the Import feature and survive reopening the design. Files without names or assembly metadata retain generated body names and a flat structure.
- **Vertices off their curves**: some systems write an edge's vertex a little beside the end of its curve, often further off than the accuracy the file declares (`UNCERTAINTY_MEASURE_WITH_UNIT`). A vertex up to the file's own tolerance off, or up to 1/1000 of the model's size (never more than 1 mm), is read as that end of the edge: the curve's end is moved onto the vertex. A vertex further off leaves its face out, with a warning that says how far off it is.