Window Framework for UI Toolkit v2.0.x
GWG.WindowFramework.WindowFrameContextMenu Class Reference

A sophisticated context menu implementation for the Window Framework that provides dynamic menu creation with fade animations and intelligent positioning. More...

Inheritance diagram for GWG.WindowFramework.WindowFrameContextMenu:
Collaboration diagram for GWG.WindowFramework.WindowFrameContextMenu:

Public Member Functions

void RemoveNow ()
 Immediately removes the context menu from the visual hierarchy and performs complete cleanup.
void Show (Vector2 mousePosition, ContextMenuConfig config, VisualElement target, Action onClose, bool selfAdd=true)
 Displays the context menu at the specified position with the given configuration and event handlers.

Private Member Functions

VisualElement AddMenuItem (string text, bool isChecked, bool isDisabled, Action action=null)
 Creates a menu item element with the specified properties and behavior.
void ApplyThemeSheets (System.Collections.Generic.List< StyleSheet > sheets)
 Replaces only stylesheet references this menu owns; supplied references retain repository ownership.
void CancelFadeAndRestore ()
 Cancels any scheduled fade-out and restores the context menu to full opacity and interactivity.
void FadeAndRemove ()
 Initiates the fade-out animation sequence and schedules menu removal.
void FadeIn ()
 Smoothly fades in the context menu upon appearance or when cancelled during fade-out.
void OnControllerThemeChanged (System.Collections.Generic.List< StyleSheet > newSheets, System.Collections.Generic.List< StyleSheet > oldSheets)
 Updates an open menu through the existing controller notification, with no resource lookup.
void OnGlobalPointerDown (PointerDownEvent evt)
void OnMouseEnter (MouseEnterEvent evt)
void OnMouseLeave (MouseLeaveEvent evt)
void OnMouseLeaveWindow (MouseLeaveWindowEvent evt)
void OnNavCancel (NavigationCancelEvent evt)
void OnPointerDown (PointerDownEvent evt)
void OnThemeDetached (DetachFromPanelEvent evt)
 Releases theme notifications and owned references on external removal as well as explicit dismissal.
void StartFadeOut ()
 Performs the frame-by-frame fade-out animation smoothly without abrupt opacity changes.

Private Attributes

float _currentOpacity = 1f
float _delay
 The delay in seconds before the fade-out animation begins after the mouse leaves the menu area.
float _fadeTime
 The duration in seconds for the fade-out animation effect.
EventCallback< PointerDownEvent > _globalPointerDownCallback
EventCallback< MouseEnterEvent > _mouseEnterCallback
EventCallback< MouseLeaveEvent > _mouseLeaveCallback
EventCallback< MouseLeaveWindowEvent > _mouseLeaveWindowCallback
EventCallback< NavigationCancelEvent > _navCancelCallback
readonly System.Collections.Generic.List< StyleSheet > _ownedThemeSheets = new System.Collections.Generic.List<StyleSheet>()
EventCallback< PointerDownEvent > _pointerDownCallback
PickingMode _previousRootPickingMode = PickingMode.Ignore
bool _restoredRootPickingMode = false
VisualElement _rootContainer
IVisualElementScheduledItem _task
 Reference to the scheduled task managing fade-out animation and menu removal.
VisualElement _wrapper

Detailed Description

A sophisticated context menu implementation for the Window Framework that provides dynamic menu creation with fade animations and intelligent positioning.

WindowFrameContextMenu is a specialized VisualElement that creates contextual menus with advanced features:

KeyValue Features:

  • Dynamic menu item generation from configuration objects
  • Intelligent positioning with boundary detection and adjustment
  • Smooth fade-out animations with configurable timing
  • Support for menu titles, separators, and disabled items
  • Checkbox/checkmark display for toggleable options
  • Automatic cleanup and memory management
  • Integration with WindowFrameController theming system
  • Mouse and keyboard event handling for proper dismissal
  • Editor and runtime compatibility with different positioning logic

Menu Structure: The context menu consists of a wrapper container that holds:

  • Optional title label
  • Menu items with labels and optional checkmarks
  • Visual separators between logical groups
  • "No options available" fallback when no items are visible

Animation System:

  • Immediate appearance when shown
  • Configurable fade-out delay after mouse leaves menu area
  • Frame-accurate fade-out animation using Unity's scheduler
  • Automatic removal when fade completes or immediate dismissal on click

Event Handling: The menu responds to various events for natural user interaction:

  • MouseLeave/MouseLeaveWindow: Initiates fade-out sequence
  • NavigationCancel: Immediate dismissal (Escape KeyValue)
  • PointerDown: Immediate dismissal when clicking outside
  • Individual item clicks execute actions and dismiss menu

