Window Framework v1.2.4
Window Framework for Unity UI Toolkit
Loading...
Searching...
No Matches
GWG.WindowFramework.Manipulators.ContextMenuActivator Class Reference

A mouse manipulator that enables context menu functionality for any VisualElement in Unity's UI Toolkit. More...

Inheritance diagram for GWG.WindowFramework.Manipulators.ContextMenuActivator:

Public Member Functions

 ContextMenuActivator (ContextMenuConfig contextMenuConfig, int clickCount=1, MouseButton button=MouseButton.RightMouse)
 Initializes a new ContextMenuActivator with the specified configuration and activation settings.
void ShowContextMenu (Vector2 mousePosition)
 Displays the context menu at the specified position using the configured menu structure.

Protected Member Functions

override void RegisterCallbacksOnTarget ()
 Registers event callbacks on the target element to handle context menu activation.
override void UnregisterCallbacksFromTarget ()
 Unregisters event callbacks from the target element during cleanup.

Private Member Functions

void OnMouseDown (MouseDownEvent evt)
 Handles mouse down events to activate the context menu when conditions are met.

Private Attributes

ContextMenuConfig contextMenuConfig
 The configuration object defining the context menu structure, items, and actions.

Detailed Description

This manipulator provides flexible context menu activation with customizable trigger conditions. It integrates seamlessly with the Window Framework's context menu system and tooltip management.

Key Features:

  • Configurable mouse button and click count activation
  • Integration with WindowFrameContextMenu system
  • Automatic tooltip hiding during menu activation
  • Keyboard navigation support (NavigationSubmitEvent)
  • Event propagation control for clean interaction
  • Customizable menu positioning

Default Behavior:

  • Activates on single right-click
  • Shows context menu at cursor position
  • Integrates with tooltip system to prevent conflicts
  • Supports both mouse and keyboard activation

The manipulator requires a ContextMenuConfig object that defines the menu structure, items, and associated actions. This configuration-based approach allows for flexible menu customization without modifying the activation logic.

// Basic context menu setup
var menuConfig = new ContextMenuConfig();
menuConfig.AddItem("Copy", () => Debug.Log("Copy action"));
menuConfig.AddItem("Paste", () => Debug.Log("Paste action"));
menuConfig.AddSeparator();
menuConfig.AddItem("Delete", () => Debug.Log("Delete action"));
var button = new Button("Right-click me");
button.AddManipulator(new ContextMenuActivator(menuConfig));
// Custom activation (double right-click)
var specialElement = new VisualElement();
specialElement.AddManipulator(new ContextMenuActivator(menuConfig, clickCount: 2));
// Left-click context menu (non-standard but supported)
var leftClickMenu = new VisualElement();
leftClickMenu.AddManipulator(new ContextMenuActivator(menuConfig, button: MouseButton.LeftMouse));
// Complex menu configuration
var advancedConfig = new ContextMenuConfig();
advancedConfig.AddItem("Edit", () => StartEdit(), enabled: CanEdit());
advancedConfig.AddSubmenu("Transform", subItems => {
subItems.AddItem("Rotate 90°", () => Rotate90());
subItems.AddItem("Flip Horizontal", () => FlipH());
subItems.AddItem("Reset", () => ResetTransform());
});
myImage.AddManipulator(new ContextMenuActivator(advancedConfig));
Configuration class for a runtime context menu.
Definition ContextMenuConfig.cs:22
ContextMenuActivator(ContextMenuConfig contextMenuConfig, int clickCount=1, MouseButton button=MouseButton.RightMouse)
Initializes a new ContextMenuActivator with the specified configuration and activation settings.
Definition ContextMenuActivator.cs:129

Constructor & Destructor Documentation

◆ ContextMenuActivator()

