Gum forms behaviors

From vchelaru/Gum · View interactive version

Gum forms behaviors is an AI agent skill from the GitHub repository vchelaru/Gum. Gum behaviors and the design-time to runtime Forms wrapping lifecycle, including FormsProperties (Forms-only properties shown as behavior variables on a visual in the tool). Triggers: BehaviorSave, FormsProperties, ElementBehaviorReference, BehaviorFormsPropertyApplier, StandardFormsBehaviorNames, R

How to use this skill

Skill file

Gum Forms Behaviors

What Behaviors Are

Behaviors are named capability contracts stored as .behx XML files in the project's Behaviors/ folder. Each behavior (BehaviorSave) declares: The Forms, visual and Renderable layers are in gum-architecture-layers; a variable reference that reads a FormsProperty is in "Two Layers in One Variable List" below.

An ElementSave (component or screen) opts into a behavior via a List<ElementBehaviorReference>, where each reference holds only a BehaviorName string. This is the signal used at runtime to select which Forms control wraps the visual.

The Wrapping Lifecycle

At project load time, call order is:

  1. FormsUtilities.RegisterFromFileFormRuntimeDefaults() iterates every component in the loaded GumProjectSave, checks each component's Behaviors list against constants in StandardFormsBehaviorNames, and calls ElementSaveExtensions.RegisterGueInstantiationType(component.Name, typeof(DefaultFromFileXxxRuntime)) for each match.
  1. DefaultFromFileXxxRuntime (in MonoGameGum/Forms/DefaultFromFileVisuals/) is an InteractiveGue subclass selected as the runtime type. Its AfterFullCreation() override fires after the full visual tree is instantiated. Inside AfterFullCreation(), the runtime sets FormsControlAsObject = new Button(this) (passing itself as the visual), completing the pairing.
  1. ReactToVisualChanged() fires on the Forms control when its Visual is assigned. The control caches named child references (Visual.GetGraphicalUiElementByName(...)) and base.ReactToVisualChanged() subscribes to input events and calls UpdateState().

The DefaultFromFileXxxRuntime classes exist solely to bridge the file-loading path into the Forms object model. They are distinct from the DefaultVisuals classes (which serve the code-only construction path).

Behavior → Forms Control Mapping

StandardFormsBehaviorNames constants → DefaultFromFile runtime registered:

| Behavior name constant | Runtime type |

|------------------------|-------------|

| ButtonBehaviorName | DefaultFromFileButtonRuntime |

| CheckBoxBehaviorName | DefaultFromFileCheckBoxRuntime |

| ToggleBehaviorName | DefaultFromFileToggleButtonRuntime |

| DialogBoxBehaviorName | DefaultFromFileDialogBoxRuntime |

| UserControlBehaviorName | DefaultFromFileUserControlRuntime |

| ComboBoxBehaviorName | DefaultFromFileComboBoxRuntime |

| ListBoxBehaviorName | DefaultFromFileListBoxRuntime |

| TextBoxBehaviorName | DefaultFromFileTextBoxRuntime |

| LabelBehaviorName | DefaultFromFileLabelRuntime / DefaultFromFileLabelTextRuntime |

| ItemsControlBehaviorName | DefaultFromFileItemsControlRuntime |

| ProgressBarBehaviorName | DefaultFromFileProgressBarRuntime |

| RadioButtonBehaviorName | DefaultFromFileRadioButtonRuntime |

| SliderBehaviorName | DefaultFromFileSliderRuntime |

| ScrollBarBehaviorName | DefaultFromFileScrollBarRuntime |

| ScrollViewerBehaviorName | DefaultFromFileScrollViewerRuntime |

| MenuBehaviorName | DefaultFromFileMenuRuntime |

| MenuItemBehaviorName | DefaultFromFileMenuItemRuntime |

| PasswordBoxBehaviorName | DefaultFromFilePasswordBoxRuntime |

| PanelBehaviorName | DefaultFromFilePanelRuntime |

| StackPanelBehaviorName | DefaultFromFileStackPanelRuntime |