Integration: Works seamlessly with ContextMenuConfig objects and ContextMenuActivator manipulators to provide a complete context menu system.

var config = new ContextMenuConfig { Title = "Options" };
config.Items.Add(new ContextMenuItem("Copy", () => UnityEngine.Debug.Log("Copy")));
config.Items.Add(new ContextMenuItem()); // separator
var button = new Button { text = "Right-click me" };
button.AddManipulator(new GWG.WindowFramework.Manipulators.ContextMenuActivator(config));
// Manual display requires a valid target and configuration:
var menu = new WindowFrameContextMenu();
menu.Show(button.worldBound.center, config, button, () => UnityEngine.Debug.Log("Item activated"));
// The current implementation anchors to target geometry; mousePosition is not used for layout.
Configuration class for a runtime context menu.
Definition ContextMenuConfig.cs:26
List< ContextMenuItem > Items
Ordered mutable menu entries; keep the list and every entry nonnull.
Definition ContextMenuConfig.cs:32
ContextMenuItem()
Create a menu seperator in the menu.
Definition ContextMenuItem.cs:127
A mouse manipulator that enables context menu functionality for any VisualElement in Unity's UI Toolk...
Definition ContextMenuActivator.cs:43
Window and content interaction manipulators. Provides dragging, directional resizing,...
Core WindowFramework controls, controller and configuration/data APIs. Contains WindowFrame,...
Definition LogViewerContentExample.cs:5
Garage-Ware Games namespace root. Groups the namespaces used by this package. Namespace qualification...
Definition LogViewerContentExample.cs:5

Member Function Documentation

◆ AddMenuItem()

VisualElement GWG.WindowFramework.WindowFrameContextMenu.AddMenuItem ( string text,
bool isChecked,
bool isDisabled,
Action action = null )
inlineprivate

Creates a menu item element with the specified properties and behavior.

Parameters
textThe display text for the menu item
isCheckedWhether to display a checkmark next to the item
isDisabledWhether the item should appear disabled and non-interactive
actionThe action to execute when the item is clicked (null for disabled items)
Returns
A VisualElement representing the complete menu item with label and optional checkmark

This method creates a structured menu item with the following components:

Item Structure:

  • Wrapper container with flex row layout for horizontal arrangement
  • Label element displaying the menu item text
  • Checkbox element for visual indication of checked state

Visual States:

  • Normal: Interactive item with hover and click responses
  • Disabled: Grayed out appearance with no interaction capability
  • Checked: Visible checkmark indicator for toggle states
  • Unchecked: Hidden checkmark for normal menu items

Event Handling:

  • Registers PointerDownEvent for enabled items only
  • Executes provided action and dismisses menu on click
  • Uses TrickleDown.NoTrickleDown for precise event targeting

CSS Classes:

  • "context-menu__item": Applied to the wrapper for styling
  • "context-menu__item-disabled": Applied when item is disabled
  • "context-menu__item-label": Applied to the text label
  • "context-menu__item-checked-box": Applied to the checkmark element

The method provides a consistent visual structure while allowing flexible content and behavior through the configuration parameters.

// AddMenuItem is used internally by Show() method
// Examples of different menu item types created:
// Standard clickable item
var normalItem = AddMenuItem("Save File", false, false, () => SaveCurrentFile());
// Result: Clickable "Save File" item with no checkmark
// Checked toggle item
var checkedItem = AddMenuItem("Auto Save", true, false, () => ToggleAutoSave());
// Result: Clickable "Auto Save" item with visible checkmark
// Disabled item
var disabledItem = AddMenuItem("Undo", false, true, null);
// Result: Non-clickable "Undo" item with disabled appearance
VisualElement AddMenuItem(string text, bool isChecked, bool isDisabled, Action action=null)
Creates a menu item element with the specified properties and behavior.
Definition WindowFrameContextMenu.cs:509
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ApplyThemeSheets()

void GWG.WindowFramework.WindowFrameContextMenu.ApplyThemeSheets ( System.Collections.Generic.List< StyleSheet > sheets)
inlineprivate

Replaces only stylesheet references this menu owns; supplied references retain repository ownership.

Here is the caller graph for this function:

◆ CancelFadeAndRestore()

void GWG.WindowFramework.WindowFrameContextMenu.CancelFadeAndRestore ( )
inlineprivate

Cancels any scheduled fade-out and restores the context menu to full opacity and interactivity.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ FadeAndRemove()

