From 4dab0e8f381d7362777277f621d418b991a5789f Mon Sep 17 00:00:00 2001 From: Bruno Santos Date: Wed, 18 Nov 2026 00:45:26 +0000 Subject: [PATCH] feat(studio): boolean and choice parameters in the Design variants window (B.02, G.03) The Design variants window treated every program parameter as a number. Edit value rejected a text choice ("Enter a finite numeric value"), accepted any number for a boolean or numeric choice and failed later, and Explore values read numbers only, so typed parameters were compared and saved through the tool. - The parameter list shows On/Off or the chosen value with the declared list. A row wider than the list scrolls sideways instead of being cut. - Edit value keeps the numeric editor for a number, switches a boolean and opens the declared list of a numeric or text choice, taken by position. - Explore values opens on the selected parameter with its own trial values (min, current and max, or every declared value) and offers another parameter's values when that parameter is chosen. It reads On/Off words and listed texts; a listed text holding a comma is matched whole. No trial values, or the offered ones left unchanged, means every declared value. An unlisted value stays a failed trial, as in the tool. - Result rows and thumbnails name the value each trial tried. - The explore guidance now fits the two lines the shared dialog shows. - Text goes to and from the shared field dialog in the system code page, so accented choice text shows and is typed correctly. parametricProgramParameterKinds exposes the engine's own kind rule so the window does not restate it. The tool, the document format and release.json are unchanged: this is not a new distributable iteration. Local evidence, MSVC Release with OCCT: - studio-design-variants-ui installs a second program with a boolean, a numeric choice and a text choice whose list holds a comma, an accent and a letter outside the Western code page. Each is staged from the window's controls; Preview reports the exact 16800 mm3 volume and 12 mm height of the staged choices; Apply publishes one revision with matching objects; two named variants are saved with text and 1/0 values, compared, loaded and reopened from disk; exploration covers listed, comma-holding, unlisted, offered, emptied, boolean-word and rejected trial values without publishing. - Captures .typed, .typed-choice-dialog, .typed-explore and .typed-explore-dialog were inspected, with the existing .compact capture. - parametric-programs checks the exposed kinds against the compile report. - design_variants, parametric-programs, studio-program-hud-ui, -parametric-hud-ui, -parametric-graph-ui, -parametric-authoring-ui, -parametric-role-ui, -geometry-nodes-ui, -team-blockers-ui, release-evidence and release-metadata pass. Not run: the full native and Studio suites, and any live provider. Hosted CI runs no Studio UI checks. Text outside the system code page can be picked and explored from the offered values but not typed as a trial value. The Trial values label is still cut by the shared dialog. Co-Authored-By: Claude Fable 5.2 --- docs/DESIGN_VARIANTS_067G.md | 38 +++++++++++++--- docs/PARAMETRIC_PROGRAMS.md | 9 ++-- docs/ROADMAP.md | 2 +- include/ark/parametric_programs.hpp | 3 ++ src/parametric_programs.cpp | 1 + src/view/design_variants.inl | 54 ++++++++++++++++++++--- src/view/design_variants_selftest.inl | 63 ++++++++++++++++++++++++++- tests/parametric_programs_tests.cpp | 2 + 8 files changed, 150 insertions(+), 22 deletions(-) diff --git a/docs/DESIGN_VARIANTS_067G.md b/docs/DESIGN_VARIANTS_067G.md index 249cce9..bf85b12 100644 --- a/docs/DESIGN_VARIANTS_067G.md +++ b/docs/DESIGN_VARIANTS_067G.md @@ -4,8 +4,10 @@ Scope: **B.02/B.04/D.05/G.03 — Verificado no escopo local**. See the [iteratio The Studio **Design variants** window configures an installed parametric program. **New family** installs one of the existing editable examples. The parameter list -shows authored values, units and declared bounds; **Edit value** stages a numeric -value. **Preview** evaluates the staged configuration without publishing it; +shows authored values, units and declared bounds, or the declared values of a +boolean or choice. **Edit value** stages a number, switches a boolean between +**Off** and **On**, or opens the declared list of a numeric or text choice. +**Preview** evaluates the staged configuration without publishing it; **Apply** prepares and publishes one revision-bound exact candidate. Undo restores the previous editable source. @@ -23,7 +25,14 @@ Save or Apply. Triangles are display evidence only and never select the producti geometry or measured dimensions. **Explore values** evaluates explicitly entered values for one parameter in the -native UI. Optional width/depth/height/mass limits filter feasibility. Explicit +native UI. It opens on the selected parameter with trial values to edit: minimum, +current and maximum for a number, every declared value for a boolean or choice. +Choosing another parameter offers that parameter's values. Trial values are +numbers or expressions, **On**/**Off** for a boolean, or listed texts separated +by commas; a listed text that itself holds a comma is matched whole. Leaving +them empty tries every declared value of a boolean or choice. Each result row +names the value it tried. Optional width/depth/height/mass limits filter +feasibility. Explicit feature pairs and a minimum gap use native B-rep distance/common-volume inspection for each trial. Overlap, missing features or unavailable measurements cannot rank as feasible. The Studio form accepts one pair; the tool accepts up to sixteen @@ -63,10 +72,9 @@ including choice text, for example retained failed trial. Results and saved variants store resolved values: `1`/`0` for a boolean and the listed text for a text choice. A saved text value requires semantic version 60; numeric-only variants keep version 56. Studio's -**Edit value** and **Explore values** stage numbers only, so text choices are -compared and saved through the tool. The -[Parametric HUD](PARAMETRIC_PROGRAMS.md#studio) configures a text choice on the -installed program. +**Edit value** and **Explore values** take the same kinds, so a boolean or a +numeric or text choice is staged, saved, compared and explored in the window as +well as through the tool. `ranked_indices` indexes `results` in objective order and includes only feasible rows with the requested metric available. `mass_kg` is absent and cannot be ranked @@ -83,3 +91,19 @@ Pair clearance is static at the evaluated definition positions, not a continuous-motion certificate. AI authors can propose the value sets through this same tool; real-provider design quality and savings require separate evidence. + +## Typed values in the window + +Booleans and choices in **Edit value** and **Explore values** were added after +067G and are not yet part of an identified iteration. The local +`studio-design-variants-ui` check installs a second program with a boolean, a +numeric choice and a text choice, stages each from the window's controls and +checks the previewed exact volume and height, one applied revision, two saved +named variants, their comparison, exploration and reopening. Its captures +(`.typed.png`, `.typed-choice-dialog.png`, `.typed-explore.png` and +`.typed-explore-dialog.png`) were inspected. Hosted CI runs no Studio UI checks. + +The field dialog exchanges text in the system code page. A choice text outside +that code page is still picked from its list by position, and explored when the +offered trial values are left unchanged or emptied, but it cannot be typed as a +trial value. diff --git a/docs/PARAMETRIC_PROGRAMS.md b/docs/PARAMETRIC_PROGRAMS.md index 9e111a0..1905f08 100644 --- a/docs/PARAMETRIC_PROGRAMS.md +++ b/docs/PARAMETRIC_PROGRAMS.md @@ -321,8 +321,8 @@ the HUD shows a **Parameters / Programs** switch under its header. It opens on **Programs** when no document parameter is exposed. The [Design variants](DESIGN_VARIANTS_067G.md) window (**Manage > Variants** or **All tools > Parametric configurator**) remains the place for named -configurations, comparison and exploration; the HUD's **Variants** button opens -it on the same namespace. +configurations, comparison and exploration of every parameter kind; the HUD's +**Variants** button opens it on the same namespace. - **Bindings.** After each revision the view reads `parametric_program{action:"inspect"}`: namespace and name, owned objects and @@ -534,7 +534,4 @@ measurement, not a benchmark. Assertions and bounds encode the design rules stated by the author. They are not manufacturing, structural or fit qualification. No measured agent quality, time or token benefit is claimed. Editing program source in Studio is not -implemented. Studio's Design variants window stages numeric values only, so a -text choice is compared and saved as a variant through the tool; the -Parametric HUD configures it on the installed program. Program assembly output -is not implemented (see above). +implemented. Program assembly output is not implemented (see above). diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 9959b6a..5c7c6b7 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -491,7 +491,7 @@ Goal: create and revise a complete product with clear, reliable interactions. | ID | Milestone | Status | Acceptance still governing the work | |---|---|---|---| | B.01 | Readable navigation and editing | Parcial | Stable cube/axes, free orbit, selection/Spotlight, shortcuts and DPI; no clipped controls at supported resolutions. Measurement and display units have [013B evidence](iterations/013B.md); BOM layout has [015B evidence](iterations/015B.md). [017B scoped evidence](iterations/017B.md). [018B editable authoring and coordination](iterations/018B.md). [019B native/mesh pointer selection, hover and visual authoring](iterations/019B.md). [020B exact extrusion gestures and source dimensions](iterations/020B.md). [021B direct handle and snapshot feedback](iterations/021B.md). [022B existing-solid resize, asynchronous previews, exact vertex tools and integrated sheets](iterations/022B.md). 029B adds accessible native fields, visible focus and dynamic DPI/work-area reflow; [sketch/accessibility evidence](SKETCH_ASSISTANCE_029B.md). [048B](iterations/048B.md) adds the Studio parametric HUD overlay with staged Rebuild/Auto. [053B native graph](PARAMETRIC_COMPONENTS_053B.md) connects authored relationships, geometry selection and local navigation. [065F](iterations/065F.md) unifies the Studio palette, ribbon grouping and one outline-icon family, with a floating sidebar on every tab. [072A storage visibility](GROWABLE_EDITING_072A.md) replaces discontinued quota percentages with actual retained counts/bytes and explicit resource errors; UI verification is pending. | -| B.02 | Everyday sketches and feature history | Parcial | Actionable constraint diagnostics, valid reorder, suppress/rollback and visible dependencies; rejection leaves the document intact. Arcs/snaps/expressions have scoped 005B/008D evidence. [017B scoped evidence](iterations/017B.md). [018B editable authoring and coordination](iterations/018B.md). [019B visual and parametric authoring](iterations/019B.md). [020B exact extrusion gestures and source dimensions](iterations/020B.md). [021B associative extrusion source](iterations/021B.md). [022B source-preserving edits, opaque validated preview handoff and version-37 journal checks](iterations/022B.md). 029B adds equilibrated QR solving and source/revision-bound reviewed conflict alternatives; [sketch assistance](SKETCH_ASSISTANCE_029B.md). [046B profile regions](PROFILE_REGIONS_046B.md) make multi-loop sketches with holes one extrude/revolve profile, with typed loop rejections and an optional region selection. [048B parametric HUD](PARAMETRIC_HUD_048B.md) exposes ranged named parameters and a sampled flex check. [051A scoped sketches](SCOPED_SKETCHES_051A.md) add definition ownership, explicit references and guarded per-scope capacity. [Parametric programs](PARAMETRIC_PROGRAMS.md) compile code-defined families into namespaced native features, with atomic re-runs that reject local edits and outside dependants (local CTest only). [072A growing history](GROWABLE_EDITING_072A.md) removes fixed history/node/replay ceilings without pruning or changing authoring semantics; local persistence and UI validation passed. [076A](iterations/076A.md) hardens program expressions and provenance, adds boolean/choice/text parameters (conditional format 60), `.arkprog` exchange and Studio HUD program controls; programs still emit no assembly. The HUD's Programs view has since gained controls for booleans and numeric or text choices (local `studio-program-hud-ui` only; not yet part of an identified iteration). | +| B.02 | Everyday sketches and feature history | Parcial | Actionable constraint diagnostics, valid reorder, suppress/rollback and visible dependencies; rejection leaves the document intact. Arcs/snaps/expressions have scoped 005B/008D evidence. [017B scoped evidence](iterations/017B.md). [018B editable authoring and coordination](iterations/018B.md). [019B visual and parametric authoring](iterations/019B.md). [020B exact extrusion gestures and source dimensions](iterations/020B.md). [021B associative extrusion source](iterations/021B.md). [022B source-preserving edits, opaque validated preview handoff and version-37 journal checks](iterations/022B.md). 029B adds equilibrated QR solving and source/revision-bound reviewed conflict alternatives; [sketch assistance](SKETCH_ASSISTANCE_029B.md). [046B profile regions](PROFILE_REGIONS_046B.md) make multi-loop sketches with holes one extrude/revolve profile, with typed loop rejections and an optional region selection. [048B parametric HUD](PARAMETRIC_HUD_048B.md) exposes ranged named parameters and a sampled flex check. [051A scoped sketches](SCOPED_SKETCHES_051A.md) add definition ownership, explicit references and guarded per-scope capacity. [Parametric programs](PARAMETRIC_PROGRAMS.md) compile code-defined families into namespaced native features, with atomic re-runs that reject local edits and outside dependants (local CTest only). [072A growing history](GROWABLE_EDITING_072A.md) removes fixed history/node/replay ceilings without pruning or changing authoring semantics; local persistence and UI validation passed. [076A](iterations/076A.md) hardens program expressions and provenance, adds boolean/choice/text parameters (conditional format 60), `.arkprog` exchange and Studio HUD program controls; programs still emit no assembly. The HUD's Programs view and the Design variants window have since gained controls for booleans and numeric or text choices (local `studio-program-hud-ui` and `studio-design-variants-ui` only; not yet part of an identified iteration). | | B.03 | Advanced solids and surfaces | Parcial | Difficult loft/sweep/guide/patch/trim/thicken corpus, measured continuity and explicit repair; no mesh fallback concealing exact failures. [017B scoped evidence](iterations/017B.md). [018B editable authoring and coordination](iterations/018B.md). [019B visual and parametric authoring](iterations/019B.md). [020B exact sketch extrusion](iterations/020B.md). [021B bounded face/extrusion geometry](iterations/021B.md). [022B exact polyhedral vertex pull](NATIVE_VERTEX_PULL_022B.md) adds a bounded faceted-solid domain with input/output validity and selfinterference checks. 029B adds bounded exact orientation repair and a difficult geometry corpus; [repair evidence](SURFACE_REPAIR_029B.md). [046B hollow sweep sections](PROFILE_REGIONS_046B.md) sweep inner loops with one shared placement and a volume-conservation check. [051A native regression evidence](NATIVE_GEOMETRY_051A.md) covers shallow C0 offset classification and translated analytic C2 lofts with unchanged tolerances. | | B.04 | Large, configurable assemblies | Parcial | Subassemblies, reused instances, configurations, external references and selective loading; editing one definition updates all occurrences. Supported mechanisms are locally scoped. [022B source-linked component patterns](SPECIALIZED_PATTERNS_022B.md) cover inheritance, planar/spatial points, exact curve stations, chain alternation, skips and actual occurrence consumers; large configuration/loading qualification remains open. 029B adds semantic loading, measured derived-buffer/external-I/O reduction and scoped v2 configuration/pin ownership; [assembly evidence](ASSEMBLY_SCALING_029B.md). [048B exploded views](EXPLODED_VISUALIZE_048B.md) are display-only, revision-neutral and drivable by baked motions. [051A definition-owned sketches](SCOPED_SKETCHES_051A.md) are shared across occurrences and remapped with component checkout/merge. [053B reusable recipes](PARAMETRIC_COMPONENTS_053B.md) embed parts/assemblies with public overrides and explicit pinned revision updates. | | B.05 | Technical drawings and exchange | Parcial | Local 022B binds part definitions, exact occurrences and root/group assemblies to source-linked views, isometric projections, planar sections/hatches, semantic dimensions and declared tolerances in the same CAD viewport. Agents author drawings only on explicit user request. 029B adds bounded exact DXF export with local readback and source metadata. Broader drafting standards, GD&T qualification, independent recipient interoperability and physical qualification remain open. [067G](DRAWING_LIBRARY_067G.md) adds local multipage vector PDF presentation and caller-declared named geometric tolerance frames. [Drawing contract](DRAWINGS.md) [022B viewport evidence](DRAWING_VIEWPORT_022B.md) [029B evidence](VERIFICATION_029B.md). [048B Visualize](EXPLODED_VISUALIZE_048B.md) renders exploded assembly images with balloons and a BOM table on explicit request. | diff --git a/include/ark/parametric_programs.hpp b/include/ark/parametric_programs.hpp index 4d02d3c..003e9ca 100644 --- a/include/ark/parametric_programs.hpp +++ b/include/ark/parametric_programs.hpp @@ -28,4 +28,7 @@ bool parametricProgramsRequire60(const Document&); bool callParametricProgramTool(AgentSession&,const std::string&,const arkjson::Value&,arkjson::Value&); void appendParametricProgramTools(arkjson::Value&); arkjson::Value parametricProgramExamples(); +// Kind of each declared parameter by name: "number", "boolean", "choice" or +// "text_choice", exactly as validate and inspect report parameter_kinds. +arkjson::Value parametricProgramParameterKinds(const arkjson::Value& program); } diff --git a/src/parametric_programs.cpp b/src/parametric_programs.cpp index f621fbd..883a058 100644 --- a/src/parametric_programs.cpp +++ b/src/parametric_programs.cpp @@ -579,6 +579,7 @@ void appendParametricProgramTools(V& list){ tool.set("inputSchema",schema);annotations.set("readOnlyHint",V::makeBool(false));tool.set("annotations",annotations);list.arr.push_back(tool); } +V parametricProgramParameterKinds(const V& program){return parameterKinds(program);} V parametricProgramExamples(){ V out=V::makeArr(); auto add=[&](const char* id,const char* summary,const char* source){V row=V::makeObj(),program;if(!arkjson::parse(source,program))fail("EXAMPLE",id);validateProgram(program);row.set("id",V::makeStr(id));row.set("summary",V::makeStr(summary));row.set("program",program);out.arr.push_back(row);}; diff --git a/src/view/design_variants.inl b/src/view/design_variants.inl index 44383ec..fb33e0b 100644 --- a/src/view/design_variants.inl +++ b/src/view/design_variants.inl @@ -2,7 +2,7 @@ // exact B-rep metrics returned by the same tool used by agents. namespace design_variants_view_067g { using V=arkjson::Value; -struct State {HWND window=nullptr,program=nullptr,parameters=nullptr,variants=nullptr,name=nullptr,results=nullptr,status=nullptr;HFONT font=nullptr;std::string ns;V values,report;u64 revision=0,epoch=0;bool busy=false;std::vector parameterNames,savedNames,programNames;int selectedResult=0;}; +struct State {HWND window=nullptr,program=nullptr,parameters=nullptr,variants=nullptr,name=nullptr,results=nullptr,status=nullptr;HFONT font=nullptr;std::string ns;V values,report;u64 revision=0,epoch=0;bool busy=false;std::vector parameterNames,savedNames,programNames;int selectedResult=0;std::string axis;}; static State state; static const V& field(const V& v,const char* key){static V none;const auto* p=v.find(key);return p?*p:none;} static std::wstring wide(const std::string& s){return bomWide(s);} @@ -10,20 +10,60 @@ static std::string windowText(HWND w){int n=GetWindowTextLengthW(w);std::wstring static void message(const std::string& s){SetWindowTextW(state.status,wide(s).c_str());g_status=s;} static void add(HWND list,const std::string& s,bool combo=false){SendMessageW(list,combo?CB_ADDSTRING:LB_ADDSTRING,0,(LPARAM)wide(s).c_str());} static const V* program(){for(const auto& p:g_doc.parametricPrograms.arr)if(field(p,"namespace").str==state.ns)return &p;return nullptr;} -static void fillParameters(){SendMessageW(state.parameters,LB_RESETCONTENT,0,0);state.parameterNames.clear();const auto* p=program();if(!p)return;for(const auto& parameter:field(field(*p,"program"),"parameters").obj){state.parameterNames.push_back(parameter.first);const auto& spec=parameter.second;std::string label=parameter.first+" = "+field(state.values,parameter.first.c_str()).dump()+" "+field(spec,"unit").asStr();if(spec.find("min")||spec.find("max"))label+=" ["+(spec.find("min")?field(spec,"min").dump():"-")+" .. "+(spec.find("max")?field(spec,"max").dump():"-")+"]";add(state.parameters,label);}if(!state.parameterNames.empty())SendMessageW(state.parameters,LB_SETCURSEL,0,0);} +// Parameter kinds as the program tool reports them. A boolean is staged as 1/0 +// and a text choice as its listed text, the forms design_variants stores. +enum class ParameterKind{Number,Boolean,Choice,Text}; +static ParameterKind parameterKind(const std::string& name){const auto* p=program();const std::string kind=p?field(parametricProgramParameterKinds(field(*p,"program")),name.c_str()).asStr():std::string();return kind=="boolean"?ParameterKind::Boolean:kind=="choice"?ParameterKind::Choice:kind=="text_choice"?ParameterKind::Text:ParameterKind::Number;} +static std::string shownValue(ParameterKind kind,const V& value){if(value.t==V::Str)return value.str;if(kind==ParameterKind::Boolean)return (value.t==V::Bool?value.b:value.num!=0)?"On":"Off";return value.dump();} +// Declared values of a boolean or choice in declared order; none for a number. +static std::vector declaredValues(ParameterKind kind,const std::string& name){if(kind==ParameterKind::Boolean)return {V::makeNum(0),V::makeNum(1)};const auto* p=program();if(kind==ParameterKind::Number||!p)return {};const auto& choices=field(field(field(field(*p,"program"),"parameters"),name.c_str()),"choices");return choices.t==V::Arr?choices.arr:std::vector{};} +// The declared values for one list row; a long list is cut at a whole value and counted. +static std::string listedValues(ParameterKind kind,const std::vector& values){std::string out;size_t count=0;for(const auto& value:values){const auto item=shownValue(kind,value);if(count&&out.size()+item.size()>70)break;out+=(count?", ":"")+item;++count;}return countsize()))continue;const auto next=input.find_first_not_of(' ',at+c.size());if(next==std::string::npos||input[next]==',')listed=&c;}const auto comma=input.find(',',listed?at+listed->size():at);const auto word=listed?*listed:trimField(input.substr(at,comma==std::string::npos?std::string::npos:comma-at));if(!word.empty())out.arr.push_back(V::makeStr(word));if(comma==std::string::npos)break;at=comma+1;}return out;} + std::istringstream in(input);std::string word;while(std::getline(in,word,',')){word=trimField(word);if(kind==ParameterKind::Boolean){std::string lower=word;for(auto& ch:lower)ch=(char)std::tolower((unsigned char)ch);const bool on=lower=="on"||lower=="true"||lower=="1";if(!on&&lower!="off"&&lower!="false"&&lower!="0")throw std::runtime_error("Trial values of "+name+" are On or Off");out.arr.push_back(V::makeNum(on?1:0));}else{bool ok=false;const double number=evalExpr(word,g_doc.buildEnv(),&ok);if(!ok||!std::isfinite(number))throw std::runtime_error("Trial values must be finite numbers");out.arr.push_back(V::makeNum(number));}} + return out; +} +// An exploration row names the value it tried, so "Trial 2" is not its only label. +static std::string resultTitle(const V& row){const auto name=field(row,"name").asStr();const auto* value=state.axis.empty()?nullptr:field(row,"values").find(state.axis.c_str());return value?name+" ("+state.axis+" = "+shownValue(parameterKind(state.axis),*value)+")":name;} +static void fillParameters(){SendMessageW(state.parameters,LB_RESETCONTENT,0,0);SendMessageW(state.parameters,LB_SETHORIZONTALEXTENT,0,0);state.parameterNames.clear();const auto* p=program();if(!p)return;HDC dc=GetDC(state.parameters);const auto listFont=SelectObject(dc,state.font);int extent=0;for(const auto& parameter:field(field(*p,"program"),"parameters").obj){state.parameterNames.push_back(parameter.first);const auto& spec=parameter.second;const ParameterKind kind=parameterKind(parameter.first);const auto unit=field(spec,"unit").asStr();std::string label=parameter.first+" = "+shownValue(kind,field(state.values,parameter.first.c_str()))+(kind==ParameterKind::Number||!unit.empty()?" "+unit:std::string());if(kind!=ParameterKind::Number)label+=" ["+listedValues(kind,declaredValues(kind,parameter.first))+"]";else if(spec.find("min")||spec.find("max"))label+=" ["+(spec.find("min")?field(spec,"min").dump():"-")+" .. "+(spec.find("max")?field(spec,"max").dump():"-")+"]";add(state.parameters,label);const auto shown=wide(label);SIZE size{};GetTextExtentPoint32W(dc,shown.c_str(),(int)wcslen(shown.c_str()),&size);extent=std::max(extent,(int)size.cx);} + // A row wider than the list, such as a long declared list, scrolls sideways instead of being cut. + SelectObject(dc,listFont);ReleaseDC(state.parameters,dc);SendMessageW(state.parameters,LB_SETHORIZONTALEXTENT,extent+12,0);if(!state.parameterNames.empty())SendMessageW(state.parameters,LB_SETCURSEL,0,0);} static void fillSaved(){SendMessageW(state.variants,LB_RESETCONTENT,0,0);state.savedNames.clear();for(const auto& v:g_doc.designVariants.arr)if(field(v,"namespace").str==state.ns){state.savedNames.push_back(field(v,"name").str);const auto* p=program();add(state.variants,field(v,"name").str+(p&&field(v,"program_sha256").str==field(*p,"program_sha256").str?"":" [source changed]"));}} -static void refresh(){state.revision=g_session.revision;state.epoch=g_documentEpoch;state.report={};state.selectedResult=0;SendMessageW(state.results,LB_RESETCONTENT,0,0);SendMessageW(state.program,CB_RESETCONTENT,0,0);state.programNames.clear();int selected=0;for(const auto& p:g_doc.parametricPrograms.arr){if(field(p,"namespace").str==state.ns)selected=(int)state.programNames.size();state.programNames.push_back(field(p,"namespace").str);add(state.program,field(p,"namespace").str+" / "+field(p,"name").str,true);}for(const auto& v:g_doc.designVariants.arr){const auto ns=field(v,"namespace").str;if(std::find(state.programNames.begin(),state.programNames.end(),ns)==state.programNames.end()){if(ns==state.ns)selected=(int)state.programNames.size();state.programNames.push_back(ns);add(state.program,ns+" / program removed",true);}}if(!state.programNames.empty()){SendMessageW(state.program,CB_SETCURSEL,selected,0);state.ns=state.programNames[selected];state.values=program()?field(*program(),"values"):V::makeObj();}else{state.ns.clear();state.values=V::makeObj();}fillParameters();fillSaved();message(state.ns.empty()?"Install a starter program to create an editable family.":"Edit parameters, preview, save named configurations, then compare or explore.");InvalidateRect(state.window,nullptr,TRUE);} +static void refresh(){state.revision=g_session.revision;state.epoch=g_documentEpoch;state.report={};state.axis.clear();state.selectedResult=0;SendMessageW(state.results,LB_RESETCONTENT,0,0);SendMessageW(state.program,CB_RESETCONTENT,0,0);state.programNames.clear();int selected=0;for(const auto& p:g_doc.parametricPrograms.arr){if(field(p,"namespace").str==state.ns)selected=(int)state.programNames.size();state.programNames.push_back(field(p,"namespace").str);add(state.program,field(p,"namespace").str+" / "+field(p,"name").str,true);}for(const auto& v:g_doc.designVariants.arr){const auto ns=field(v,"namespace").str;if(std::find(state.programNames.begin(),state.programNames.end(),ns)==state.programNames.end()){if(ns==state.ns)selected=(int)state.programNames.size();state.programNames.push_back(ns);add(state.program,ns+" / program removed",true);}}if(!state.programNames.empty()){SendMessageW(state.program,CB_SETCURSEL,selected,0);state.ns=state.programNames[selected];state.values=program()?field(*program(),"values"):V::makeObj();}else{state.ns.clear();state.values=V::makeObj();}fillParameters();fillSaved();message(state.ns.empty()?"Install a starter program to create an editable family.":"Edit parameters, preview, save named configurations, then compare or explore.");InvalidateRect(state.window,nullptr,TRUE);} static V tool(V a){a.set("namespace",V::makeStr(state.ns));a.set("expected_revision",V::makeNum(double(state.revision)));auto r=runTool("design_variants",a);if(field(r,"isError").b)throw std::runtime_error(field(r,"structuredContent").dump());return field(r,"structuredContent");} static V args(const char* action){V a=V::makeObj();a.set("action",V::makeStr(action));return a;} static void commit(const V& preview){V a=V::makeObj();a.set("expected_revision",V::makeNum(double(state.revision)));a.set("candidate_id",field(preview,"candidate_id"));const auto r=runTool("doc_apply",a);if(field(r,"isError").b)throw std::runtime_error(field(r,"structuredContent").dump());refresh();} -static void showReport(V report){state.report=std::move(report);state.selectedResult=0;SendMessageW(state.results,LB_RESETCONTENT,0,0);for(const auto& row:field(state.report,"results").arr){const auto& m=field(row,"metrics");std::string label=field(row,"name").str+" | ";if(!field(row,"valid").b)label+="FAILED: "+field(row,"error").str;else{label+=field(m,"width_mm").dump()+" x "+field(m,"depth_mm").dump()+" x "+field(m,"height_mm").dump()+" mm | "+field(m,"volume_mm3").dump()+" mm3 | ";label+=field(m,"mass_available").b?field(m,"mass_kg").dump()+" kg":"mass: assign density";if(!field(row,"feasible").b)label+=" | outside constraints";}add(state.results,label);}if(!field(state.report,"ranked_indices").arr.empty())state.selectedResult=(int)field(state.report,"ranked_indices").arr[0].num;SendMessageW(state.results,LB_SETCURSEL,state.selectedResult,0);message(std::to_string((int)field(state.report,"attempted").num)+" evaluated / "+std::to_string((int)field(state.report,"failed").num)+" failed. Exact metrics; sampled thumbnails are display only.");InvalidateRect(state.window,nullptr,TRUE);} -static void editParameter(){int i=(int)SendMessageW(state.parameters,LB_GETCURSEL,0,0);if(i<0||i>=(int)state.parameterNames.size())return;const auto name=state.parameterNames[i];std::string value=field(state.values,name.c_str()).dump();if(!editText(("Parameter: "+name).c_str(),value))return;bool ok=false;double parsed=evalExpr(trimField(value),g_doc.buildEnv(),&ok);if(!ok||!std::isfinite(parsed))throw std::runtime_error("Enter a finite numeric value");state.values.set(name,V::makeNum(parsed));fillParameters();SendMessageW(state.parameters,LB_SETCURSEL,i,0);message("Value staged; Preview validates the program and exact geometry before Apply.");} +static void showReport(V report,std::string axis={}){state.report=std::move(report);state.axis=std::move(axis);state.selectedResult=0;SendMessageW(state.results,LB_RESETCONTENT,0,0);for(const auto& row:field(state.report,"results").arr){const auto& m=field(row,"metrics");std::string label=resultTitle(row)+" | ";if(!field(row,"valid").b)label+="FAILED: "+field(row,"error").str;else{label+=field(m,"width_mm").dump()+" x "+field(m,"depth_mm").dump()+" x "+field(m,"height_mm").dump()+" mm | "+field(m,"volume_mm3").dump()+" mm3 | ";label+=field(m,"mass_available").b?field(m,"mass_kg").dump()+" kg":"mass: assign density";if(!field(row,"feasible").b)label+=" | outside constraints";}add(state.results,label);}if(!field(state.report,"ranked_indices").arr.empty())state.selectedResult=(int)field(state.report,"ranked_indices").arr[0].num;SendMessageW(state.results,LB_SETCURSEL,state.selectedResult,0);message(std::to_string((int)field(state.report,"attempted").num)+" evaluated / "+std::to_string((int)field(state.report,"failed").num)+" failed. Exact metrics; sampled thumbnails are display only.");InvalidateRect(state.window,nullptr,TRUE);} +static void editParameter(){int i=(int)SendMessageW(state.parameters,LB_GETCURSEL,0,0);if(i<0||i>=(int)state.parameterNames.size())return;const auto name=state.parameterNames[i];const ParameterKind kind=parameterKind(name);const V current=field(state.values,name.c_str());V staged; + if(kind==ParameterKind::Number){std::string value=current.dump();if(!editText(("Parameter: "+name).c_str(),value))return;bool ok=false;double parsed=evalExpr(trimField(value),g_doc.buildEnv(),&ok);if(!ok||!std::isfinite(parsed))throw std::runtime_error("Enter a finite numeric value");staged=V::makeNum(parsed);} + else if(kind==ParameterKind::Boolean)staged=V::makeNum(shownValue(kind,current)=="On"?0:1); + // A choice is taken by its position in the declared list, not by the text the dialog returns. + else{const auto values=declaredValues(kind,name);std::vector labels;for(const auto& value:values)labels.push_back(toDialog(shownValue(kind,value)));int picked=-1;std::vector fields{choiceField(name.c_str(),toDialog(shownValue(kind,current)),labels)};if(!editFields(("Parameter: "+name).c_str(),(std::to_string(values.size())+" declared choices. The value is staged; Preview validates it before Apply.").c_str(),fields,false,"Stage",nullptr,false,[&](const std::vector& controls){picked=(int)SendMessage(controls[0],CB_GETCURSEL,0,0);}))return;if(picked<0||picked>=(int)values.size())throw std::runtime_error("Choose one of the declared values of "+name);staged=values[(size_t)picked];} + state.values.set(name,staged);fillParameters();SendMessageW(state.parameters,LB_SETCURSEL,i,0);message(kind==ParameterKind::Number?std::string("Value staged; Preview validates the program and exact geometry before Apply."):name+" = "+shownValue(kind,staged)+" staged; Preview validates the program and exact geometry before Apply.");} static void loadSaved(){if(!program())throw std::runtime_error("The program was removed. This saved configuration can be inspected or deleted, but cannot be applied.");int i=(int)SendMessageW(state.variants,LB_GETCURSEL,0,0);if(i<0||i>=(int)state.savedNames.size())return;for(const auto& v:g_doc.designVariants.arr)if(field(v,"namespace").str==state.ns&&field(v,"name").str==state.savedNames[i]){if(field(v,"program_sha256").str!=field(*program(),"program_sha256").str)throw std::runtime_error("Program source changed. Review each parameter before creating a new configuration.");state.values=field(v,"values");SetWindowTextW(state.name,wide(state.savedNames[i]).c_str());fillParameters();message("Saved values staged. Preview checks geometry; Apply publishes the selected configuration.");break;}} static void starter(){const V examples=parametricProgramExamples();std::vector fields{{"Example",field(examples.arr.front(),"id").str},{"Namespace","family"}};for(const auto& example:examples.arr)fields[0].choices.push_back(field(example,"id").str);if(!editFields("New parametric family","Installs an editable example with exact native features. Existing designs are preserved.",fields))return;const auto ns=trimField(fields[1].value);V a=V::makeObj();a.set("action",V::makeStr("prepare"));a.set("mode",V::makeStr("install"));a.set("namespace",V::makeStr(ns));a.set("expected_revision",V::makeNum(double(state.revision)));for(const auto& example:examples.arr)if(field(example,"id").str==fields[0].value)a.set("program",field(example,"program"));const auto r=runTool("parametric_program",a);if(field(r,"isError").b)throw std::runtime_error(field(r,"structuredContent").dump());commit(field(r,"structuredContent"));state.ns=ns;refresh();} -static void explore(){const auto* p=program();if(!p)throw std::runtime_error("Install a program first");std::vector fields{{"Parameter",state.parameterNames.empty()?"":state.parameterNames.front()},{"Trial values (comma separated)",""},{"Minimize","volume_mm3"},{"Maximum width mm (optional)",""},{"Maximum depth mm (optional)",""},{"Maximum height mm (optional)",""},{"Maximum mass kg (optional)",""},{"Clearance feature A (optional)",""},{"Clearance feature B (optional)",""},{"Minimum pair gap mm (optional)",""}};fields[0].choices=state.parameterNames;fields[2].choices={"volume_mm3","mass_kg","width_mm","depth_mm","height_mm"};if(!state.parameterNames.empty()){const auto& spec=field(field(*p,"program"),"parameters").obj.front().second;const auto& value=field(state.values,state.parameterNames.front().c_str());fields[1].value=(spec.find("min")?field(spec,"min").dump():value.dump())+", "+value.dump()+", "+(spec.find("max")?field(spec,"max").dump():value.dump());}if(!editFields("Explore parameter alternatives","Every explicit value is evaluated with the exact kernel. Program assertions and entered limits govern feasibility. Failed trials remain visible. No structural or manufacturing claim.",fields))return;V a=args("explore"),axes=V::makeObj(),values=V::makeArr(),constraints=V::makeObj();std::istringstream in(fields[1].value);std::string word;while(std::getline(in,word,',')){bool ok=false;const double number=evalExpr(trimField(word),g_doc.buildEnv(),&ok);if(!ok||!std::isfinite(number))throw std::runtime_error("Trial values must be finite numbers");values.arr.push_back(V::makeNum(number));}axes.set(fields[0].value,values);const char* keys[]={"width_mm","depth_mm","height_mm","mass_kg"};for(int i=0;i<4;++i)if(!trimField(fields[i+3].value).empty()){bool ok=false;const auto value=evalExpr(trimField(fields[i+3].value),g_doc.buildEnv(),&ok);if(!ok||!std::isfinite(value))throw std::runtime_error("Limits must be finite numbers");V range=V::makeObj();range.set("max",V::makeNum(value));constraints.set(keys[i],range);}if(!trimField(fields[7].value).empty()||!trimField(fields[8].value).empty()||!trimField(fields[9].value).empty()){bool ok=false;const double gap=evalExpr(trimField(fields[9].value),g_doc.buildEnv(),&ok);if(!ok||!std::isfinite(gap)||gap<0||trimField(fields[7].value).empty()||trimField(fields[8].value).empty())throw std::runtime_error("Enter both program feature names and a nonnegative minimum gap");V pairs=V::makeArr(),pair=V::makeObj();pair.set("a",V::makeStr(trimField(fields[7].value)));pair.set("b",V::makeStr(trimField(fields[8].value)));pair.set("min_mm",V::makeNum(gap));pairs.arr.push_back(pair);a.set("clearance_pairs",pairs);}a.set("values",state.values);a.set("axes",axes);a.set("constraints",constraints);a.set("objective",V::makeStr(fields[2].value));a.set("thumbnails",V::makeBool(true));showReport(tool(a));} +static void explore(){const auto* p=program();if(!p)throw std::runtime_error("Install a program first");const int listed=(int)SendMessageW(state.parameters,LB_GETCURSEL,0,0);const std::string initial=state.parameterNames.empty()?std::string():state.parameterNames[listed>=0&&listed<(int)state.parameterNames.size()?(size_t)listed:0];std::vector fields{{"Parameter",initial},{"Trial values (comma separated)",""},{"Minimize","volume_mm3"},{"Maximum width mm (optional)",""},{"Maximum depth mm (optional)",""},{"Maximum height mm (optional)",""},{"Maximum mass kg (optional)",""},{"Clearance feature A (optional)",""},{"Clearance feature B (optional)",""},{"Minimum pair gap mm (optional)",""}};fields[0].choices=state.parameterNames;fields[2].choices={"volume_mm3","mass_kg","width_mm","depth_mm","height_mm"};fields[1].value=toDialog(suggestedTrials(initial)); + // Choosing another parameter offers that parameter's own trial values. + std::string offered=initial;if(!editFields("Explore parameter alternatives","Exact kernel evaluation; failed trials stay listed. No trial values: every declared value is tried. No structural or manufacturing claim.",fields,false,"Apply",nullptr,false,[&](const std::vector& controls){char name[160]{};GetWindowTextA(controls[0],name,sizeof name);if(offered==name)return;offered=name;SetWindowTextA(controls[1],toDialog(suggestedTrials(offered)).c_str());}))return;// Offered values of a boolean or choice that were left as offered are the declared values themselves, so text the system code page cannot carry is still explored. + const bool asOffered=parameterKind(fields[0].value)!=ParameterKind::Number&&fields[1].value==toDialog(suggestedTrials(fields[0].value));V a=args("explore"),axes=V::makeObj(),constraints=V::makeObj();axes.set(fields[0].value,trialValues(fields[0].value,asOffered?std::string():fromDialog(fields[1].value)));const char* keys[]={"width_mm","depth_mm","height_mm","mass_kg"};for(int i=0;i<4;++i)if(!trimField(fields[i+3].value).empty()){bool ok=false;const auto value=evalExpr(trimField(fields[i+3].value),g_doc.buildEnv(),&ok);if(!ok||!std::isfinite(value))throw std::runtime_error("Limits must be finite numbers");V range=V::makeObj();range.set("max",V::makeNum(value));constraints.set(keys[i],range);}if(!trimField(fields[7].value).empty()||!trimField(fields[8].value).empty()||!trimField(fields[9].value).empty()){bool ok=false;const double gap=evalExpr(trimField(fields[9].value),g_doc.buildEnv(),&ok);if(!ok||!std::isfinite(gap)||gap<0||trimField(fields[7].value).empty()||trimField(fields[8].value).empty())throw std::runtime_error("Enter both program feature names and a nonnegative minimum gap");V pairs=V::makeArr(),pair=V::makeObj();pair.set("a",V::makeStr(trimField(fields[7].value)));pair.set("b",V::makeStr(trimField(fields[8].value)));pair.set("min_mm",V::makeNum(gap));pairs.arr.push_back(pair);a.set("clearance_pairs",pairs);}a.set("values",state.values);a.set("axes",axes);a.set("constraints",constraints);a.set("objective",V::makeStr(fields[2].value));a.set("thumbnails",V::makeBool(true));showReport(tool(a),fields[0].value);} static void action(int id){if(state.busy)return;state.busy=true;g_error=false;try{if(id!=1&&state.epoch!=g_documentEpoch)throw std::runtime_error("Document changed. Refresh before editing.");if(id!=1&&state.revision!=g_session.revision)throw std::runtime_error("Model revision changed. Refresh and review values before continuing.");if(id==1)refresh();else if(id==2)starter();else if(id==3)editParameter();else if(id==4){V a=args("evaluate");a.set("name",V::makeStr("Staged"));a.set("values",state.values);a.set("thumbnails",V::makeBool(true));showReport(tool(a));}else if(id==5){V a=args("prepare");a.set("values",state.values);commit(tool(a));message("Configuration applied. Undo restores the previous editable source.");}else if(id==6){V a=args("save");a.set("name",V::makeStr(trimField(windowText(state.name))));a.set("values",state.values);const V staged=state.values;commit(tool(a));state.values=staged;fillParameters();message("Named configuration saved in the document; Save the .ark to retain it on disk.");}else if(id==7)loadSaved();else if(id==8){int i=(int)SendMessageW(state.variants,LB_GETCURSEL,0,0);if(i<0||i>=(int)state.savedNames.size())throw std::runtime_error("Select a saved variant");V a=args("remove");a.set("name",V::makeStr(state.savedNames[i]));const V staged=state.values;commit(tool(a));state.values=staged;fillParameters();}else if(id==9){V a=args("evaluate");a.set("thumbnails",V::makeBool(true));showReport(tool(a));}else if(id==10)explore();else if(id==11){int i=(int)SendMessageW(state.results,LB_GETCURSEL,0,0);const auto& rows=field(state.report,"results").arr;if(i<0||i>=(int)rows.size()||!field(rows[i],"valid").b)throw std::runtime_error("Select a valid evaluated result");state.values=field(rows[i],"values");SetWindowTextW(state.name,wide(field(rows[i],"name").str).c_str());fillParameters();message("Result values staged. Save a named variant or Apply to the model.");}}catch(const std::exception& e){g_error=true;message(e.what());}state.busy=false;InvalidateRect(state.window,nullptr,TRUE);} static void text(HDC dc,RECT r,const std::string& s,COLORREF color=RGB(225,228,232)){SetTextColor(dc,color);SetBkMode(dc,TRANSPARENT);DrawTextW(dc,wide(s).c_str(),-1,&r,DT_LEFT|DT_WORDBREAK|DT_END_ELLIPSIS);} -static void thumbnail(HDC dc,RECT r,const V& row){auto brush=CreateSolidBrush(RGB(39,43,49));FillRect(dc,&r,brush);DeleteObject(brush);RECT label{r.left+10,r.top+8,r.right-8,r.top+44};text(dc,label,field(row,"name").asStr(),RGB(255,174,94));const auto& triangles=field(row,"display_triangles").arr;if(triangles.empty()){RECT empty{r.left+10,r.top+50,r.right-10,r.bottom-10};text(dc,empty,field(row,"valid").b?"No display mesh available":field(row,"error").asStr());return;}double loX=1e300,loY=1e300,hiX=-1e300,hiY=-1e300;auto point=[](const V& t,int i){return std::pair{.866*(t.arr[i].num-t.arr[i+1].num),.5*(t.arr[i].num+t.arr[i+1].num)-t.arr[i+2].num};};for(const auto& tri:triangles)if(tri.arr.size()==9)for(int j=0;j<9;j+=3){auto p=point(tri,j);loX=std::min(loX,p.first);hiX=std::max(hiX,p.first);loY=std::min(loY,p.second);hiY=std::max(hiY,p.second);}double scale=std::min((r.right-r.left-28.)/std::max(1.,hiX-loX),(r.bottom-r.top-66.)/std::max(1.,hiY-loY));const double x=r.left+(r.right-r.left-(hiX-loX)*scale)*.5-loX*scale,y=r.top+45+(r.bottom-r.top-55-(hiY-loY)*scale)*.5-loY*scale;auto pen=CreatePen(PS_SOLID,1,RGB(140,154,170));auto fill=CreateSolidBrush(RGB(80,91,107));auto oldP=SelectObject(dc,pen),oldB=SelectObject(dc,fill);std::vector ordered;for(const auto& tri:triangles)if(tri.arr.size()==9)ordered.push_back(&tri);auto depth=[](const V* tri){double z=0;for(const auto& coordinate:tri->arr)z+=coordinate.num;return z;};std::stable_sort(ordered.begin(),ordered.end(),[&](const V* a,const V* b){return depth(a)1e-12?std::clamp((.3*nx+.5*ny+.8*nz)/length,0.,1.):0.;const int shade=(int)(65+65*light);auto faceBrush=CreateSolidBrush(RGB(shade,shade+11,shade+27));auto priorBrush=SelectObject(dc,faceBrush);Polygon(dc,pts,3);SelectObject(dc,priorBrush);DeleteObject(faceBrush);}SelectObject(dc,oldP);SelectObject(dc,oldB);DeleteObject(pen);DeleteObject(fill);} +static void thumbnail(HDC dc,RECT r,const V& row){auto brush=CreateSolidBrush(RGB(39,43,49));FillRect(dc,&r,brush);DeleteObject(brush);RECT label{r.left+10,r.top+8,r.right-8,r.top+44};text(dc,label,resultTitle(row),RGB(255,174,94));const auto& triangles=field(row,"display_triangles").arr;if(triangles.empty()){RECT empty{r.left+10,r.top+50,r.right-10,r.bottom-10};text(dc,empty,field(row,"valid").b?"No display mesh available":field(row,"error").asStr());return;}double loX=1e300,loY=1e300,hiX=-1e300,hiY=-1e300;auto point=[](const V& t,int i){return std::pair{.866*(t.arr[i].num-t.arr[i+1].num),.5*(t.arr[i].num+t.arr[i+1].num)-t.arr[i+2].num};};for(const auto& tri:triangles)if(tri.arr.size()==9)for(int j=0;j<9;j+=3){auto p=point(tri,j);loX=std::min(loX,p.first);hiX=std::max(hiX,p.first);loY=std::min(loY,p.second);hiY=std::max(hiY,p.second);}double scale=std::min((r.right-r.left-28.)/std::max(1.,hiX-loX),(r.bottom-r.top-66.)/std::max(1.,hiY-loY));const double x=r.left+(r.right-r.left-(hiX-loX)*scale)*.5-loX*scale,y=r.top+45+(r.bottom-r.top-55-(hiY-loY)*scale)*.5-loY*scale;auto pen=CreatePen(PS_SOLID,1,RGB(140,154,170));auto fill=CreateSolidBrush(RGB(80,91,107));auto oldP=SelectObject(dc,pen),oldB=SelectObject(dc,fill);std::vector ordered;for(const auto& tri:triangles)if(tri.arr.size()==9)ordered.push_back(&tri);auto depth=[](const V* tri){double z=0;for(const auto& coordinate:tri->arr)z+=coordinate.num;return z;};std::stable_sort(ordered.begin(),ordered.end(),[&](const V* a,const V* b){return depth(a)1e-12?std::clamp((.3*nx+.5*ny+.8*nz)/length,0.,1.):0.;const int shade=(int)(65+65*light);auto faceBrush=CreateSolidBrush(RGB(shade,shade+11,shade+27));auto priorBrush=SelectObject(dc,faceBrush);Polygon(dc,pts,3);SelectObject(dc,priorBrush);DeleteObject(faceBrush);}SelectObject(dc,oldP);SelectObject(dc,oldB);DeleteObject(pen);DeleteObject(fill);} static void layout(){RECT r{};GetClientRect(state.window,&r);const int w=r.right,h=r.bottom,left=350;MoveWindow(state.program,18,48,w-262,300,TRUE);MoveWindow(GetDlgItem(state.window,2),w-232,47,105,28,TRUE);MoveWindow(GetDlgItem(state.window,1),w-117,47,98,28,TRUE);MoveWindow(state.parameters,18,112,left-36,180,TRUE);MoveWindow(GetDlgItem(state.window,3),18,300,102,28,TRUE);MoveWindow(GetDlgItem(state.window,4),128,300,92,28,TRUE);MoveWindow(GetDlgItem(state.window,5),228,300,104,28,TRUE);MoveWindow(state.name,18,363,left-36,25,TRUE);MoveWindow(GetDlgItem(state.window,6),18,397,left-36,28,TRUE);MoveWindow(state.variants,18,465,left-36,std::max(80,h-565),TRUE);MoveWindow(GetDlgItem(state.window,7),18,h-92,147,28,TRUE);MoveWindow(GetDlgItem(state.window,8),176,h-92,156,28,TRUE);MoveWindow(state.results,left+10,112,w-left-28,134,TRUE);MoveWindow(GetDlgItem(state.window,9),left+10,256,150,28,TRUE);MoveWindow(GetDlgItem(state.window,10),left+170,256,150,28,TRUE);MoveWindow(GetDlgItem(state.window,11),left+330,256,174,28,TRUE);MoveWindow(state.status,18,h-51,w-36,42,TRUE);} static LRESULT CALLBACK procedure(HWND w,UINT m,WPARAM wp,LPARAM lp){if(m==WM_CREATE){state.window=w;state.font=CreateFontW(-15,0,0,0,FW_NORMAL,FALSE,FALSE,FALSE,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,L"Segoe UI");auto control=[&](const wchar_t* type,const wchar_t* title,DWORD style,int id){HWND c=CreateWindowExW(type==std::wstring(L"EDIT")||type==std::wstring(L"LISTBOX")?WS_EX_CLIENTEDGE:0,type,title,WS_CHILD|WS_VISIBLE|style,0,0,100,25,w,(HMENU)(INT_PTR)id,GetModuleHandle(nullptr),nullptr);SendMessageW(c,WM_SETFONT,(WPARAM)state.font,TRUE);return c;};state.program=control(L"COMBOBOX",L"",CBS_DROPDOWNLIST|WS_VSCROLL,20);state.parameters=control(L"LISTBOX",L"",LBS_NOTIFY|WS_VSCROLL|WS_HSCROLL,21);state.name=control(L"EDIT",L"Standard",ES_AUTOHSCROLL,22);state.variants=control(L"LISTBOX",L"",LBS_NOTIFY|WS_VSCROLL,23);state.results=control(L"LISTBOX",L"",LBS_NOTIFY|WS_VSCROLL|WS_HSCROLL,24);SendMessageW(state.results,LB_SETHORIZONTALEXTENT,2000,0);state.status=control(L"STATIC",L"",0,25);const wchar_t* labels[]={L"Refresh",L"New family",L"Edit value",L"Preview",L"Apply",L"Save named variant",L"Load values",L"Delete variant",L"Compare saved",L"Explore values",L"Use selected result"};for(int i=0;i<11;++i)control(L"BUTTON",labels[i],BS_PUSHBUTTON|WS_TABSTOP,i+1);SetTimer(w,1,500,nullptr);return 0;}if(m==WM_SIZE){layout();InvalidateRect(w,nullptr,TRUE);return 0;}if(m==WM_GETMINMAXINFO){auto* info=(MINMAXINFO*)lp;info->ptMinTrackSize={960,680};return 0;}if(m==WM_COMMAND){const int id=LOWORD(wp),event=HIWORD(wp);if(id<=11&&event==BN_CLICKED){action(id);return 0;}if(id==20&&event==CBN_SELCHANGE){int i=(int)SendMessageW(state.program,CB_GETCURSEL,0,0);if(i>=0&&i<(int)state.programNames.size()){state.ns=state.programNames[i];refresh();}return 0;}if(id==21&&event==LBN_DBLCLK){action(3);return 0;}if(id==23&&event==LBN_DBLCLK){action(7);return 0;}if(id==24&&event==LBN_SELCHANGE){state.selectedResult=(int)SendMessageW(state.results,LB_GETCURSEL,0,0);InvalidateRect(w,nullptr,TRUE);return 0;}}if(m==WM_TIMER){if(!state.busy&&(state.revision!=g_session.revision||state.epoch!=g_documentEpoch))message("Model changed. Refresh and review the current parameters before applying a configuration.");return 0;}if(m==WM_PAINT){PAINTSTRUCT ps{};HDC dc=BeginPaint(w,&ps);RECT r{};GetClientRect(w,&r);auto brush=CreateSolidBrush(RGB(27,30,35));FillRect(dc,&r,brush);DeleteObject(brush);auto old=SelectObject(dc,state.font);text(dc,{18,14,r.right-18,40},"Design variants / configure, compare and explore",RGB(255,174,94));text(dc,{18,87,330,108},"Program parameters");text(dc,{360,87,r.right-18,108},"Exact comparison results");text(dc,{18,337,330,360},"Variant name");text(dc,{18,439,330,462},"Saved configurations");const auto& rows=field(state.report,"results").arr;const int count=std::min(3,(int)rows.size()),cardWidth=(r.right-378)/3;int start=std::max(0,std::min(state.selectedResult-1,(int)rows.size()-count));for(int i=0;i=0&&r.right<=client.right&&r.top>=0&&r.bottom<=client.bottom,"Configurator control outside window: "+std::to_string(id));} const auto persisted=shotPath+".variants.ark";check(saveDocument(g_doc,persisted.c_str()),"Save variants document failed");Document loaded;std::string error;check(loadDocument(persisted.c_str(),loaded,&error),error);check(loaded.designVariants.arr.size()==3,"Saved variant configurations lost on reopen"); - DestroyWindow(state.window);g_busyTestMode=oldBusyTest;std::ofstream(shotPath+".variants-test.log")<<"PASS three named variants, exact preview, comparison thumbnails, apply/undo, stale rejection, numeric edit, exploration failures, compact controls, persistence\n";return 0; + // Typed parameters: a boolean, a numeric choice and a text choice are staged from the window's + // own controls, previewed, applied, saved, compared and explored. One listed text holds a + // comma, one holds an accent, which the shared dialog carries in the system code page, and + // one holds a letter outside the Western code page, which is picked by position. + stage("typed-install");SetWindowPos(state.window,nullptr,0,0,1160,780,SWP_NOMOVE|SWP_NOZORDER);const std::string steel="a\xC3\xA7o",omega="\xCE\xA9mega"; + V tray=json(R"JSON({"action":"prepare","mode":"install","namespace":"tray","program":{"format":"ark.parametric-program.v1","name":"Tray family","parameters":{"width":{"default":80,"min":40,"max":200,"unit":"mm"},"pegs":{"choices":[2,4,6],"default":4,"description":"Mounting pegs"},"rail":{"boolean":true,"default":false,"description":"Use the tall rail"},"finish":{"choices":["matte","satin","gloss","oak, oiled","a\u00e7o","\u03a9mega"],"default":"satin","description":"Surface finish"}},"body":[{"emit":{"op":"feature.add","type":"native_solid","name":"Plate {@finish}","native":{"op":"box"},"p":{"width":"{width}","depth":30,"height":"{3+finish}"}}},{"emit":{"op":"feature.add","type":"native_solid","name":"Rail","native":{"op":"box"},"p":{"width":"{width}","depth":4,"height":"{rail ? 12 : 6}"}}},{"for":"i","count":"pegs","body":[{"emit":{"op":"feature.add","type":"native_solid","name":"Peg {i+1}","native":{"op":"box"},"p":{"width":4,"depth":4,"height":10}}}]}]}})JSON"); + tray.set("expected_revision",V::makeNum(double(g_session.revision)));const auto trayPrepared=runTool("parametric_program",tray);check(!field(trayPrepared,"isError").b,trayPrepared.dump());{V a=V::makeObj();a.set("candidate_id",field(field(trayPrepared,"structuredContent"),"candidate_id"));a.set("expected_revision",V::makeNum(double(g_session.revision)));runTool("doc_apply",a);check(!g_error,g_status);} + press(1);{int index=-1;for(size_t i=0;i=0,"Tray program is not listed");SendMessageW(state.program,CB_SETCURSEL,index,0);SendMessageW(state.window,WM_COMMAND,MAKEWPARAM(20,CBN_SELCHANGE),(LPARAM)state.program);} + check(state.ns=="tray"&&state.parameterNames.size()==4,"Tray program was not selected with its four parameters"); + auto select=[&](const char* name){for(size_t i=0;iclient.right,"A row wider than the parameter list cannot be scrolled into view");} + stage("typed-edit");select("finish");g_dialogSmoke=3;g_dialogShot=shotPath+".typed-choice-dialog.png";g_dialogOverrideQueue={{"gloss"}};press(3);g_dialogSmoke=0;g_dialogShot.clear();check(!g_error&&staged("finish").t==V::Str&&staged("finish").str=="gloss"&&g_status.find("finish = gloss staged")!=std::string::npos,"The choice list did not stage the picked text: "+g_status); + const bool accents=fromDialog(toDialog(steel))==steel;if(accents){choose("finish",toDialog(steel));check(staged("finish").str==steel&&row("finish")==widen("finish = "+steel)+finishList,"An accented choice was not staged as its listed text");} + choose("finish","oak, oiled");check(staged("finish").str=="oak, oiled","A listed text holding a comma was not staged"); + choose("finish",toDialog(omega));check(staged("finish").str==omega,"A choice was not staged by its position in the declared list");choose("finish","gloss"); + select("rail");press(3);check(!g_error&&staged("rail").t==V::Num&&staged("rail").num==1&&g_status.find("rail = On staged")!=std::string::npos,"Edit value did not switch the boolean on: "+g_status); + choose("pegs","6");check(staged("pegs").t==V::Num&&staged("pegs").num==6,"The choice list did not stage the picked number"); + check(row("finish")==L"finish = gloss"+finishList&&row("rail")==L"rail = On [Off, On]"&&row("pegs")==L"pegs = 6 [2, 4, 6]","Staged typed values are not shown in the parameter rows: "+shownRows()); + const double glossVolume=80.*30*5+80.*4*12+6*160.,matteVolume=80.*30*3+80.*4*6+2*160.; + auto about=[](double value,double expected){return std::fabs(value-expected)<=std::fabs(expected)*1e-9;}; + stage("typed-preview");const auto typedRevision=g_session.revision;press(4);check(!g_error,g_status);{const auto& rows=field(state.report,"results").arr;check(rows.size()==1,"Typed preview did not produce one row");check(field(rows[0],"valid").b,"Typed preview failed: "+field(rows[0],"error").asStr());const auto& m=field(rows[0],"metrics");check(about(field(m,"volume_mm3").num,glossVolume)&&about(field(m,"height_mm").num,12)&&about(field(m,"width_mm").num,80),"Preview metrics do not follow the staged choices: "+m.dump());} + check(g_session.revision==typedRevision,"Preview published the typed configuration");capture(".typed.png"); + stage("typed-apply");press(5);check(!g_error&&g_session.revision==typedRevision+1,"Apply did not publish the typed configuration as one revision: "+g_status); + auto binding=[&]()->const V&{for(const auto& p:g_doc.parametricPrograms.arr)if(field(p,"namespace").str=="tray")return field(p,"values");throw std::runtime_error("Tray binding missing");}; + auto named=[&](const std::string& prefix){int n=0;for(const auto& f:g_doc.features)if(f.name.rfind(prefix,0)==0)++n;return n;}; + check(field(binding(),"finish").t==V::Str&&field(binding(),"finish").str=="gloss"&&field(binding(),"rail").num==1&&field(binding(),"pegs").num==6&&named("tray / Peg ")==6&&named("tray / Plate gloss")==1&&named("tray / Plate satin")==0,"Applied values or generated objects differ from the staged choices: "+binding().dump()); + stage("typed-save");SetWindowTextW(state.name,L"Gloss railed");press(6);check(!g_error,g_status); + choose("finish","matte");select("rail");press(3);check(staged("rail").num==0&&g_status.find("rail = Off staged")!=std::string::npos,"Edit value did not switch the boolean off: "+g_status);choose("pegs","2");SetWindowTextW(state.name,L"Matte plain");press(6);check(!g_error,g_status); + {int typed=0;for(const auto& v:g_doc.designVariants.arr)if(field(v,"namespace").str=="tray"){++typed;const auto& values=field(v,"values");const bool gloss=field(v,"name").str=="Gloss railed";check(field(values,"finish").t==V::Str&&field(values,"finish").str==(gloss?"gloss":"matte")&&field(values,"rail").num==(gloss?1:0)&&field(values,"pegs").num==(gloss?6:2),"A saved typed configuration differs from its staged values: "+values.dump());}check(typed==2,"Two typed configurations were not saved");} + stage("typed-compare");const auto comparedRevision=g_session.revision;press(9);check(!g_error,g_status);{const auto& rows=field(state.report,"results").arr;check(rows.size()==2,"Compare did not evaluate both typed configurations");for(const auto& r:rows){check(field(r,"valid").b,"A typed configuration failed: "+field(r,"error").asStr());check(about(field(field(r,"metrics"),"volume_mm3").num,field(r,"name").str=="Gloss railed"?glossVolume:matteVolume),"A compared volume does not follow its saved choices: "+field(r,"metrics").dump());}} + {int index=-1;for(size_t i=0;i=0,"Saved typed configuration is not listed");SendMessageW(state.variants,LB_SETCURSEL,index,0);press(7);check(!g_error&&staged("finish").str=="gloss"&&staged("rail").num==1&&staged("pegs").num==6,"Load values did not stage the saved typed configuration: "+g_status);} + // Explore: a listed text with a comma is one trial, an unlisted text stays a failed trial, and + // each result row names the value it tried. + stage("typed-explore");auto explore=[&](const char* selected,std::vector overrides){select(selected);g_dialogSmoke=3;g_dialogOverrideQueue.clear();if(!overrides.empty())g_dialogOverrideQueue.push_back(std::move(overrides));press(10);g_dialogSmoke=0;}; + auto tried=[&](size_t i,const char* name)->const V&{return field(field(field(state.report,"results").arr.at(i),"values"),name);}; + explore("finish",{"finish","gloss, oak, oiled, walnut"});check(!g_error,g_status);check(field(state.report,"attempted").num==3&&field(state.report,"failed").num==1,"Text exploration did not keep three trials with one failure"); + check(tried(0,"finish").str=="gloss"&&tried(1,"finish").str=="oak, oiled"&&field(field(state.report,"results").arr[1],"valid").b&&tried(2,"finish").str=="walnut"&&!field(field(state.report,"results").arr[2],"valid").b,"Text trial values were not read as listed texts"); + check(listText(state.results,1).find(L"Trial 2 (finish = oak, oiled) | ")==0&&listText(state.results,2).find(L"Trial 3 (finish = walnut) | FAILED")==0,"Exploration rows do not name the value they tried");capture(".typed-explore.png"); + SendMessageW(state.results,LB_SETCURSEL,1,0);press(11);check(!g_error&&staged("finish").str=="oak, oiled","Use selected result did not stage the explored text"); + explore("finish",{"finish",""});check(!g_error&&field(state.report,"attempted").num==6&&field(state.report,"failed").num==0&&tried(4,"finish").str==steel&&tried(5,"finish").str==omega&&field(state.report,"ranked_indices").arr.at(0).num==0,"No trial values did not try every declared text: "+g_status); + // The dialog opens on the selected row with that row's own trial values, which read back as + // the declared values; choosing another parameter offers that parameter's values instead. + g_dialogShot=shotPath+".typed-explore-dialog.png";explore("finish",{});g_dialogShot.clear();check(!g_error&&field(state.report,"attempted").num==6&&field(state.report,"failed").num==0&&tried(3,"finish").str=="oak, oiled"&&tried(4,"finish").str==steel&&tried(5,"finish").str==omega,"The offered text trial values were not explored as the declared texts: "+g_status); + explore("pegs",{});check(!g_error&&field(state.report,"attempted").num==3&&tried(0,"pegs").num==2&&tried(2,"pegs").num==6,"The dialog did not offer the declared numeric choices of the selected row: "+g_status); + explore("finish",{"rail"});check(!g_error&&field(state.report,"attempted").num==2&&tried(0,"rail").num==0&&tried(1,"rail").num==1&&listText(state.results,1).find(L"Trial 2 (rail = On) | ")==0,"Choosing another parameter did not offer its own trial values: "+g_status); + explore("rail",{"rail","on, FALSE"});check(!g_error&&field(state.report,"attempted").num==2&&tried(0,"rail").num==1&&tried(1,"rail").num==0,"Boolean trial words were not read: "+g_status); + explore("pegs",{"pegs","2, 5"});check(!g_error&&field(state.report,"attempted").num==2&&field(state.report,"failed").num==1,"An unlisted numeric choice was not kept as a failed trial: "+g_status); + if(accents){explore("finish",{"finish",toDialog(steel+", matte")});check(!g_error&&field(state.report,"failed").num==0&&tried(0,"finish").str==steel,"An accented trial text was not read as its listed text: "+g_status);} + explore("rail",{"rail","maybe"});check(g_error&&g_status.find("Trial values of rail are On or Off")!=std::string::npos,"A word that is not On or Off was accepted as a boolean trial: "+g_status);g_error=false; + check(g_session.revision==comparedRevision,"Comparing or exploring typed parameters published geometry"); + {const auto typedFile=shotPath+".typed.ark";check(saveDocument(g_doc,typedFile.c_str()),"Save typed variants document failed");Document reopened;std::string why;check(loadDocument(typedFile.c_str(),reopened,&why),why);int typed=0;for(const auto& v:reopened.designVariants.arr)if(field(v,"namespace").str=="tray"&&field(field(v,"values"),"finish").t==V::Str)++typed;check(reopened.designVariants.arr.size()==5&&typed==2,"Saved text values were lost on reopen");} + DestroyWindow(state.window);g_busyTestMode=oldBusyTest;std::ofstream(shotPath+".variants-test.log")<<"PASS three named variants, exact preview, comparison thumbnails, apply/undo, stale rejection, numeric edit, exploration failures, compact controls, persistence; typed parameters: boolean switch, numeric and text choice lists, comma and accented texts, preview/apply/save/compare, typed exploration with named trials"<<(accents?"":" (accented text not exercised: the system code page cannot carry it)")<<"\n";return 0; }catch(const std::exception& e){g_dialogSmoke=0;g_dialogOverrideQueue.clear();if(state.window)DestroyWindow(state.window);g_busyTestMode=oldBusyTest;std::ofstream(shotPath+".variants-test.log")<<"FAIL "<