GWG.WindowFramework.Manipulators.ContextMenuActivator.ContextMenuActivator ( ContextMenuConfig contextMenuConfig,
int clickCount = 1,
MouseButton button = MouseButton::RightMouse )
Parameters
contextMenuConfigThe configuration object defining the context menu structure and actions
clickCountThe number of clicks required to activate the context menu. Default: 1
buttonThe mouse button that triggers the context menu. Default: MouseButton.RightMouse

The constructor configures the manipulator's activation filter based on the provided parameters. This allows for flexible context menu activation patterns to suit different UI design requirements.

Common Activation Patterns:

  • Single right-click (default): Standard context menu behavior
  • Double right-click: Prevents accidental menu activation
  • Left-click: Alternative activation for touch-friendly interfaces
  • Middle-click: Special-purpose context menus

The contextMenuConfig parameter is required and must contain properly configured menu items and actions. The configuration is validated when the menu is displayed.

// Standard right-click context menu
var standardActivator = new ContextMenuActivator(myMenuConfig);
// Double right-click to prevent accidental activation
var doubleClickActivator = new ContextMenuActivator(myMenuConfig, clickCount: 2);
// Left-click context menu (alternative activation)
var leftClickActivator = new ContextMenuActivator(myMenuConfig, button: MouseButton.LeftMouse);
// Middle-click for special actions
var middleClickActivator = new ContextMenuActivator(specialConfig, button: MouseButton.MiddleMouse);
// Triple-click for advanced users
var expertActivator = new ContextMenuActivator(expertConfig, clickCount: 3);
// Apply to elements
myButton.AddManipulator(standardActivator);
expertPanel.AddManipulator(expertActivator);

Member Function Documentation

◆ OnMouseDown()

void GWG.WindowFramework.Manipulators.ContextMenuActivator.OnMouseDown ( MouseDownEvent evt)
private
Parameters
evtThe mouse down event data containing button information and cursor position

This method processes mouse down events and determines whether to activate the context menu based on the configured activation criteria:

Validation Process:

  1. Checks if the manipulation can start (correct button, click count, etc.)
  2. Validates that the mouse button matches the configured activation button
  3. Ensures the click count meets the specified requirements

Activation Process:

  1. Closes any active tooltips to prevent UI conflicts
  2. Stops event propagation to prevent other handlers from processing the event
  3. Shows the context menu at the current mouse cursor position

The method integrates with the Window Framework's tooltip system to ensure clean UI behavior by hiding tooltips before showing context menus.

// OnMouseDown is triggered automatically when user clicks the element
// Example activation flow:
// 1. User right-clicks element (assuming default configuration)
// 2. OnMouseDown receives MouseDownEvent
// 3. CanStartManipulation() validates:
// - Button matches MouseButton.RightMouse ✓
// - Click count matches 1 ✓
// - Other conditions met ✓
// 4. Active tooltips are closed
// 5. Event propagation stopped
// 6. ShowContextMenu() called with mouse position
// Example with custom configuration:
// var activator = new ContextMenuActivator(config, clickCount: 2, button: MouseButton.LeftMouse);
// Requires: Double left-click to activate
// Integration with tooltip system:
// - Any visible tooltip immediately hidden
// - Prevents tooltip/context menu conflicts
// - Ensures clean visual transition

◆ RegisterCallbacksOnTarget()

override void GWG.WindowFramework.Manipulators.ContextMenuActivator.RegisterCallbacksOnTarget ( )
protected

This method establishes the event handling infrastructure for context menu activation by registering callbacks for two primary activation methods:

Mouse Activation:

  • MouseDownEvent: Handles mouse-based context menu activation
  • Uses TrickleDown phase to catch events early in the event flow
  • Respects the configured mouse button and click count settings

Keyboard Activation:

  • NavigationSubmitEvent: Provides accessibility support
  • Allows keyboard-only users to access context menus
  • Typically triggered by Enter key or similar navigation inputs

The TrickleDown registration ensures that the context menu activation is processed before other elements can intercept the mouse events, providing reliable activation behavior in complex UI hierarchies.