void GWG.WindowFramework.WindowFrameContextMenu.FadeAndRemove ( )
inlineprivate

Initiates the fade-out animation sequence and schedules menu removal.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ FadeIn()

void GWG.WindowFramework.WindowFrameContextMenu.FadeIn ( )
inlineprivate

Smoothly fades in the context menu upon appearance or when cancelled during fade-out.

Here is the caller graph for this function:

◆ OnControllerThemeChanged()

void GWG.WindowFramework.WindowFrameContextMenu.OnControllerThemeChanged ( System.Collections.Generic.List< StyleSheet > newSheets,
System.Collections.Generic.List< StyleSheet > oldSheets )
inlineprivate

Updates an open menu through the existing controller notification, with no resource lookup.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ OnGlobalPointerDown()

void GWG.WindowFramework.WindowFrameContextMenu.OnGlobalPointerDown ( PointerDownEvent evt)
inlineprivate
Here is the call graph for this function:
Here is the caller graph for this function:

◆ OnMouseEnter()

void GWG.WindowFramework.WindowFrameContextMenu.OnMouseEnter ( MouseEnterEvent evt)
inlineprivate
Here is the call graph for this function:
Here is the caller graph for this function:

◆ OnMouseLeave()

void GWG.WindowFramework.WindowFrameContextMenu.OnMouseLeave ( MouseLeaveEvent evt)
inlineprivate
Here is the call graph for this function:
Here is the caller graph for this function:

◆ OnMouseLeaveWindow()

void GWG.WindowFramework.WindowFrameContextMenu.OnMouseLeaveWindow ( MouseLeaveWindowEvent evt)
inlineprivate
Here is the call graph for this function:
Here is the caller graph for this function:

◆ OnNavCancel()

void GWG.WindowFramework.WindowFrameContextMenu.OnNavCancel ( NavigationCancelEvent evt)
inlineprivate
Here is the call graph for this function:
Here is the caller graph for this function:

◆ OnPointerDown()

void GWG.WindowFramework.WindowFrameContextMenu.OnPointerDown ( PointerDownEvent evt)
inlineprivate
Here is the call graph for this function:
Here is the caller graph for this function:

◆ OnThemeDetached()

void GWG.WindowFramework.WindowFrameContextMenu.OnThemeDetached ( DetachFromPanelEvent evt)
inlineprivate

Releases theme notifications and owned references on external removal as well as explicit dismissal.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ RemoveNow()

void GWG.WindowFramework.WindowFrameContextMenu.RemoveNow ( )
inline

Immediately removes the context menu from the visual hierarchy and performs complete cleanup.

Stops any active fade tasks, unregisters all event callbacks from the menu and root container, removes the element from its parent hierarchy, and updates active window tracking.

// Dismiss active context menu immediately
contextMenu.RemoveNow();
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Show()

void GWG.WindowFramework.WindowFrameContextMenu.Show ( Vector2 mousePosition,
ContextMenuConfig config,
VisualElement target,
Action onClose,
bool selfAdd = true )
inline

Displays the context menu at the specified position with the given configuration and event handlers.

Parameters
mousePositionRetained input position argument; current layout anchors to target bounds instead.
configNonnull configuration/list containing nonnull items and valid state predicates.
targetNonnull trigger element used for host selection and layout anchoring.
onCloseOptional callback after successful enabled item action/removal; not a general dismissal notification.
selfAddIf true, mount in controller root, target panel root or target fallback.

A background target may be refused by active modal ownership without creating a menu. Visible nonseparator items require nonnull IsChecked and IsDisabled predicates. These and IsVisible are evaluated while constructing the menu; they are not continuously rebound. Action/predicate exceptions propagate. The argument onClose is invoked for successful item activation only, not outside click, fade, navigation cancel or RemoveNow. Prefer a fresh instance per presentation; RemoveNow performs root-callback and picking-mode restoration.

This method orchestrates the complete context menu display process with sophisticated positioning and configuration logic:

Container Management:

  • Determines appropriate root container (WindowFrameController.UIRoot or target panel)
  • Removes any existing context menu to prevent duplicates
  • Optionally adds itself to the container hierarchy

Event Registration:

  • MouseLeave/MouseLeaveWindow: Triggers fade-out sequence
  • KeyDown (any key): Immediately closes menu
  • Outside PointerDown: Immediately closes menu when clicking outside
  • Outside Application Window (MouseLeaveWindowEvent): Immediately closes menu
  • NavigationCancel: Immediate dismissal (Escape key support)