| WindowBehaviorName | DefaultFromFileWindowRuntime |

The Property Promotion Gap (closed for logical + state-mapped)

The Gum tool operates at the visual layer — layout, colors, fonts, dimensions saved as VariableSave entries. The Forms behavioral layer (state, data, interaction) is added at runtime. Two mechanisms now bridge the save model into Forms semantics: FormsProperties for the value-on-the-control half, and ToolOnlyVariableReferences for the design-time visual-state preview half.

Two Layers in One Variable List

`BehaviorSave.FormsProperties` (v1)

A List<VariableSave> declaring design-time properties that flow through to the wrapped FrameworkElement at runtime via reflection. Each entry's Name must match a property on the control (e.g. ToolTip, IsEnabled); Value is the declared default (used as a fallback tier — see below).

The variable grid synthesizes a "Behavior" category for these declarations on both the component definition and any instance (ElementSaveDisplayer.AddBehaviorFormsPropertyMembers). When a component sets a default on a promoted property under General, the displayer relocates it into "Behavior" to keep categorization consistent.

`BehaviorSave.ToolOnlyVariableReferences` (v2)

A List<string> of variable-reference assignments evaluated only at design time to drive wireframe preview. Example on ButtonBehavior:

ButtonCategoryState = IsEnabled ? "Enabled" : "Disabled"

Tool-time apply (BehaviorToolOnlyReferencesApplier, in Tools/Gum.ProjectServices/Editing/) walks every linked behavior's ToolOnlyVariableReferences, evaluates the RHS via EvaluatedSyntax against the component's effective state, and writes the resolved value back into the state via SetValue. For instances, bare RHS identifiers are auto-qualified with the instance name. Hooked into VariableReferenceLogic.DoVariableReferenceReaction and gumcli edit's setVariableReferences, immediately after the state-level apply.

The runtime apply path never traverses this list — that's what the ToolOnly name encodes structurally. At runtime, the Forms control's own setter (e.g. FrameworkElement.IsEnabled → UpdateState()) owns the visual; applying the reference again would double-write.

Every reference's left-hand variable must be in VariablesHiddenFromInstances on each template component using the behavior. Otherwise an instance can set the visual state directly: the tool shows it, while the runtime still follows the Forms property. TemplateDerivedVariablesHiddenTests enforces this for the Standard template and every theme.

Hide every other state category the control drives at runtime too (ScrollViewerCategoryState, OrientationCategoryState), not only reference targets. TemplateDerivedVariablesHiddenTests fails for any category on a behavior-bearing component that is neither hidden nor in its InstanceAuthoredCategories list (SizingCategory, TextCategory: states an instance is meant to set). A hidden variable with no reference stays visible on instances that already author it; one that a reference drives never does.

Container-structure variables (ContainedType, ChildrenLayout, ClipsChildren, IsRenderTarget, ExposeChildrenEvents) are exposed on an instance only when the control is the visual itself, a bare container (Panel, UserControl, StackPanel). A control with something internal (ItemsControl, ListBox, ScrollViewer, Window, DialogBox, SettingsView, every other control) hides all five. StackPanel also hides ChildrenLayout because its Orientation reference drives it. TemplateDerivedVariablesHiddenTests enforces this against an explicit per-control table (MustHideStructureVariables); a new template control needs an entry there. Hiding is tool-only, so an instance that already authored one of them keeps the value in the tool, at runtime, and in generated code (CodeGenerator skips a hidden variable only when a behavior reference drives it, IObjectFinder.IsVariableDrivenByToolOnlyReference).

BehaviorFormsPropertyCatalogTests (MonoGameGum.Tests) pins that each declared FormsProperty exists on the control and that its declared default equals a new control's, because the applier writes that default onto every authored control.

Three-tier default resolution

Both apply paths plus the variable-grid display getter consult the same priority order:

  1. Parent-state instance override (e.g. screen state "ButtonInstance.IsEnabled")
  2. Component's own default state value
  3. Behavior-declared FormsProperty.Value (the implicit default)

Tier 3 is virtual — never written to state, never appears in .gusx. State-empty stays state-empty. The fallback machinery:

Each tier-2/3 default is applied once, at the control's own build, never re-applied by an ancestor. SetGraphicalUiElement calls InitialFormsPropertiesNotifier(built, true) for the element it just built (all three tiers) and (instance, false) for that element's own instances only (Apply(..., authoredOverridesOnly: true): just a value the container's default state, or a base of it, explicitly authors for the instance; no fall-through to the instance's component and no declared default). An instance owned by a nested element is skipped, so code that ran in that element's CustomInitialize (which runs in AfterFullCreation, after the control exists) keeps what it set, at any nesting depth. A value the container authors still wins over CustomInitialize, since the container's pass runs after it. InitialStateAppliedNotifier (the UpdateState re-sync) still walks every descendant. The built element's own control gets its values where it is created: every DefaultFromFile*Runtime.AfterFullCreation calls BehaviorFormsPropertyApplier.ApplyToCreatedControl(this) right after FormsControlAsObject = new X(this), and ApplyOnceAtBuild (a ConditionalWeakTable mark) makes the build's root pass a no-op for that control. So a custom runtime deriving a DefaultFromFile*Runtime that sets a Forms property after base.AfterFullCreation() keeps it. A runtime type that creates its own control instead of deriving one gets no creation-time apply and keeps the old behavior (the root pass applies after its AfterFullCreation).

Codegen (FullyInCode GumForms) mirrors tiers 1 and 2 only (and a Forms property authored in a category state, which ApplyState also writes onto the control): it assigns authored values on the control and relies on tier 3 equalling the control's code default (see CodeGenerator.FillWithFormsPropertyAssignments, gum-tool-codegen).

`VariableSave.Description` (v3)

Authored documentation persisted alongside the FormsProperty declaration in the .behx. ElementSaveDisplayer.AddBehaviorFormsPropertyMembers seeds each row's srim.DetailText from the declaration's Description when surfacing behavior-promoted variables, so the variable grid shows authored docs by default. Distinct from the [XmlIgnore] DetailText field, which holds transient state-dependent hints set by tool/plugin code at runtime; see the cross-referencing XML docs on both fields. Use Description only when a property's name is ambiguous, has overlapping siblings (e.g. MaxLength vs MaxLettersToShow), or assumes prior framework knowledge.

Covered today