// RegisterCallbacksOnTarget is called automatically when manipulator is added
myElement.AddManipulator(new ContextMenuActivator(menuConfig));
// ↑ Automatically registers MouseDown and NavigationSubmit callbacks
// Events that will be handled:
// - MouseDownEvent (TrickleDown phase) → Mouse activation
// - NavigationSubmitEvent → Keyboard activation
// Example activation scenarios:
// 1. User right-clicks element → MouseDownEvent → ShowContextMenu()
// 2. User navigates to element and presses Enter → NavigationSubmitEvent → ShowContextMenu()
// 3. User navigates to element and presses Menu key → NavigationSubmitEvent → ShowContextMenu()

◆ ShowContextMenu()

void GWG.WindowFramework.Manipulators.ContextMenuActivator.ShowContextMenu ( Vector2 mousePosition)
Parameters
mousePositionThe screen position where the context menu should appear

This method creates and displays a context menu using the Window Framework's context menu system. It handles the complete menu lifecycle from creation to cleanup:

Menu Creation:

Display Configuration:

  • Positions the menu at the specified mouse coordinates
  • Enables modal behavior for proper interaction handling
  • Sets up automatic cleanup when the menu is dismissed

The method includes a callback mechanism that is triggered when the menu closes, allowing for post-menu cleanup or state updates if needed.

// ShowContextMenu is called automatically by event handlers
// But can also be called programmatically for custom scenarios:
// Manual context menu activation
public void ShowCustomContextMenu()
{
Vector2 centerPosition = new Vector2(Screen.width / 2, Screen.height / 2);
contextMenuActivator.ShowContextMenu(centerPosition);
}
// Context menu positioning examples:
// 1. At mouse cursor (standard): ShowContextMenu(evt.mousePosition)
// 2. At element center: ShowContextMenu(element.worldBound.center)
// 3. At screen center: ShowContextMenu(new Vector2(Screen.width/2, Screen.height/2))
// 4. Offset from cursor: ShowContextMenu(evt.mousePosition + Vector2.right * 50)
// The context menu will:
// - Display at the specified position
// - Show all configured menu items
// - Handle user interactions
// - Execute associated actions when items are selected
// - Clean up automatically when dismissed
// - Trigger the close callback for additional cleanup

◆ UnregisterCallbacksFromTarget()

override void GWG.WindowFramework.Manipulators.ContextMenuActivator.UnregisterCallbacksFromTarget ( )
protected

This method performs cleanup by removing the event callbacks that were registered during initialization. It ensures proper resource management and prevents memory leaks when the manipulator is removed or the element is destroyed.

The method attempts to unregister both mouse and navigation event callbacks to maintain cleanup symmetry with the registration process. Debug logging is included to assist with troubleshooting callback lifecycle issues.

Note: The NavigationSubmitEvent unregistration uses an empty lambda as Unity's UI Toolkit requires the exact same callback delegate reference for proper unregistration. In practice, this specific pattern may need refinement for complete cleanup.

// UnregisterCallbacksFromTarget is called automatically when manipulator is removed
myElement.RemoveManipulator(existingContextMenuActivator);
// ↑ Automatically unregisters all event callbacks
// Also called when element is destroyed
myElement.RemoveFromHierarchy();
// ↑ Triggers cleanup including callback unregistration
// Debug output helps verify cleanup:
// "Unregistering callbacks from target" appears in console
// Callbacks removed:
// ✓ MouseDownEvent (with TrickleDown)
// ✓ NavigationSubmitEvent (partial - see remarks)

Member Data Documentation

◆ contextMenuConfig

ContextMenuConfig GWG.WindowFramework.Manipulators.ContextMenuActivator.contextMenuConfig
private

This configuration contains all the information needed to build and display the context menu, including:

  • Menu items and their associated actions
  • Submenu structures and hierarchies
  • Item enabled/disabled states
  • Separators and visual grouping
  • Custom styling and appearance settings

The configuration is provided during construction and used whenever the context menu needs to be displayed.