From 9cd4e2c7d9be01d91b22c23b511d7a3bc9cc94c8 Mon Sep 17 00:00:00 2001 From: Wengao Liu Date: Tue, 24 Nov 2026 21:13:07 +0800 Subject: [PATCH] fix(#1935): size a loop box from its body's bounds relative to the loop A loop written by 'create microflow' got its Size from its body's ABSOLUTE canvas coordinates: moving the loop 600px right grew the box by exactly 600 (body at 600,300 -> 710;380; at 1200,300 -> 1310;380), and the centred box swallowed its neighbours - MPR008/MPR011 then blamed the neighbourhood. Rebuilt flows kept the sticky wrong size (mendixlabs/mxcli#1935). Root cause: @position is a canvas coordinate everywhere in the language, but a loop's ObjectCollection stores children relative to the loop's top-left frame. The builder filed the authored value raw, fitContainerSize measured those canvas values, and Studio Pro drew the child shifted inside the frame. One contract, both directions - canvas in the language, frame in storage: - builder: addStatement records the consumed canvas @position per built object (save/restored across nested dispatches so an IF's branches do not wipe the split's); @merge-positioned merges join the canvas family in container bodies; the container's finalize translates them into its frame once the box size is final, and re-derives enum-split tail sides whose creation-time comparison mixed spaces. - sizing: fitContainerSizeWithAuthored bounds the box around the loop's own anchor (authored centre sized symmetrically, flow-placed loops grow from their pinned edge), so the box depends on where the body sits RELATIVE to the loop, never on where the loop sits on the canvas. - describer: emission adds the frame back on @position/@merge inside loop bodies (ExecContext.describeFrameOrigin), keeping describe->exec byte-identical for Studio Pro and mxcli-authored flows alike. - splice: storedLocator.within, pinBody and storedLoopStatement translate the other way, so create or modify keeps addressing loop bodies. Old scripts' stored loop geometry changes on re-exec - that is the fix: the sticky wrong box heals on rebuild. Auto-placed bodies (#884) and explicit @size overrides (#2369) keep their contracts. Test: mdl/executor/issue1935_loop_box_test.go (box independent of loop position for loop and while; child stored relative to the frame; the auto-placed and @size contracts kept). Verified end to end on 11.12.4: bson dump of the issue's own repro stores 220;360 for both loops and 110;280 for both children, describe->exec reports Unchanged, mx check and lint stay quiet. --- ...oop-box-sized-from-canvas-coordinates.json | 1 + cmd/mxcli/syntax/features_microflow.go | 6 + mdl/executor/cmd_flow_modify.go | 36 ++++- mdl/executor/cmd_microflows_builder.go | 36 ++++- .../cmd_microflows_builder_actions.go | 7 + .../cmd_microflows_builder_control.go | 86 +++++++++++- mdl/executor/cmd_microflows_builder_flows.go | 6 + mdl/executor/cmd_microflows_builder_graph.go | 46 +++++++ .../cmd_microflows_builder_nested_test.go | 19 +++ mdl/executor/cmd_microflows_merge_test.go | 2 +- mdl/executor/cmd_microflows_show_helpers.go | 42 +++++- mdl/executor/exec_context.go | 8 ++ mdl/executor/flow_splice_loop_body.go | 19 ++- mdl/executor/issue1935_loop_box_test.go | 120 +++++++++++++++++ mdl/executor/layout.go | 124 ++++++++++++++++++ 15 files changed, 537 insertions(+), 21 deletions(-) create mode 100644 .claude/skills/fix-issue/findings/mdl-executor/2026-11-24-loop-box-sized-from-canvas-coordinates.json create mode 100644 mdl/executor/issue1935_loop_box_test.go diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-11-24-loop-box-sized-from-canvas-coordinates.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-24-loop-box-sized-from-canvas-coordinates.json new file mode 100644 index 0000000000..8a152bcede --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-24-loop-box-sized-from-canvas-coordinates.json @@ -0,0 +1 @@ +{"area": "mdl/executor", "date": "2026-11-24", "symptom": "A loop written by `create microflow` got its box Size from its body's ABSOLUTE canvas coordinates, so moving the loop 600px right grew the box by exactly 600 (body at 600,300 -> 710;380; at 1200,300 -> 1310;380, the issue's own numbers), and the centred box swallowed its neighbours. MPR008/MPR011 then blamed the neighbourhood.", "cause": "Three coordinate spaces met in one loop body. @position is a canvas coordinate everywhere in the language, but a loop's ObjectCollection stores children relative to the loop's top-left frame; addStatement filed the authored value raw, fitContainerSize measured those canvas values, and Studio Pro drew the child at canvas offset inside the frame. The box then grew with where the loop sat.", "file": "mdl/executor/cmd_microflows_builder_graph.go (addStatement records the consumed canvas @position per built object; save/restore across nested dispatches so an IF's branches do not wipe the split's), mdl/executor/cmd_microflows_builder_control.go (fitContainerSizeWithAuthored bounds the box around the loop's own anchor; finalize translates authored children and re-derives mergeSideFor tail sides), mdl/executor/layout.go, cmd_microflows_show_helpers.go (describe adds the frame back on @position/@merge inside loop bodies via ExecContext.describeFrameOrigin), cmd_flow_modify.go (storedLocator.within translates; pinBody; storedLoopStatement composes origins), flow_splice_loop_body.go", "fix": "Canvas in, frame stored: authored children and @merge-positioned merges are recorded per ID and translated into the frame at the container's finalize; describe adds the frame back on emission so describe->exec stays byte-identical for both Studio Pro and mxcli-authored flows; the splice locator, pinBody and storedLoopStatement translate the other way; enum-split tail sides are re-derived at finalize when the creation-time comparison mixed spaces.", "insight": "A stored-space change radiates to every consumer of the convention: builder, describer, splice locator, pin sets, storedLoopStatement, and flow siding that reads objectPosition mid-build. Fix it as one contract (canvas in the language, frame in storage, translate at the boundary in both directions) rather than patching consumers one by one. Geometry comparisons during the build (mergeSideFor via objectPosition) must run on final positions - derive sides at finalize, not creation, or the side depends on which space each operand was in at creation time. mxcli-authored loop children stored canvas-raw before, so old scripts' stored geometry CHANGES on re-exec (and that is the fix: the sticky wrong box from the issue heals on rebuild).", "refs": ["mendixlabs/mxcli#1935", "#884", "ako/mxcli#2369", "#1832", "#1693", "#750"], "test": "mdl/executor/issue1935_loop_box_test.go (box independent of loop position for loop and while; child stored relative to frame; auto-placed and @size contracts kept)"} diff --git a/cmd/mxcli/syntax/features_microflow.go b/cmd/mxcli/syntax/features_microflow.go index 13745932b8..604d5b9687 100644 --- a/cmd/mxcli/syntax/features_microflow.go +++ b/cmd/mxcli/syntax/features_microflow.go @@ -1023,6 +1023,12 @@ func init() { "pixel offset from its end of the line. (0, 0) at both ends is straight.\n" + "@position on a split belongs to the SPLIT, so its end-if join has its own\n" + "annotation. Container Size is still computed, not authorable.\n\n" + + "@position and @merge are CANVAS coordinates everywhere, inside a loop body\n" + + "too: state where the statement sits on the flow's canvas, and the loop box\n" + + "is sized from the body's bounds RELATIVE to the loop, so moving the loop\n" + + "never changes its box (mendixlabs/mxcli#1935). DESCRIBE prints those\n" + + "statements in canvas coordinates as well; what Mendix stores inside the\n" + + "box is the loop's own business.\n\n" + "WITHOUT @position the builder places everything. The main line runs left to\n" + "right and wraps onto a new row past 2880px; the line joining two rows leaves\n" + "the bottom of one and arrives on top of the next. A guard (if … return; end\n" + diff --git a/mdl/executor/cmd_flow_modify.go b/mdl/executor/cmd_flow_modify.go index 5072d55360..9e45254c2c 100644 --- a/mdl/executor/cmd_flow_modify.go +++ b/mdl/executor/cmd_flow_modify.go @@ -1677,7 +1677,10 @@ func bodyRefusal(lc mfmutator.Candidate, at ast.MicroflowStatement, why string) // its nodes are drawn at, in the loop box's coordinates: each statement's // @position and its notes' positions. Making room in that body then moves no // node away from where the script draws it — under mdl 1, as at top level -// (statedPoints). +// (statedPoints). The locator's frame origin is the box's canvas origin +// (within), and the language's @position is a canvas coordinate (#1935), so +// position pins are translated into the box; a note's position: is stated in +// the box's own coordinates and pins as stored. func (pd *patchDiff) pinBody(loop model.ID, declared []ast.MicroflowStatement) { for _, st := range declared { ann := statementAnnotations(st) @@ -1685,7 +1688,11 @@ func (pd *patchDiff) pinBody(loop model.ID, declared []ast.MicroflowStatement) { continue } if ann.Position != nil { - pd.bodyPins = append(pd.bodyPins, bodyPin{loop: loop, at: model.Point{X: ann.Position.X, Y: ann.Position.Y}}) + at := model.Point{X: ann.Position.X, Y: ann.Position.Y} + if pd.loc != nil && pd.loc.inFrame { + at = model.Point{X: at.X - pd.loc.frameOrigin.X, Y: at.Y - pd.loc.frameOrigin.Y} + } + pd.bodyPins = append(pd.bodyPins, bodyPin{loop: loop, at: at}) } for _, n := range ann.Notes { if n.Position != nil { @@ -2058,6 +2065,12 @@ func lcsStatements(declared, stored []ast.MicroflowStatement) [][2]int { type storedLocator struct { byPos map[model.Point][]mfmutator.Candidate cands []mfmutator.Candidate + // frameOrigin is the canvas coordinate of this collection's frame origin, + // set by within for a loop body: the language's @position is a canvas + // coordinate, describe emits it as one, and the stored body keeps frame + // coordinates — locate translates (#1935). Top level keeps raw canvas. + frameOrigin model.Point + inFrame bool } func newStoredLocator(a *alterFlowContext) *storedLocator { @@ -2065,10 +2078,18 @@ func newStoredLocator(a *alterFlowContext) *storedLocator { } // within is the locator of a stored loop's body: describe prints a body -// statement's @position relative to the loop box, unique among the body's -// own objects but not across the flow. +// statement's @position on the canvas, while the stored body keeps positions +// relative to the loop box (#1935) — locate translates by the box's canvas +// origin. The body's coordinates are unique among the body's own objects but +// not across the flow, which is why the body gets its own locator. func (l *storedLocator) within(loop *microflows.LoopedActivity) *storedLocator { - return locatorOver(l.cands, loop.ObjectCollection) + inner := locatorOver(l.cands, loop.ObjectCollection) + inner.frameOrigin = model.Point{ + X: l.frameOrigin.X + loop.Position.X - loop.Size.Width/2, + Y: l.frameOrigin.Y + loop.Position.Y - loop.Size.Height/2, + } + inner.inFrame = true + return inner } func locatorOver(cands []mfmutator.Candidate, oc *microflows.MicroflowObjectCollection) *storedLocator { @@ -2094,6 +2115,11 @@ func (l *storedLocator) locate(st ast.MicroflowStatement) (mfmutator.Candidate, return mfmutator.Candidate{}, cannotSplice("the stored statement %q has no activity to address (a join, merge or end of a branch)", statementKind(st)) } p := model.Point{X: ann.Position.X, Y: ann.Position.Y} + if l.inFrame { + // The script speaks canvas coordinates; the stored body speaks + // frame-relative ones (#1935). + p = model.Point{X: p.X - l.frameOrigin.X, Y: p.Y - l.frameOrigin.Y} + } switch cs := l.byPos[p]; len(cs) { case 1: return cs[0], nil diff --git a/mdl/executor/cmd_microflows_builder.go b/mdl/executor/cmd_microflows_builder.go index 8be99934b9..ab770bf186 100644 --- a/mdl/executor/cmd_microflows_builder.go +++ b/mdl/executor/cmd_microflows_builder.go @@ -141,9 +141,34 @@ type flowBuilder struct { // quiet silences the builder's own stderr warnings. Set for describe's // layout check (derivedFlowLayout), which rebuilds a flow it only reads and // must not repeat, once per round, a warning nobody asked for. - quiet bool - hierarchy *ContainerHierarchy // For resolving container IDs to module names - pendingAnnotations *ast.ActivityAnnotations // Pending annotations to attach to next activity + quiet bool + hierarchy *ContainerHierarchy // For resolving container IDs to module names + pendingAnnotations *ast.ActivityAnnotations // Pending annotations to attach to next activity + // pendingAuthoredPos holds the canvas @position the statement being built + // consumed, until the dispatch produces the object's ID; addStatement then + // files it into authoredPos. A loop's ObjectCollection stores positions + // relative to the loop's own frame, so these canvas values are translated + // into the frame of the collection that holds them once every container + // has its final size (#1935). Top-level objects keep canvas coordinates + // and are never translated. + pendingAuthoredPos *model.Point + // authoredPos maps a built object to the canvas @position its statement + // authored. Nested builders hand theirs up alongside their objects, so the + // root builder holds the whole table when the translation pass runs. + authoredPos map[model.ID]model.Point // canvas @position per built object + // sidedTails are enum-split tail flows whose destination side mergeSideFor + // derived from body geometry. A container's finalize re-derives them after + // the hand-placed children hold their frame positions, because during the + // build that comparison can read two coordinate spaces at once (#1935). + sidedTails []*microflows.SequenceFlow + // containerCursor is the frame-space line an inContainer builder's + // auto-placed statements continue on, saved across an authored statement's + // canvas detour (see addStatement). + containerCursorX, containerCursorY int + // inContainer marks a builder whose objects are stored inside a + // container's ObjectCollection (a loop body) rather than on the + // microflow's canvas. + inContainer bool restServices []*model.ConsumedRestService // Cached REST services for parameter classification listInputVariables map[string]bool // Variables later consumed by list-only actions objectInputVariables map[string]bool // Variables later consumed through object/attribute access @@ -242,6 +267,11 @@ func (fb *flowBuilder) nestedBuilder(x, y int) *flowBuilder { posY: y, baseY: y, spacing: HorizontalSpacing, + // A nested builder's objects live in a container's frame, so its + // cursor stays frame-relative: an authored canvas @position places + // that one object and does not drag the auto-placed line that + // follows it out of the frame (#1935). + inContainer: true, varTypes: fb.varTypes, // one variable scope declaredVars: fb.declaredVars, // (fixes a nil map panic) diff --git a/mdl/executor/cmd_microflows_builder_actions.go b/mdl/executor/cmd_microflows_builder_actions.go index 3da63c978d..c7103e0073 100644 --- a/mdl/executor/cmd_microflows_builder_actions.go +++ b/mdl/executor/cmd_microflows_builder_actions.go @@ -589,6 +589,7 @@ func (fb *flowBuilder) addEnumSplit(s *ast.EnumSplitStmt) model.ID { }, } fb.objects = append(fb.objects, merge) + fb.noteAuthoredMerge(merge, s.Annotations) } return merge } @@ -784,6 +785,11 @@ func (fb *flowBuilder) addEnumSplit(s *ast.EnumSplitStmt) model.ID { } if origins != nil { tail.DestinationConnectionIndex = mergeSideFor(fb.objectPosition(lastID), fb.objectPosition(ensureMerge().ID)) + // The side is re-derived at the container's finalize, once every + // hand-placed child holds its frame position (#1935): during the + // build this comparison can read a canvas coordinate against a + // frame one, and the final geometry is what the side must match. + fb.sidedTails = append(fb.sidedTails, tail) } if column != nil { tail.OriginConnectionIndex, tail.DestinationConnectionIndex = AnchorRight, AnchorBottom @@ -1049,6 +1055,7 @@ func (fb *flowBuilder) addStructuredInheritanceSplit(s *ast.InheritanceSplitStmt }, } fb.objects = append(fb.objects, merge) + fb.noteAuthoredMerge(merge, s.Annotations) for _, tail := range branchTails { if tail.fromSplit { var flow *microflows.SequenceFlow diff --git a/mdl/executor/cmd_microflows_builder_control.go b/mdl/executor/cmd_microflows_builder_control.go index 32148e34b5..43d4e4665a 100644 --- a/mdl/executor/cmd_microflows_builder_control.go +++ b/mdl/executor/cmd_microflows_builder_control.go @@ -169,6 +169,7 @@ func (fb *flowBuilder) addIfStatement(s *ast.IfStmt) model.ID { }, } fb.objects = append(fb.objects, merge) + fb.noteAuthoredMerge(merge, s.Annotations) mergeID = merge.ID } if needMerge { @@ -807,9 +808,16 @@ func (fb *flowBuilder) addLoopStatement(s *ast.LoopStmt) model.ID { } // Size the box from the children that were actually built, not from the - // statement count measured before the body existed (#884 problem 1). Recompute - // the centre too: the width just changed under it. - loopWidth, loopHeight = fitContainerSize(loopBuilder.objects, innerStartX, MinLoopWidth, MinLoopHeight) + // statement count measured before the body existed (#884 problem 1). + // Hand-placed children bound the box around this loop's own anchor so it + // does not grow with canvas position (#1935). Recompute the centre too: + // the width just changed under it. + anchorX, symmetricX := loopLeftX, false + if s.Annotations != nil && s.Annotations.Position != nil { + anchorX, symmetricX = s.Annotations.Position.X, true + } + loopWidth, loopHeight = fitContainerSizeWithAuthored( + loopBuilder.objects, loopBuilder.authoredPos, symmetricX, anchorX, fb.posY, MinLoopWidth, MinLoopHeight) if s.Annotations != nil && s.Annotations.Size != nil && s.Annotations.Size.Width > 0 && s.Annotations.Size.Height > 0 { // The box Studio Pro stored, @size(w, h) (ako/mxcli#2369). loopWidth, loopHeight = s.Annotations.Size.Width, s.Annotations.Size.Height @@ -820,6 +828,36 @@ func (fb *flowBuilder) addLoopStatement(s *ast.LoopStmt) model.ID { loopLeftX = loopCenterX - loopWidth/2 } + // Children that carry a canvas @position are stored frame-relative — a + // loop's ObjectCollection positions its children from the box's top-left + // corner (#1935) — and every geometry decision the rest of the build makes + // about them (flow siding, box growth) reads this list, so they must hold + // frame values from here on, not after some post-pass. The frame is final: + // fitContainerSizeWithAuthored bounded it and @size may have overridden + // it. The post-pass in buildFlowGraph repeats the same arithmetic for what + // this loop cannot see here — its own centre, when the loop is itself a + // child of another body. + frameLeft, frameTop := loopLeftX, fb.posY-loopHeight/2 + for _, obj := range loopBuilder.objects { + if obj == nil { + continue + } + if a, ok := loopBuilder.authoredPos[obj.GetID()]; ok { + obj.SetPosition(model.Point{X: a.X - frameLeft, Y: a.Y - frameTop}) + } + } + // Re-derive the enum-split tail sides from the final frame geometry: the + // creation-time comparison read hand-placed children in canvas coordinates + // against auto-placed ones in frame coordinates (#1935). Both ends hold + // their stored positions now, which is the geometry the side must match. + for _, st := range loopBuilder.sidedTails { + origin, dest := loopBuilder.objectByID(st.OriginID), loopBuilder.objectByID(st.DestinationID) + if origin == nil || dest == nil { + continue + } + st.DestinationConnectionIndex = mergeSideFor(origin.GetPosition(), dest.GetPosition()) + } + // Create LoopedActivity with calculated size // Position is the CENTER point (RelativeMiddlePoint in Mendix) loop := µflows.LoopedActivity{ @@ -862,6 +900,12 @@ func (fb *flowBuilder) addLoopStatement(s *ast.LoopStmt) model.ID { // dropped on the floor, so exec reported success on a flow it had silently // written wrong (#1077). fb.errors = append(fb.errors, loopBuilder.errors...) + for id, p := range loopBuilder.authoredPos { + if fb.authoredPos == nil { + fb.authoredPos = map[model.ID]model.Point{} + } + fb.authoredPos[id] = p + } if fb.annotationsByLabel == nil { fb.annotationsByLabel = loopBuilder.annotationsByLabel } @@ -1164,8 +1208,14 @@ func (fb *flowBuilder) addWhileStatement(s *ast.WhileStmt) model.ID { whileExpr := fb.exprToString(s.Condition) - // Size from the built children, as addLoopStatement does (#884 problem 1). - loopWidth, loopHeight = fitContainerSize(loopBuilder.objects, innerStartX, MinLoopWidth, MinLoopHeight) + // Size from the built children, as addLoopStatement does (#884 problem 1), + // bounded around this loop's own anchor (#1935). + anchorX, symmetricX := loopLeftX, false + if s.Annotations != nil && s.Annotations.Position != nil { + anchorX, symmetricX = s.Annotations.Position.X, true + } + loopWidth, loopHeight = fitContainerSizeWithAuthored( + loopBuilder.objects, loopBuilder.authoredPos, symmetricX, anchorX, fb.posY, MinLoopWidth, MinLoopHeight) if s.Annotations != nil && s.Annotations.Size != nil && s.Annotations.Size.Width > 0 && s.Annotations.Size.Height > 0 { // The box Studio Pro stored, @size(w, h) (ako/mxcli#2369). loopWidth, loopHeight = s.Annotations.Size.Width, s.Annotations.Size.Height @@ -1176,6 +1226,26 @@ func (fb *flowBuilder) addWhileStatement(s *ast.WhileStmt) model.ID { loopLeftX = loopCenterX - loopWidth/2 } + // Children that carry a canvas @position are stored frame-relative, as + // addLoopStatement does (#1935): the frame is final here, and the rest of + // the build reads these positions. + frameLeft, frameTop := loopLeftX, fb.posY-loopHeight/2 + for _, obj := range loopBuilder.objects { + if obj == nil { + continue + } + if a, ok := loopBuilder.authoredPos[obj.GetID()]; ok { + obj.SetPosition(model.Point{X: a.X - frameLeft, Y: a.Y - frameTop}) + } + } + for _, st := range loopBuilder.sidedTails { + origin, dest := loopBuilder.objectByID(st.OriginID), loopBuilder.objectByID(st.DestinationID) + if origin == nil || dest == nil { + continue + } + st.DestinationConnectionIndex = mergeSideFor(origin.GetPosition(), dest.GetPosition()) + } + loop := µflows.LoopedActivity{ BaseMicroflowObject: microflows.BaseMicroflowObject{ BaseElement: model.BaseElement{ID: model.ID(types.GenerateID())}, @@ -1206,6 +1276,12 @@ func (fb *flowBuilder) addWhileStatement(s *ast.WhileStmt) model.ID { // dropped on the floor, so exec reported success on a flow it had silently // written wrong (#1077). fb.errors = append(fb.errors, loopBuilder.errors...) + for id, p := range loopBuilder.authoredPos { + if fb.authoredPos == nil { + fb.authoredPos = map[model.ID]model.Point{} + } + fb.authoredPos[id] = p + } if fb.annotationsByLabel == nil { fb.annotationsByLabel = loopBuilder.annotationsByLabel } diff --git a/mdl/executor/cmd_microflows_builder_flows.go b/mdl/executor/cmd_microflows_builder_flows.go index 2da9089ec1..41d6a5577e 100644 --- a/mdl/executor/cmd_microflows_builder_flows.go +++ b/mdl/executor/cmd_microflows_builder_flows.go @@ -983,6 +983,12 @@ func (fb *flowBuilder) addErrorHandlerFlow(sourceActivityID model.ID, sourceX in fb.flows = append(fb.flows, errBuilder.flows...) fb.annotationFlows = append(fb.annotationFlows, errBuilder.annotationFlows...) fb.errors = append(fb.errors, errBuilder.errors...) + for id, p := range errBuilder.authoredPos { + if fb.authoredPos == nil { + fb.authoredPos = map[model.ID]model.Point{} + } + fb.authoredPos[id] = p + } // The handler's objects land in this collection, so its stated notes are // this builder's to pin too. for id := range errBuilder.statedNotes { diff --git a/mdl/executor/cmd_microflows_builder_graph.go b/mdl/executor/cmd_microflows_builder_graph.go index f8c028d818..6faff6079c 100644 --- a/mdl/executor/cmd_microflows_builder_graph.go +++ b/mdl/executor/cmd_microflows_builder_graph.go @@ -280,6 +280,14 @@ func (fb *flowBuilder) buildFlowGraph(stmts []ast.MicroflowStatement, returns *a // this is the first point where a row's real depth is known. fb.separateRows() + // Hand-placed children authored a CANVAS @position, but a loop's + // ObjectCollection stores positions relative to the loop's own frame. + // Translate each authored object into the frame of the collection that + // holds it (#1935). After separateRows so every container has its final + // size, and top-down: a nested loop's frame is read from its centre after + // that centre itself was translated into its parent's frame. + translateAuthoredLoopChildren(fb.objects, fb.authoredPos, model.Point{}) + // Note lines after everything has moved: the sides that face each other // depend on where the note and its element finally sit. orientAnnotationFlows(fb.objects, fb.annotationFlows) @@ -633,7 +641,37 @@ func (fb *flowBuilder) addTerminalEndEventForPendingHandler(returns *ast.Microfl } // addStatement converts an AST statement to a microflow activity and returns its ID. +// +// A statement that consumed a @position has that canvas coordinate filed under +// the created object's ID (authoredPos), so the loop-frame translation can +// find it later (#1935). func (fb *flowBuilder) addStatement(stmt ast.MicroflowStatement) model.ID { + // A dispatch that builds sub-statements (an IF's branches) recurses through + // here; the inner statements must not wipe the @position THIS statement is + // still waiting to file under its own object. Saved across the dispatch. + savedAuthoredPos := fb.pendingAuthoredPos + fb.pendingAuthoredPos = nil + + id := fb.addStatementDispatch(stmt) + if id != "" && fb.pendingAuthoredPos != nil { + if fb.authoredPos == nil { + fb.authoredPos = map[model.ID]model.Point{} + } + fb.authoredPos[id] = *fb.pendingAuthoredPos + // Inside a container the statement's canvas detour must not drag the + // auto-placed line with it: restore the frame cursor so what follows + // stays frame-relative (#1935). On the canvas the detour IS the row + // semantics (#1768) and the cursor keeps the canvas spot. + if fb.inContainer { + fb.posX = fb.containerCursorX + fb.spacing + fb.posY = fb.containerCursorY + } + } + fb.pendingAuthoredPos = savedAuthoredPos + return id +} + +func (fb *flowBuilder) addStatementDispatch(stmt ast.MicroflowStatement) model.ID { // The loop-body tail is this statement's alone: only an IF reads it, and a // CASE or anything else must not leave it set for an IF nested inside, // which is not at the tail (atBodyTail). @@ -646,9 +684,17 @@ func (fb *flowBuilder) addStatement(stmt ast.MicroflowStatement) model.ID { // Apply @position before creating the activity so it's placed at the right position if fb.pendingAnnotations != nil && fb.pendingAnnotations.Position != nil { + if fb.inContainer { + // Remember the frame-space line so addStatement can put the + // auto-placed cursor back after this canvas detour (#1935). + fb.containerCursorX, fb.containerCursorY = fb.posX, fb.posY + } fb.posX = fb.pendingAnnotations.Position.X fb.posY = fb.pendingAnnotations.Position.Y + p := fb.pendingAnnotations.Position + fb.pendingAuthoredPos = &model.Point{X: p.X, Y: p.Y} } else { + fb.pendingAuthoredPos = nil fb.clearLowerLane(stmt) } if fb.pendingAnnotations != nil { diff --git a/mdl/executor/cmd_microflows_builder_nested_test.go b/mdl/executor/cmd_microflows_builder_nested_test.go index 803fc9c0f0..a84302f885 100644 --- a/mdl/executor/cmd_microflows_builder_nested_test.go +++ b/mdl/executor/cmd_microflows_builder_nested_test.go @@ -56,6 +56,13 @@ var nestedBuilderInherits = map[string]bool{ "emptyErrorHandlerFrom": false, "errorHandlerTailFrom": false, "errorHandlerSource": false, "errorHandlerSkipVar": false, "errorHandlerTailCase": false, "errorHandlerTailAnchor": false, "errorHandlerTailIsSource": false, "errorHandlerReturnValue": false, "pendingErrorHandlers": false, + // #1935: pendingAuthoredPos is per-statement transient; authoredPos is the + // body's own table, handed up at the adopt site like errors; the cursor + // save and the inContainer mark are the body's own frame-space state; + // sidedTails are the body's own, re-derived at its finalize. + "pendingAuthoredPos": false, "authoredPos": false, + "containerCursorX": false, "containerCursorY": false, "inContainer": false, + "sidedTails": false, // Set by the one site that shares it: an error handler's body is in its // parent's collection and on its path (addErrorHandlerFlow); a loop's is @@ -76,6 +83,14 @@ var nestedBuilderInherits = map[string]bool{ "assocObjectVars": false, "joinScopes": false, } +// nestedBuilderStamps are fields nestedBuilder itself sets on the body it +// builds, so the test wants the stamped value rather than the parent's or +// zero. inContainer: every nested body lives in a container's frame, which +// is the whole point of the mark (#1935). +var nestedBuilderStamps = map[string]bool{ + "inContainer": true, +} + func TestNestedBuilder_InheritsSharedState(t *testing.T) { typ := reflect.TypeOf(flowBuilder{}) fields := map[string]bool{} @@ -118,6 +133,10 @@ func TestNestedBuilder_InheritsSharedState(t *testing.T) { if !sameValue(p, c) { t.Errorf("a nested body does not inherit flowBuilder.%s", name) } + case nestedBuilderStamps[name]: + if !c.Bool() { + t.Errorf("nestedBuilder does not stamp flowBuilder.%s; a nested body must build in its container's frame (#1935)", name) + } case !c.IsZero(): t.Errorf("a nested body inherits flowBuilder.%s, classified as its own", name) } diff --git a/mdl/executor/cmd_microflows_merge_test.go b/mdl/executor/cmd_microflows_merge_test.go index ee1d05c080..7780bee252 100644 --- a/mdl/executor/cmd_microflows_merge_test.go +++ b/mdl/executor/cmd_microflows_merge_test.go @@ -181,7 +181,7 @@ func TestMergeIsNotEmittedForANonSplit(t *testing.T) { act := µflows.ActionActivity{} act.ID = model.ID("a") var lines []string - emitMergeAnnotation(act, map[model.ID][]*microflows.SequenceFlow{}, map[model.ID]microflows.MicroflowObject{}, nil, &lines, "") + emitMergeAnnotation(act, map[model.ID][]*microflows.SequenceFlow{}, map[model.ID]microflows.MicroflowObject{}, nil, nil, &lines, "") if len(lines) != 0 { t.Errorf("emitted %v for a plain activity, want nothing", lines) } diff --git a/mdl/executor/cmd_microflows_show_helpers.go b/mdl/executor/cmd_microflows_show_helpers.go index 91a4763278..75a8527b6e 100644 --- a/mdl/executor/cmd_microflows_show_helpers.go +++ b/mdl/executor/cmd_microflows_show_helpers.go @@ -492,6 +492,19 @@ func emitCurveAnnotation( // // The merge is found by walking forward from EVERY branch of the split and // taking the first node reachable from all of them that is an ExclusiveMerge. +// describedCanvasPos adds the frame the describe walk is in back onto a +// stored position: a loop body's children are stored relative to the loop's +// frame, while the language's @position and @merge state canvas coordinates +// (#1935). The walk's frame origin rides on the emitter's ExecContext and is +// zero on the microflow's own canvas. +func describedCanvasPos(annotationsByTarget *annotationEmitter, p model.Point) model.Point { + if annotationsByTarget != nil && annotationsByTarget.ctx != nil && annotationsByTarget.ctx.describeFrameOrigin != nil { + o := *annotationsByTarget.ctx.describeFrameOrigin + return model.Point{X: p.X + o.X, Y: p.Y + o.Y} + } + return p +} + // The describer's own split→merge map is not in scope at this call site, and // threading it here would mean touching ten-plus call sites of // emitObjectAnnotations — the multi-site change that silently skips one. Both @@ -501,6 +514,7 @@ func emitMergeAnnotation( flowsByOrigin map[model.ID][]*microflows.SequenceFlow, activityMap map[model.ID]microflows.MicroflowObject, layout *flowLayoutKeep, + annotationsByTarget *annotationEmitter, lines *[]string, indentStr string, ) { @@ -514,7 +528,7 @@ func emitMergeAnnotation( // through: the description drops the merge's label, so its position // rides on the activity (#750). if m := fallThroughRejoinMerge(obj.GetID(), flowsByOrigin, activityMap); m != "" { - p := activityMap[m].GetPosition() + p := describedCanvasPos(annotationsByTarget, activityMap[m].GetPosition()) *lines = append(*lines, indentStr+fmt.Sprintf("@merge(%d, %d)", p.X, p.Y)) } return @@ -539,7 +553,7 @@ func emitMergeAnnotation( if !layout.keepsPosition(merge.GetID()) && len(findNormalFlows(flowsByOrigin[merge.GetID()])) > 0 { return } - p := merge.GetPosition() + p := describedCanvasPos(annotationsByTarget, merge.GetPosition()) // The merge's own box when it is not the builder's 40x40: Studio Pro // draws 90x60 and other sizes, which a re-created merge lost and, from // its centre, its position too (ako/mxcli#2369). @@ -1104,6 +1118,10 @@ func emitObjectAnnotations( currentID := obj.GetID() pos := obj.GetPosition() + // A loop body's children are stored relative to the loop's frame; the + // language's @position is a canvas coordinate, so emission adds the frame + // the walk is in back on (#1935). Zero on the microflow's own canvas. + pos = describedCanvasPos(annotationsByTarget, pos) layout := annotationsByTarget.layoutKeep() if layout.keepsPosition(currentID) { *lines = append(*lines, indentStr+fmt.Sprintf("@position(%d, %d)", pos.X, pos.Y)) @@ -1126,7 +1144,7 @@ func emitObjectAnnotations( if layout.keepsCurve(currentID) { emitCurveAnnotation(obj, flowsByOrigin, activityMap, lines, indentStr) } - emitMergeAnnotation(obj, flowsByOrigin, activityMap, layout, lines, indentStr) + emitMergeAnnotation(obj, flowsByOrigin, activityMap, layout, annotationsByTarget, lines, indentStr) } if activity, ok := obj.(*microflows.ActionActivity); ok { @@ -2109,6 +2127,22 @@ func emitLoopBody( prevFallsOn := ctx.describeFallsOn ctx.describeFallsOn = false defer func() { ctx.describeFallsOn = prevFallsOn }() + // Children describe in CANVAS coordinates: their stored positions are + // relative to this loop's frame, the language's @position is a canvas + // coordinate, so emission adds the frame back (#1935). A nested loop's + // own frame is read from its centre in this (parent) frame, so the + // offsets compose. + parent := model.Point{} + if ctx.describeFrameOrigin != nil { + parent = *ctx.describeFrameOrigin + } + childOrigin := model.Point{ + X: parent.X + loop.Position.X - loop.Size.Width/2, + Y: parent.Y + loop.Position.Y - loop.Size.Height/2, + } + prevOrigin := ctx.describeFrameOrigin + ctx.describeFrameOrigin = &childOrigin + defer func() { ctx.describeFrameOrigin = prevOrigin }() } loopAnnotationsByTarget := annotationsByTarget.withOverlay(buildAnnotationsByTarget(loop.ObjectCollection)) @@ -3313,7 +3347,7 @@ func whileHeaderAnnotations(merge microflows.MicroflowObject, annotationsByTarge if merge == nil || !annotationsByTarget.layoutKeep().keepsPosition(merge.GetID()) { return nil } - p := merge.GetPosition() + p := describedCanvasPos(annotationsByTarget, merge.GetPosition()) out := []string{indentStr + fmt.Sprintf("@position(%d, %d)", p.X, p.Y)} if sz := objectSize(merge); sz.Width > 0 && sz.Height > 0 && (sz.Width != MergeSize || sz.Height != MergeSize) { out = append(out, indentStr+fmt.Sprintf("@size(%d, %d)", sz.Width, sz.Height)) diff --git a/mdl/executor/exec_context.go b/mdl/executor/exec_context.go index df74a13143..7e1b7e8468 100644 --- a/mdl/executor/exec_context.go +++ b/mdl/executor/exec_context.go @@ -181,6 +181,14 @@ type ExecContext struct { // every loop body; see traverseFlowUntilMerge. describeFallsOn bool + // describeFrameOrigin is the canvas coordinate of the frame origin of the + // loop body DESCRIBE is currently walking, nil on the microflow's own + // canvas. A loop's ObjectCollection stores child positions relative to the + // loop's top-left corner, but the language's @position is a canvas + // coordinate, so emission adds the frame back (#1935). Set and restored by + // emitLoopBody as it descends. + describeFrameOrigin *model.Point + // describeIn, when set, is the exact language DESCRIBE writes, in place of // describeLanguage's default. create or modify pins it to the script's own // version to describe the stored side of its diff, so both sides are read diff --git a/mdl/executor/flow_splice_loop_body.go b/mdl/executor/flow_splice_loop_body.go index 92e5d047f7..bd73f11321 100644 --- a/mdl/executor/flow_splice_loop_body.go +++ b/mdl/executor/flow_splice_loop_body.go @@ -9,6 +9,7 @@ import ( "github.com/mendixlabs/mxcli/mdl/ast" "github.com/mendixlabs/mxcli/mdl/backend" "github.com/mendixlabs/mxcli/mdl/backend/mfmutator" + "github.com/mendixlabs/mxcli/model" "github.com/mendixlabs/mxcli/sdk/microflows" ) @@ -104,14 +105,26 @@ func (a *alterFlowContext) storedLoopStatement(ctx *ExecContext, target mfmutato } stmts := storedBody(a.storedDesc) around := a.loopsAround(target.ID) + // The description states canvas coordinates; the stored loops keep frame + // positions, so each level's position is its stored centre plus the + // enclosing boxes' canvas origins (#1935). + origin := model.Point{} for i := len(around) - 1; i >= 0; i-- { - st := statementDrawnAt(stmts, around[i].Position) + lp := model.Point{X: around[i].Position.X + origin.X, Y: around[i].Position.Y + origin.Y} + st := statementDrawnAt(stmts, lp) if st == nil { - return nil, fmt.Errorf("no stored loop is drawn at (%d, %d)", around[i].Position.X, around[i].Position.Y) + return nil, fmt.Errorf("no stored loop is drawn at (%d, %d)", lp.X, lp.Y) + } + origin = model.Point{ + X: origin.X + around[i].Position.X - around[i].Size.Width/2, + Y: origin.Y + around[i].Position.Y - around[i].Size.Height/2, } stmts = loopStatements(st) } - p := target.Object.GetPosition() + p := model.Point{ + X: target.Object.GetPosition().X + origin.X, + Y: target.Object.GetPosition().Y + origin.Y, + } switch st := statementDrawnAt(stmts, p).(type) { case *ast.LoopStmt, *ast.WhileStmt: return st, nil diff --git a/mdl/executor/issue1935_loop_box_test.go b/mdl/executor/issue1935_loop_box_test.go new file mode 100644 index 0000000000..4d9d3d04bc --- /dev/null +++ b/mdl/executor/issue1935_loop_box_test.go @@ -0,0 +1,120 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "testing" + + "github.com/mendixlabs/mxcli/mdl/ast" + "github.com/mendixlabs/mxcli/mdl/visitor" + "github.com/mendixlabs/mxcli/model" + "github.com/mendixlabs/mxcli/sdk/microflows" +) + +// mendixlabs/mxcli#1935: a new loop's box was sized from its body's ABSOLUTE +// canvas coordinates, so moving the loop 600px right grew the box by exactly +// 600 (body at 600,300 → 710;380; body at 1200,300 → 1310;380) and the box, +// being centred on the loop, swallowed its neighbours. The box must come from +// the body's bounds RELATIVE to the loop, and a body activity's @position — +// a canvas coordinate everywhere else in the language — must be translated +// into the loop's own frame before it is stored. + +func loopOf1935(t *testing.T, coll *microflows.MicroflowObjectCollection) *microflows.LoopedActivity { + t.Helper() + for _, o := range coll.Objects { + if l, ok := o.(*microflows.LoopedActivity); ok { + return l + } + } + t.Fatal("no loop built") + return nil +} + +func build1935(t *testing.T, body string) *microflows.MicroflowObjectCollection { + t.Helper() + src := "create microflow M.F ($L: List of M.E)\nbegin\n" + body + "end;\n" + prog, errs := visitor.Build(src) + if len(errs) != 0 { + t.Fatalf("parse: %v", errs) + } + mf := prog.Statements[0].(*ast.CreateMicroflowStmt) + fb := &flowBuilder{ + posX: 100, posY: 200, spacing: HorizontalSpacing, + varTypes: map[string]string{}, declaredVars: map[string]string{}, + measurer: &layoutMeasurer{}, + } + return fb.buildFlowGraph(mf.Body, mf.ReturnType) +} + +// The issue's own reproduction, twice, differing only in the loop's x. +func TestLoopBoxDoesNotGrowWithLoopPosition(t *testing.T) { + small := loopOf1935(t, build1935(t, " @position(600, 200)\n loop $I in $L\n begin\n @position(600, 300)\n log info node 'x' 'a';\n end loop;\n")) + large := loopOf1935(t, build1935(t, " @position(1200, 200)\n loop $I in $L\n begin\n @position(1200, 300)\n log info node 'x' 'a';\n end loop;\n")) + if small.Size != large.Size { + t.Errorf("moving the loop 600px changed its box: %v vs %v — the box must be sized from the body relative to the loop, not from canvas coordinates", + small.Size, large.Size) + } +} + +// A body activity's stored position is relative to the loop's frame, so the +// rendered child must sit where the script placed it and inside its container +// (what MPR011 checks). +func TestLoopBodyPositionStoredRelativeToLoopFrame(t *testing.T) { + coll := build1935(t, " @position(600, 200)\n loop $I in $L\n begin\n @position(600, 300)\n log info node 'x' 'a';\n end loop;\n") + loop := loopOf1935(t, coll) + if len(loop.ObjectCollection.Objects) != 1 { + t.Fatalf("loop holds %d objects, want 1", len(loop.ObjectCollection.Objects)) + } + child := loop.ObjectCollection.Objects[0] + p := child.GetPosition() + left, top := p.X-ActivityWidth/2, p.Y-ActivityHeight/2 + right, bottom := p.X+ActivityWidth/2, p.Y+ActivityHeight/2 + if left < 0 || top < 0 || right > loop.Size.Width || bottom > loop.Size.Height { + t.Errorf("child stored at %v escapes its container %v — the canvas @position was not translated into the loop's frame", p, loop.Size) + } + // The authored canvas spot was (600, 300) with the loop centred at + // (600, 200): relative to the frame the child must keep that offset — + // horizontally centred on the loop, half a box below its centre. + if p.X != loop.Size.Width/2 { + t.Errorf("child x %d, want %d (authored on the loop's centre line)", p.X, loop.Size.Width/2) + } + wantY := loop.Size.Height/2 + 100 // authored 100px below the loop's centre + if p.Y != wantY { + t.Errorf("child y %d, want %d (authored 100px below the loop's centre)", p.Y, wantY) + } +} + +// The while form shares the machinery; moving it must not grow its box either. +func TestWhileBoxDoesNotGrowWithLoopPosition(t *testing.T) { + small := loopOf1935(t, build1935(t, " @position(600, 200)\n while true\n begin\n @position(600, 300)\n log info node 'x' 'a';\n break;\n end while;\n")) + large := loopOf1935(t, build1935(t, " @position(1200, 200)\n while true\n begin\n @position(1200, 300)\n log info node 'x' 'a';\n break;\n end while;\n")) + if small.Size != large.Size { + t.Errorf("moving the while 600px changed its box: %v vs %v", small.Size, large.Size) + } +} + +// Auto-placed bodies keep the box they always had: no @position anywhere, the +// statement count alone must still set the size (the #884 contract). +func TestLoopBoxAutoPlacedBodyUnchanged(t *testing.T) { + loop := loopOf1935(t, build1935(t, " loop $I in $L\n begin\n log info node 'x' 'a';\n end loop;\n")) + if loop.Size.Width < MinLoopWidth || loop.Size.Height < MinLoopHeight { + t.Errorf("auto-placed loop box %v below the minimum %dx%d", loop.Size, MinLoopWidth, MinLoopHeight) + } + for _, child := range loop.ObjectCollection.Objects { + p := child.GetPosition() + if p.X == 0 && p.Y == 0 { + continue + } + if p.X+ActivityWidth/2 > loop.Size.Width || p.Y+ActivityHeight/2 > loop.Size.Height { + t.Errorf("auto-placed child at %v escapes its container %v", p, loop.Size) + } + } +} + +// An explicit @size still wins over the computed box (the #2369 contract). +func TestLoopExplicitSizeStillWins(t *testing.T) { + loop := loopOf1935(t, build1935(t, " @position(600, 200)\n @size(990, 270)\n loop $I in $L\n begin\n @position(600, 300)\n log info node 'x' 'a';\n end loop;\n")) + if loop.Size != (model.Size{Width: 990, Height: 270}) { + t.Errorf("loop box %v, want the @size 990×270", loop.Size) + } +} diff --git a/mdl/executor/layout.go b/mdl/executor/layout.go index 9a8ad34de9..922f3da39c 100644 --- a/mdl/executor/layout.go +++ b/mdl/executor/layout.go @@ -566,3 +566,127 @@ func fitContainerSize(objects []microflows.MicroflowObject, leftInset, minWidth, _ = leftInset return width, height } + +// fitContainerSizeWithAuthored sizes a container box around both families of +// children a loop body can hold (mendixlabs/mxcli#1935). +// +// Auto-placed children were built in the container's own frame, so their +// bound is the plain fitContainerSize rule: right/bottom edge + padding. +// Hand-placed children carry a canvas @position — the language's one +// coordinate space everywhere else — and their stored form only becomes +// frame-relative in the translation pass, so here they are bounded directly +// against where the frame will anchor: +// +// - a loop that states its own @position is sized SYMMETRICALLY around that +// centre: width ≥ 2·(|x−cx| + half + padding). The centre is the one +// canvas anchor that does not move when the width changes, so the bound is +// exact and — the point of #1935 — independent of where the loop sits on +// the canvas. +// - a flow-placed loop keeps its LEFT edge pinned where the flow line put it +// (centre = left + width/2 moves with the width), so the bound is linear: +// width ≥ (x−left) + half + padding. A child authored left of that edge +// cannot stretch the box leftward; MPR011 reports it, as for any child +// placed outside its container. +// - vertically every loop is centred on its row (fb.posY), so height is +// always the symmetric bound around it. +func fitContainerSizeWithAuthored(objects []microflows.MicroflowObject, authored map[model.ID]model.Point, symmetricX bool, anchorX, centreY, minWidth, minHeight int) (width, height int) { + width, height = minWidth, minHeight + auto := make([]microflows.MicroflowObject, 0, len(objects)) + for _, o := range objects { + if o == nil { + continue + } + if _, hand := authored[o.GetID()]; hand { + continue + } + auto = append(auto, o) + } + _, _, maxX, maxY, n := containerBounds(auto) + if n > 0 { + width = max(width, maxX+LoopPadding) + height = max(height, maxY+LoopPadding) + } + for _, o := range objects { + if o == nil { + continue + } + a, hand := authored[o.GetID()] + if !hand { + continue + } + hw, hh := halfBoxOf(o) + dx := a.X - anchorX + if symmetricX { + width = max(width, 2*(absInt(dx)+hw+LoopPadding)) + } else { + width = max(width, dx+hw+LoopPadding) + } + dy := a.Y - centreY + height = max(height, 2*(absInt(dy)+hh+LoopPadding)) + } + return width, height +} + +// halfBoxOf is half the object's stored box, the amount by which a centre +// point's box pokes past its position. Objects without a size (annotations) +// contribute nothing, matching containerBounds. +func halfBoxOf(o microflows.MicroflowObject) (hw, hh int) { + if withSize, ok := o.(interface{ GetSize() model.Size }); ok { + if sz := withSize.GetSize(); sz.Width > 0 || sz.Height > 0 { + return sz.Width / 2, sz.Height / 2 + } + } + return 0, 0 +} + +// noteAuthoredMerge files a merge created at its @merge position under the +// canvas coordinate it states, so a container's finalize translates it into +// the frame like any hand-placed child (#1935). Outside a container the merge +// keeps canvas coordinates and nothing is recorded. Without this, a +// merge-positioned merge stayed frame-raw during the body build while the +// hand-placed statements around it held canvas values, and the geometry +// comparisons that side their flows (mergeSideFor) read two spaces at once. +func (fb *flowBuilder) noteAuthoredMerge(merge *microflows.ExclusiveMerge, ann *ast.ActivityAnnotations) { + if !fb.inContainer || merge == nil || ann == nil || ann.Merge == nil { + return + } + if fb.authoredPos == nil { + fb.authoredPos = map[model.ID]model.Point{} + } + fb.authoredPos[merge.ID] = model.Point{X: ann.Merge.X, Y: ann.Merge.Y} +} + +// translateAuthoredLoopChildren moves every hand-placed object from the +// canvas coordinates its @position authored into the frame of the collection +// that holds it: a loop's ObjectCollection positions its children relative to +// the loop's own top-left corner, which is how Studio Pro stores them +// (mendixlabs/mxcli#1935). origin is the canvas coordinate of the current +// frame's origin — (0,0) at the top level, so top-level objects keep canvas +// coordinates and are never moved. Authored objects translate before the walk +// descends, so a nested loop's frame is read from its already-translated +// centre and nesting composes. +func translateAuthoredLoopChildren(objects []microflows.MicroflowObject, authored map[model.ID]model.Point, origin model.Point) { + for _, obj := range objects { + if obj == nil { + continue + } + if a, ok := authored[obj.GetID()]; ok { + obj.SetPosition(model.Point{X: a.X - origin.X, Y: a.Y - origin.Y}) + } + loop, ok := obj.(*microflows.LoopedActivity) + if !ok || loop.ObjectCollection == nil { + continue + } + translateAuthoredLoopChildren(loop.ObjectCollection.Objects, authored, model.Point{ + X: origin.X + loop.Position.X - loop.Size.Width/2, + Y: origin.Y + loop.Position.Y - loop.Size.Height/2, + }) + } +} + +func absInt(v int) int { + if v < 0 { + return -v + } + return v +}