Menu Structure Creation:

  • Creates wrapper container with appropriate styling classes
  • Adds optional title if specified in configuration
  • Processes all menu items with visibility, state, and action handling
  • Adds separators and handles empty menu scenarios

Theming and Positioning:

  • Applies current theme stylesheets from WindowFrameController
  • Calculates optimal position considering target bounds and screen boundaries
  • Adjusts position to ensure menu remains fully visible

The method provides intelligent defaults while allowing full customization through the configuration object and callback parameters.

var config = new ContextMenuConfig { Title = "Advanced Options" };
config.Items.Add(new ContextMenuItem("Edit", () => UnityEngine.Debug.Log("Edit")) {
IsVisible = () => true, IsDisabled = () => false, IsChecked = () => false
});
config.Items.Add(new ContextMenuItem());
new WindowFrameContextMenu().Show(target.worldBound.center, config, target, null);
A sophisticated context menu implementation for the Window Framework that provides dynamic menu creat...
Definition WindowFrameContextMenu.cs:60
void Show(Vector2 mousePosition, ContextMenuConfig config, VisualElement target, Action onClose, bool selfAdd=true)
Displays the context menu at the specified position with the given configuration and event handlers.
Definition WindowFrameContextMenu.cs:196
Here is the call graph for this function:

◆ StartFadeOut()

void GWG.WindowFramework.WindowFrameContextMenu.StartFadeOut ( )
inlineprivate

Performs the frame-by-frame fade-out animation smoothly without abrupt opacity changes.

Here is the call graph for this function:
Here is the caller graph for this function:

Field Documentation

◆ _currentOpacity

float GWG.WindowFramework.WindowFrameContextMenu._currentOpacity = 1f
private

◆ _delay

float GWG.WindowFramework.WindowFrameContextMenu._delay
private

The delay in seconds before the fade-out animation begins after the mouse leaves the menu area.

This value is retrieved from WindowFrameController.ContextMenuFadeDelay during menu display and provides users time to return their cursor to the menu before it starts fading away. This prevents accidental menu dismissal during cursor movements between menu items.

◆ _fadeTime

float GWG.WindowFramework.WindowFrameContextMenu._fadeTime
private

The duration in seconds for the fade-out animation effect.

This value is retrieved from WindowFrameController.ContextMenuFadeTime during menu display and cached for consistent animation behavior throughout the menu's lifecycle. A value of 0 results in instant disappearance without fade animation.

◆ _globalPointerDownCallback

EventCallback<PointerDownEvent> GWG.WindowFramework.WindowFrameContextMenu._globalPointerDownCallback
private

◆ _mouseEnterCallback

EventCallback<MouseEnterEvent> GWG.WindowFramework.WindowFrameContextMenu._mouseEnterCallback
private

◆ _mouseLeaveCallback

EventCallback<MouseLeaveEvent> GWG.WindowFramework.WindowFrameContextMenu._mouseLeaveCallback
private

◆ _mouseLeaveWindowCallback

EventCallback<MouseLeaveWindowEvent> GWG.WindowFramework.WindowFrameContextMenu._mouseLeaveWindowCallback
private

◆ _navCancelCallback

EventCallback<NavigationCancelEvent> GWG.WindowFramework.WindowFrameContextMenu._navCancelCallback
private

◆ _ownedThemeSheets

readonly System.Collections.Generic.List<StyleSheet> GWG.WindowFramework.WindowFrameContextMenu._ownedThemeSheets = new System.Collections.Generic.List<StyleSheet>()
private

◆ _pointerDownCallback

EventCallback<PointerDownEvent> GWG.WindowFramework.WindowFrameContextMenu._pointerDownCallback
private

◆ _previousRootPickingMode

PickingMode GWG.WindowFramework.WindowFrameContextMenu._previousRootPickingMode = PickingMode.Ignore
private

◆ _restoredRootPickingMode

bool GWG.WindowFramework.WindowFrameContextMenu._restoredRootPickingMode = false
private

◆ _rootContainer

VisualElement GWG.WindowFramework.WindowFrameContextMenu._rootContainer
private

◆ _task

IVisualElementScheduledItem GWG.WindowFramework.WindowFrameContextMenu._task
private

Reference to the scheduled task managing fade-out animation and menu removal.

This task handles the timing and execution of fade-out effects and final menu removal. It can be paused or canceled when immediate menu dismissal is required, such as when the user clicks a menu item or presses the Escape KeyValue.

◆ _wrapper

VisualElement GWG.WindowFramework.WindowFrameContextMenu._wrapper
private