Snapshot, not a live reference. Standard Forms behaviors (.behx) and components (.gucx) are copied into the project when Forms controls are added — the Add Forms dialog (and new-project setup) copies the chosen theme into the project via FormsFileService. Two themes ship, and a fix usually belongs in both: Tools/Gum.ProjectServices/Templates/FormsTemplate/ — exposed as the Standard theme, so the source folder name differs from the theme name — and Tools/Gum.ProjectServices/Templates/FormsThemes/Bubblegum/. (GumFormsPlugin's post-build stages both under Content/FormsThemes/{Standard,Bubblegum}/, which is what FormsFileService reads.) Later improvements — new FormsProperty declarations, new ToolOnlyVariableReferences, additional VariablesHiddenFromInstances entries — do not retroactively reach controls already copied into a project; only controls added afterward from an updated tool build get them. So a "feature works in a new project but not mine" report usually means the project's copy predates the improvement. (Concrete case: a project whose TextBoxBehavior lacks the TextWrapping FormsProperty and whose Controls/TextBox.gucx doesn't yet hide LineModeCategoryState — the user set the raw visual line-mode to Multi, the text wraps, but the forms line-mode never engages and the caret stays single-line.)

State-mapped (FormsProperty + ToolOnlyVariableReference, three-tier default resolution):

Logical-only (FormsProperty only — runtime reflects directly):

Value-alias (FormsProperty name ≠ the underlying visual variable name — needs both a reference and hiding):

Wireframe incremental-update gotcha (value-alias). A value-alias name (Spacing, Orientation) is not a real GraphicalUiElement property, so the editor's incremental preview path (MainEditorTabPlugin.HandleVariableSetLate, gated by PropertiesSupportingIncrementalChange) can't push it onto the live GUE. Left unhandled, every scrub tick of the alias falls back to a full WireframeObjectManager.RefreshAll rebuild (~1 fps — issue #3191). The bridge is BehaviorToolOnlyReferencesApplier.GetUnderlyingMembersDrivenBy(element, instance, changedMember): it resolves the alias to the underlying visual variable(s) the behavior reference drives (Spacing→StackSpacing), whose already-materialized value is then pushed via gue.SetProperty. The underlying name (not the alias) is what belongs in PropertiesSupportingIncrementalChange.

Nullable type declarations. When a Forms control's property is int? (or Orientation?) and null is meaningful, declare the ? in FormsProperty.Type (e.g. Type="int?", Type="Orientation?") so the variable grid renders the nullable editor and authors can clear back to null. The runtime applier reflects on prop.PropertyType regardless, so coercion works either way.

Enum-typed FormsProperty declarations. Author the default Value as a string (<Value xsi:type="xsd:string">Auto</Value>) — the applier's IsEnum branch parses it via Enum.Parse. The variable grid resolves the enum's name string (e.g. Type="ScrollBarVisibility") via TypeManager.GetTypeFromString, so the type must live in or be linked into an assembly TypeManager.Initialize scans (GumCommon, where TypeManager is compiled, plus the assemblies holding VerticalAlignment and DimensionUnitType). TextWrapping, ScrollBarVisibility, and Orientation are physically in MonoGameGum/Forms/ but <Compile Include>-linked into GumCommon.

Reflection apply is generic, so any new logical-only FormsProperty declaration flows through without runtime changes. State-mapped properties beyond what's listed follow the same shape: declare the FormsProperty(/ies) plus a ToolOnlyVariableReference driving the appropriate <X>CategoryState.

Key Files

| Path | Purpose |

|------|---------|

| GumDataTypes/Behaviors/BehaviorSave.cs | Behavior definition model (.behx) |

| GumDataTypes/Behaviors/ElementBehaviorReference.cs | Per-element reference holding only BehaviorName |

| GumDataTypes/Behaviors/StandardFormsBehaviorNames.cs | String constants for all standard behavior names |

| GumDataTypes/ElementSave.cs | Behaviors list on components/screens |

| MonoGameGum/Forms/FormsUtilities.cs | RegisterFromFileFormRuntimeDefaults() — drives the mapping; sets InitialFormsPropertiesNotifier (invokes BehaviorFormsPropertyApplier) and InitialStateAppliedNotifier (UpdateState) |

| MonoGameGum/Forms/DefaultFromFileVisuals/ | DefaultFromFileXxxRuntime classes — AfterFullCreation() creates Forms objects |

| MonoGameGum/Forms/BehaviorFormsPropertyApplier.cs | Reflects BehaviorSave.FormsProperties values onto the wrapped FrameworkElement (with three-tier default resolution) |

| Tools/Gum.ProjectServices/Editing/BehaviorToolOnlyReferencesApplier.cs | Tool-only design-time apply pass for ToolOnlyVariableReferences. Strictly tool-only — never invoked from runtime / generated code. |

| Gum/Plugins/InternalPlugins/VariableGrid/ElementSaveDisplayer.cs | AddBehaviorFormsPropertyMembers — surfaces FormsProperties in the variable grid; sets DefaultValueFallback on each SRIM so the grid shows the declared default; seeds srim.DetailText from the FormsProperty's Description. |

| GumDataTypes/Variables/VariableSave.cs | Description (persisted, XML-serialized) and DetailText ([XmlIgnore], transient) fields with cross-referencing XML docs. |

| Gum/Plugins/InternalPlugins/VariableGrid/StateReferencingInstanceMember.cs | DefaultValueFallback final tier in the value getter for grid display. |

| Runtimes/GumExpressions/EvaluatedSyntax.cs | Optional fallback parameter on FromSyntaxNode threaded through evaluation. |

| Gum/DataTypes/RecursiveVariableFinder.cs | Fallback property consulted when state lookup returns null. |

| GumRuntime/InteractiveGue.cs | FormsControlAsObject back-link property |

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.