Files
Terminal.Gui/docfx/docs/command.md
Tig a84b2c4896 Fixes #4419, #4148, #4408 - Toplevel is GONE - Replaced by Runnable (#4422)
* WIP: Broken

* Got working. Mostly.

* Parllel tests pass

* More progres

* Fixed app tests.

* Mouse

* more progress.

* working on shortcut

* Shortcut accept on ENTER is broken.

* One left...

* More test progress.

* All unit tests pass. Still some issues though.

* tweak

* Fixed Integration Tests

* Fixed UI Catalog

* Tweaking CP to try to find race condition

* Refactor StandardColors and improve ColorPicker logic

Refactored `StandardColors` to use lazy initialization for static fields, improving performance and avoiding static constructor convoy effects. Introduced `NamesValueFactory` and `MapValueFactory` methods for encapsulated initialization logic.

Simplified `GetColorNames` to directly return `_names.Value`. Improved `TryParseColor` by clarifying default value usage and adopting object initializer syntax. Updated `TryNameColor` to use `_argbNameMap.Value`.

Refactored `GetArgb` for better readability. Replaced `MultiStandardColorNameResolver` with `StandardColorsNameResolver` in `ColorPicker`. Commented out `app.Init("Fake")` in `ColorPickerTests` for testing purposes.

Made minor formatting improvements, including updated comments and XML documentation for consistency.

* revert

* Throttle input loop to prevent CPU spinning

Introduce a 20ms delay in the input loop of `InputImpl<TInputRecord>`
to prevent excessive CPU usage when no input is available. Removed
the `DateTime dt = Now();` line and the `while (Peek())` block, which
previously enqueued input records.

This change improves resource management, especially in scenarios
where multiple `ApplicationImpl` instances are created in parallel
tests without calling `Shutdown()`. It prevents thread pool
exhaustion and ensures better performance in such cases.

* Refactor ApplicationImpl to use IDisposable pattern

Implemented the IDisposable pattern in ApplicationImpl to improve resource management. Added `Dispose` and `DisposeCore` methods, and marked the `Shutdown` method as obsolete, encouraging the use of `Dispose` or `using` statements instead. Updated the `IApplication` interface to inherit from IDisposable and added `GetResult` methods for retrieving run session results.

Refactored unit tests to adopt the new lifecycle management approach, replacing legacy `Shutdown` calls with `Dispose` or `using`. Removed fragile and obsolete tests, and re-enabled previously skipped tests after addressing underlying issues.

Updated `FakeApplicationLifecycle` and `SetupFakeApplicationAttribute` to align with the new disposal pattern. Improved documentation and examples to guide users toward modern usage patterns. Maintained backward compatibility for legacy singleton usage.

* Add IDisposable pattern with input loop throttling

- Add IDisposable to IApplication for proper resource cleanup
- Add 20ms throttle to input loop (prevents CPU spinning)
- Add Lazy<T> to StandardColors (eliminates convoy effect)
- Add MainLoopCoordinatorTests suite (5 new tests)
- Add Dispose() calls to all 16 ColorPickerTests
- Mark Application.Shutdown() as [Obsolete]

IApplication now requires Dispose() for cleanup

Performance: 100x CPU reduction, 15x faster disposal, tests complete in <5s

Fixes: Thread leaks, CPU saturation, test hangs in parallel execution
Docs: Updated application.md and newinv2.md with disposal patterns

* Refactor test for input loop throttling clarity

Updated `InputLoop_Throttle_Limits_Poll_Rate` test to improve clarity, reliability, and efficiency:
- Rewrote summary comment to clarify purpose and emphasize the 20ms throttle's role in preventing CPU spinning.
- Replaced `var` with explicit types for better readability.
- Reduced test duration from 1s to 500ms to improve test speed.
- Revised assertions:
  - Replaced range-based assertion with upper-bound check to ensure poll count is below 500, avoiding timing sensitivity issues.
  - Added assertion to verify the thread ran and was not immediately canceled.
- Added a 2-second timeout to `inputTask.Wait` and verified task completion.
- Improved comments to explain test behavior and reasoning behind changes.

* tweaks

* Fix nullabiltiy stuff.

* runnable fixes

* more nullabe

* More nullability

* warnings gone

* Fixed fluent test failure.

* Refactor ApplicationImpl and update Runnable layout logic

Refactored `ApplicationImpl.Run.cs` for improved readability and
atomicity:
- Combined `if (wasModal)` with `SessionStack?.TryPop` to streamline
  logic.
- Simplified restoration of `previousRunnable` by reducing nesting.
- Updated comments for clarity and retained `SetIsModal` call.

Simplified focus-setting logic in `ApplicationImpl.Run.cs` using
pattern matching for `TopRunnableView`.

In `Runnable<TResult>`, added `SetNeedsLayout` after `IsModalChanged`
to ensure layout updates. Removed an unused empty line for cleanup.

Corrected namespace in `GetViewsUnderLocationForRootTests.cs` to
align with test structure.

* Update layout on modal state change

A call to `SetNeedsLayout()` was added to the `OnIsModalChanged`
method in the `Runnable` class. This ensures that the layout
is updated whenever the modal state changes.

* Increase test timeout for inputTask.Wait to 10 seconds

Extended the timeout duration for the `inputTask.Wait` method
from 4 seconds to 10 seconds in `MainLoopCoordinatorTests`.
This change ensures the test has a longer window to complete
under conditions of increased load or slower execution
environments, reducing the likelihood of false test failures.

* Refactor project files and simplify test logic

Removed `<LangVersion>` and `<ImplicitUsings>` properties from
`UnitTests.csproj` and `UnitTests.Parallelizable.csproj` to rely
on default SDK settings and disable implicit global usings.

Simplified the `SizeChanged_Event_Still_Fires_For_Compatibility`
test in `FakeDriverTests` by removing the `screenChangedFired`
variable, its associated event handler, and related assertions.
Also removed obsolete warning suppression directives as they
are no longer needed.

* Reduce UnitTestsParallelizable iterations from 10 to 3

Reduced the number of iterations for the UnitTestsParallelizable
test suite from 10 to 3 to save time and resources while still
exposing concurrency issues. Updated the loop and log messages
to reflect the new iteration count.

* disabled InputLoop_Throttle_Limits_Poll_Rate

* Refactor app lifecycle and improve Runnable API

Refactored `Program.cs` to simplify application lifecycle:
- Modularized app creation, initialization, and disposal.
- Improved result handling and ensured proper resource cleanup.

Re-implemented `Runnable<TResult>` with a cleaner design:
- Retained functionality while improving readability and structure.
- Added XML documentation and followed the Cancellable Work Pattern.

Re-implemented `RunnableWrapper<TView, TResult>`:
- Enabled wrapping any `View` to make it runnable with typed results.
- Added examples and remarks for better developer guidance.

Re-implemented `ViewRunnableExtensions`:
- Provided fluent API for making views runnable with or without results.
- Enhanced documentation with examples for common use cases.

General improvements:
- Enhanced code readability, maintainability, and error handling.
- Replaced redundant code with cleaner, more maintainable versions.

* Modernize codebase for Terminal.Gui and MVVM updates

Refactored `LoginView` to remove redundant `Application.LayoutAndDraw()`
call. Enhanced `LoginViewModel` with new observable properties for
automatic property change notifications. Updated `Message` class to use
nullable generics for improved type safety.

Replaced legacy `Application.Init()` and `Application.Run()` calls with
the modern `IApplication` API across `Program.cs`, `Example.cs`, and
`ReactiveExample`. Ensured proper disposal of `IApplication` instances
to prevent resource leaks.

Updated `TerminalScheduler` to integrate with `IApplication` for
invoking actions and managing timeouts. Added null checks and improved
timeout disposal logic for robustness.

Refactored `ExampleWindow` for better readability and alignment with
modern `Terminal.Gui` conventions. Cleaned up unused imports and
improved code clarity across the codebase.

Updated README.md to reflect the latest `Terminal.Gui` practices,
including examples of the `IApplication` API and automatic UI refresh
handling. Renamed `LoginAction` to `LoginActions` for consistency.

* Refactor: Transition to IRunnable-based architecture

Replaced `Toplevel` with `Window` as the primary top-level UI element. Introduced the `IRunnable` interface to modernize the architecture, enabling greater flexibility and testability. Deprecated the static `Application` class in favor of the instance-based `IApplication` model, which supports multiple application contexts.

Updated methods like `Application.Run()` and `Application.RequestStop()` to use `IRunnable`. Removed or replaced legacy `Modal` properties with `IsModal`. Enhanced the `IApplication` interface with a fluent API, including methods like `Run<TRunnable>()` and `GetResult<T>()`.

Refactored tests and examples to align with the new architecture. Updated documentation to reflect the instance-based model. Deprecated obsolete members and methods, including `Application.Current` and `Application.TopRunnable`.

Improved event handling by replacing the `Accept` event with `Accepting` and using `e.Handled` for event processing. Updated threading examples to use `App?.Invoke()` or `app.Invoke()` for UI updates. Cleaned up redundant code and redefined modal behavior for better consistency.

These changes modernize the `Terminal.Gui` library, improving clarity, usability, and maintainability while ensuring backward compatibility where possible.

* Refactor: Replace Toplevel with Runnable class

This commit introduces a major architectural update to the `Terminal.Gui` library, replacing the legacy `Toplevel` class with the new `Runnable` class. The changes span the entire codebase, including core functionality, tests, documentation, and configuration files.

- **Core Class Replacement**:
  - Replaced `Toplevel` with `Runnable` as the base class for modal views and session management.
  - Updated all references to `Toplevel` in the codebase, including constructors, methods, and properties.

- **Configuration Updates**:
  - Updated `tui-config-schema.json` to reflect the new `Runnable` scheme.

- **New Classes**:
  - Added `UICatalogRunnable` for managing the UI Catalog application.
  - Introduced `Runnable<TResult>` as a generic base class for blocking sessions with result handling.

- **Documentation and Tests**:
  - Updated documentation to emphasize `Runnable` and mark `Toplevel` as obsolete.
  - Refactored test cases to use `Runnable` and ensure compatibility.

- **Behavioral Improvements**:
  - Enhanced lifecycle management and alignment with the `IRunnable` interface.
  - Improved clarity and consistency in naming conventions.

These changes modernize the library, improve flexibility, and provide a clearer architecture for developers.

* Refactor: Consolidate Runnable classes and decouple View from ApplicationImpl

- Made Runnable<TResult> inherit from Runnable (eliminating ~180 LOC duplication)
- Moved View init/layout/cursor logic from ApplicationImpl to Runnable lifecycle events
- ApplicationImpl.Begin now operates purely on IRunnable interface

Related to #4419

* Simplified the disposal logic in `ApplicationImpl.Run.cs` by replacing
the type-specific check for `View` with a more general check for
`IDisposable`. This ensures proper disposal of any `IDisposable`
object, improving robustness.

Removed the `FrameworkOwnedRunnable` property from the `ApplicationImpl`
class in `ApplicationImpl.cs` and the `IApplication` interface in
`IApplication.cs`. This eliminates the need to manage this property,
reducing complexity and improving maintainability.

Updated `application.md` to reflect the removal of the
`FrameworkOwnedRunnable` property, ensuring the documentation aligns
with the updated codebase.

* Replaces the legacy `Shutdown()` method with `Dispose()` to align
with the `IDisposable` pattern, ensuring proper resource cleanup
and simplifying the API. The `Dispose()` method is now the
recommended way to release resources, with `using` statements
encouraged for automatic disposal.

Key changes:
- Marked `Shutdown()` as obsolete; it now internally calls `Dispose()`.
- Updated the fluent API to remove `Shutdown()` from chaining.
- Enhanced session lifecycle management for thread safety.
- Updated tests to validate proper disposal and state reset.
- Improved `IRunnable` integration with automatic disposal for
  framework-created runnables.
- Maintained backward compatibility for the legacy static
  `Application` singleton.
- Refactored documentation and examples to reflect modern practices
  and emphasize `Dispose()` usage.

These changes modernize the `Terminal.Gui` lifecycle, improve
testability, and encourage alignment with .NET conventions.

* Refactor runnable app context handling in ApplicationImpl

Refactor how the application context is set for `runnable` objects
by introducing a new `SetApp` method in the `IRunnable` interface.
This replaces the previous logic of directly setting the `App`
property for `View` objects, making the process more generic and
encapsulated within `IRunnable` implementations.

Simplify `Mouse.UngrabMouse()` by removing the conditional check
and calling it unconditionally.

Make a minor formatting adjustment in the generic constraint of
`Run<TRunnable>` in `ApplicationImpl`.

Add `SetApp(IApplication app)` to the `IRunnable` interface and
implement it in the `Runnable` class to set the `App` property
to the provided application instance.

* Improve docs, tests, and modularity across the codebase

Reorganized and updated `CONTRIBUTING.md`:
- Added **Key Architecture Concepts** section and reordered the table of contents.
- Updated testing requirements to discourage legacy patterns.
- Added instructions for replicating CI workflows locally.
- Clarified PR guidelines and coding style expectations.

Enhanced `README.md` with detailed CI/CD workflow documentation.

Refactored `ColorPicker.Prompt` to use `IApplication` for improved modularity and testability.

Introduced `IApplicationScreenChangedTests` for comprehensive testing of `ScreenChanged` events and `Screen` property.

Refactored `ApplicationScreenTests` and `TextView.PromptForColors` to align with modern patterns.

Updated `Terminal.sln` to include `.github/workflows/README.md`.

Performed general cleanup:
- Removed outdated documentation links.
- Improved XML documentation and coding consistency.

* readme tweaks

* Improve thread safety, layout, and test coverage

Refactored `OutputBufferImpl.cs` to enhance thread safety by locking shared resources and adding bounds checks for columns and rows. Improved handling of wide characters and removed outdated TODO comments.

Updated `Runnable.cs` to call `SetNeedsDraw()` on modal state changes, ensuring proper layout and drawing updates. Simplified layout handling in `ApplicationImpl.Run.cs` by replacing redundant comments with a `LayoutAndDraw()` call.

Added a check in `AllViewsTester.cs` to skip creating instances of `RunnableWrapper` types with unsatisfiable generic constraints, logging a warning when encountered.

Enhanced `ListViewTests.cs` by adding explicit `app.LayoutAndDraw()` calls to validate visual output and ensure tests reflect the updated application state.

These changes improve robustness, prevent race conditions, and ensure consistent behavior across the application.

* Refactor: Rename Toplevel to Runnable and update logic

Updated the `Border` class to use `Command.Quit` instead of
`Command.QuitToplevel` in the `CloseButton.Accept` handler.

Renamed test methods in `GetViewsAtLocationTests.cs` to replace
"Toplevel" with "Runnable" for consistency. Updated `Runnable<bool>`
instances to use "topRunnable" as the `Id` property.

These changes align the codebase with updated naming conventions
and improve clarity.

* Removed `ToplevelTests` and migrated relevant test cases to
`MouseDragTests` with improved structure and coverage. Updated
tests to use `Application.Create`, `app.Begin`, and `app.End`
for better resource management and lifecycle handling.

Replaced direct event handling with `app.Mouse.RaiseMouseEvent`
to align with the application's event-handling mechanism. Added
`Runnable` objects to ensure views are properly initialized and
disposed of within the application context.

Enhanced tests to include assertions for minimum width and
height constraints during resize operations. Removed redundant
tests and streamlined logic to reduce duplication and improve
maintainability.

* Reorged Unit Test namespaces.

* more

* Refactor tests and update namespaces for consistency

Updated namespaces in `ArrangementTests.cs` and `MouseDragTests.cs` for better organization. Enhanced `ArrangementTests.cs` with additional checks for arrangement flags. Reformatted and re-added `MouseDragTests.cs` and `SchemeTests.cs` with modern C# features like nullable annotations and object initializers. Ensured no functional changes while improving code clarity and consistency.

* Fix nullability warnings in MouseDragTests.cs

Updated `app.End` calls to use the null-forgiving operator (`!`)
on `app.SessionStack` to ensure it is treated as non-null.
This change addresses potential nullability warnings and
improves code safety and clarity. Applied consistently across
all relevant test cases in the `MouseDragTests` class.
2025-12-01 12:54:21 -07:00

50 KiB
Raw Blame History

Deep Dive into Command and View.Command in Terminal.Gui

See Also

Overview

The Command system in Terminal.Gui provides a standardized framework for defining and executing actions that views can perform, such as selecting items, accepting input, or navigating content. Implemented primarily through the View.Command APIs, this system integrates tightly with input handling (e.g., keyboard and mouse events) and leverages the Cancellable Work Pattern to ensure extensibility, cancellation, and decoupling. Central to this system are the Selecting and Accepting events, which encapsulate common user interactions: Selecting for changing a views state or preparing it for interaction (e.g., toggling a checkbox, focusing a menu item), and Accepting for confirming an action or state (e.g., executing a menu command, submitting a dialog).

This deep dive explores the Command and View.Command APIs, focusing on the Selecting and Accepting concepts, their implementation, and their propagation behavior. It critically evaluates the need for additional events (Selected/Accepted) and the propagation of Selecting events, drawing on insights from Menu, MenuItemv2, MenuBar, CheckBox, and FlagSelector. These implementations highlight the systems application in hierarchical (menus) and stateful (checkboxes, flag selectors) contexts. The document reflects the current implementation, including the Cancel property in CommandEventArgs and local handling of Command.Select. An appendix briefly summarizes proposed changes from a filed issue to rename Command.Select to Command.Activate, replace Cancel with Handled, and introduce a propagation mechanism, addressing limitations in the current system.

Overview of the Command System

The Command system in Terminal.Gui defines a set of standard actions via the Command enum (e.g., Command.Select, Command.Accept, Command.HotKey, Command.StartOfPage). These actions are triggered by user inputs (e.g., key presses, mouse clicks) or programmatically, enabling consistent view interactions.

Key Components

  • Command Enum: Defines actions like Select (state change or interaction preparation), Accept (action confirmation), HotKey (hotkey activation), and others (e.g., StartOfPage for navigation).
  • Command Handlers: Views register handlers using View.AddCommand, specifying a CommandImplementation delegate that returns bool? (null: no command executed; false: executed but not handled; true: handled or canceled).
  • Command Routing: Commands are invoked via View.InvokeCommand, executing the handler or raising CommandNotBound if no handler exists.
  • Cancellable Work Pattern: Command execution uses events (e.g., Selecting, Accepting) and virtual methods (e.g., OnSelecting, OnAccepting) for modification or cancellation, with Cancel indicating processing should stop.

Role in Terminal.Gui

The Command system bridges user input and view behavior, enabling:

  • Consistency: Standard commands ensure predictable interactions (e.g., Enter triggers Accept in buttons, menus, checkboxes).
  • Extensibility: Custom handlers and events allow behavior customization.
  • Decoupling: Events reduce reliance on sub-classing, though current propagation mechanisms may require subview-superview coordination.

Note on Cancel Property

The CommandEventArgs class uses a Cancel property to indicate that a command event (e.g., Accepting) should stop processing. This is misleading, as it implies action negation rather than completion. A filed issue proposes replacing Cancel with Handled to align with input events (e.g., Key.Handled). This document uses Cancel to reflect the current implementation, with the appendix summarizing the proposed change.

Implementation in View.Command

The View.Command APIs in the View class provide infrastructure for registering, invoking, and routing commands, adhering to the Cancellable Work Pattern.

Command Registration

Views register commands using View.AddCommand, associating a Command with a CommandImplementation delegate. The delegates bool? return controls processing flow.

Example: Default commands in View.SetupCommands:

private void SetupCommands()
{
    AddCommand(Command.Accept, RaiseAccepting);
    AddCommand(Command.Select, ctx =>
    {
        if (RaiseSelecting(ctx) is true)
        {
            return true;
        }
        if (CanFocus)
        {
            SetFocus();
            return true;
        }
        return false;
    });
    AddCommand(Command.HotKey, () =>
    {
        if (RaiseHandlingHotKey() is true)
        {
            return true;
        }
        SetFocus();
        return true;
    });
    AddCommand(Command.NotBound, RaiseCommandNotBound);
}
  • Default Commands: Accept, Select, HotKey, NotBound.
  • Customization: Views override or add commands (e.g., CheckBox for state toggling, MenuItemv2 for menu actions).

Command Invocation

Commands are invoked via View.InvokeCommand or View.InvokeCommands, passing an ICommandContext for context (e.g., source view, binding details). Unhandled commands trigger CommandNotBound.

Example:

public bool? InvokeCommand(Command command, ICommandContext? ctx)
{
    if (!_commandImplementations.TryGetValue(command, out CommandImplementation? implementation))
    {
        _commandImplementations.TryGetValue(Command.NotBound, out implementation);
    }
    return implementation!(ctx);
}

Command Routing

Most commands route directly to the target view. Command.Select and Command.Accept have special routing:

  • Command.Select: Handled locally, with no propagation to superviews, relying on view-specific events (e.g., SelectedMenuItemChanged in Menu) for hierarchical coordination.
  • Command.Accept: Propagates to a default button (if IsDefault = true), superview, or SuperMenuItem (in menus).

Example: Command.Accept in RaiseAccepting:

protected bool? RaiseAccepting(ICommandContext? ctx)
{
    CommandEventArgs args = new() { Context = ctx };
    args.Cancel = OnAccepting(args) || args.Cancel;
    if (!args.Cancel && Accepting is {})
    {
        Accepting?.Invoke(this, args);
    }
    if (!args.Cancel)
    {
        var isDefaultView = SuperView?.InternalSubViews.FirstOrDefault(v => v is Button { IsDefault: true });
        if (isDefaultView != this && isDefaultView is Button { IsDefault: true } button)
        {
            bool? handled = isDefaultView.InvokeCommand(Command.Accept, ctx);
            if (handled == true)
            {
                return true;
            }
        }
        if (SuperView is {})
        {
            return SuperView?.InvokeCommand(Command.Accept, ctx);
        }
    }
    return args.Cancel;
}

The Selecting and Accepting Concepts

The Selecting and Accepting events, along with their corresponding commands (Command.Select, Command.Accept), are designed to handle the most common user interactions with views:

  • Selecting: Changing a views state or preparing it for further interaction, such as highlighting an item in a list, toggling a checkbox, or focusing a menu item.
  • Accepting: Confirming an action or state, such as submitting a form, activating a button, or finalizing a selection.

These concepts are opinionated, reflecting Terminal.Guis view that most UI interactions can be modeled as either state changes/preparation (selecting) or action confirmations (accepting). Below, we explore each concept, their implementation, use cases, and propagation behavior, using Cancel to reflect the current implementation.

Selecting

  • Definition: Selecting represents a user action that changes a views state or prepares it for further interaction, such as selecting an item in a ListView, toggling a CheckBox, or focusing a MenuItemv2. It is associated with Command.Select, typically triggered by a spacebar press, single mouse click, navigation keys (e.g., arrow keys), or mouse enter (e.g., in menus).

  • Event: The Selecting event is raised by RaiseSelecting, allowing external code to modify or cancel the state change.

  • Virtual Method: OnSelecting enables subclasses to preprocess or cancel the action.

  • Implementation:

    protected bool? RaiseSelecting(ICommandContext? ctx)
    {
        CommandEventArgs args = new() { Context = ctx };
        if (OnSelecting(args) || args.Cancel)
        {
            return true;
        }
        Selecting?.Invoke(this, args);
        return Selecting is null ? null : args.Cancel;
    }
    
    • Default Behavior: Sets focus if CanFocus is true (via SetupCommands).
    • Cancellation: args.Cancel or OnSelecting returning true halts the command.
    • Context: ICommandContext provides invocation details.
  • Use Cases:

    • ListView: Selecting an item (e.g., via arrow keys or mouse click) raises Selecting to update the highlighted item.
    • CheckBox: Toggling the checked state (e.g., via spacebar) raises Selecting to change the state, as seen in the AdvanceAndSelect method:
      private bool? AdvanceAndSelect(ICommandContext? commandContext)
      {
          bool? cancelled = AdvanceCheckState();
          if (cancelled is true)
          {
              return true;
          }
          if (RaiseSelecting(commandContext) is true)
          {
              return true;
          }
          return commandContext?.Command == Command.HotKey ? cancelled : cancelled is false;
      }
      
    • OptionSelector: Selecting an OpitonSelector option raises Selecting to update the selected option.
    • Menu and MenuBar: Selecting a MenuItemv2 (e.g., via mouse enter or arrow keys) sets focus, tracked by SelectedMenuItem and raising SelectedMenuItemChanged:
      protected override void OnFocusedChanged(View? previousFocused, View? focused)
      {
          base.OnFocusedChanged(previousFocused, focused);
          SelectedMenuItem = focused as MenuItemv2;
          RaiseSelectedMenuItemChanged(SelectedMenuItem);
      }
      
    • FlagSelector: Selecting a CheckBox subview toggles a flag, updating the Value property and raising ValueChanged, though it incorrectly triggers Accepting:
      checkbox.Selecting += (sender, args) =>
      {
          if (RaiseSelecting(args.Context) is true)
          {
              args.Cancel = true;
              return;
          }
          if (RaiseAccepting(args.Context) is true)
          {
              args.Cancel = true;
          }
      };
      
    • Views without State: For views like Button, Selecting typically sets focus but does not change state, making it less relevant.
  • Propagation: Command.Select is handled locally by the target view. If the command is unhandled (null or false), processing stops without propagating to the superview or other views. This is evident in Menu, where SelectedMenuItemChanged is used for hierarchical coordination, and in CheckBox and FlagSelector, where state changes are internal.

Accepting

  • Definition: Accepting represents a user action that confirms or finalizes a views state or triggers an action, such as submitting a dialog, activating a button, or confirming a selection in a list. It is associated with Command.Accept, typically triggered by the Enter key or double-click.

  • Event: The Accepting event is raised by RaiseAccepting, allowing external code to modify or cancel the action.

  • Virtual Method: OnAccepting enables subclasses to preprocess or cancel the action.

  • Implementation: As shown above in RaiseAccepting.

    • Default Behavior: Raises Accepting and propagates to a default button (if present in the superview with IsDefault = true) or the superview if not canceled.
    • Cancellation: args.Cancel or OnAccepting returning true halts the command.
    • Context: ICommandContext provides invocation details.
  • Use Cases:

    • Button: Pressing Enter raises Accepting to activate the button (e.g., submit a dialog).
    • ListView: Double-clicking or pressing Enter raises Accepting to confirm the selected item(s).
    • TextField: Pressing Enter raises Accepting to submit the input.
    • Menu and MenuBar: Pressing Enter on a MenuItemv2 raises Accepting to execute a command or open a submenu, followed by the Accepted event to hide the menu or deactivate the menu bar:
      protected void RaiseAccepted(ICommandContext? ctx)
      {
          CommandEventArgs args = new() { Context = ctx };
          OnAccepted(args);
          Accepted?.Invoke(this, args);
      }
      
    • CheckBox: Pressing Enter raises Accepting to confirm the current CheckedState without modifying it, as seen in its command setup:
      AddCommand(Command.Accept, RaiseAccepting);
      
    • FlagSelector: Pressing Enter raises Accepting to confirm the current Value, though its subview Selecting handler incorrectly triggers Accepting, which should be reserved for parent-level confirmation.
    • Dialog: Accepting on a default button closes the dialog or triggers an action.
  • Propagation: Command.Accept propagates to:

    • A default button (if present in the superview with IsDefault = true).
    • The superview, enabling hierarchical handling (e.g., a dialog processes Accept if no button handles it).
    • In Menu, propagation extends to the SuperMenuItem for submenus in popovers, as seen in OnAccepting:
      protected override bool OnAccepting(CommandEventArgs args)
      {
          if (args.Context is CommandContext<KeyBinding> keyCommandContext && keyCommandContext.Binding.Key == Application.QuitKey)
          {
              return true;
          }
          if (SuperView is null && SuperMenuItem is {})
          {
              return SuperMenuItem?.InvokeCommand(Command.Accept, args.Context) is true;
          }
          return false;
      }
      
    • Similarly, MenuBar customizes propagation to show popovers:
      protected override bool OnAccepting(CommandEventArgs args)
      {
          if (Visible && Enabled && args.Context?.Source is MenuBarItemv2 { PopoverMenuOpen: false } sourceMenuBarItem)
          {
              if (!CanFocus)
              {
                  Active = true;
                  ShowItem(sourceMenuBarItem);
                  if (!sourceMenuBarItem.HasFocus)
                  {
                      sourceMenuBarItem.SetFocus();
                  }
              }
              else
              {
                  ShowItem(sourceMenuBarItem);
              }
              return true;
          }
          return false;
      }
      

Key Differences

Aspect Selecting Accepting
Purpose Change view state or prepare for interaction (e.g., focus menu item, toggle checkbox, select list item) Confirm action or state (e.g., execute menu command, submit, activate)
Trigger Spacebar, single click, navigation keys, mouse enter Enter, double-click
Event Selecting Accepting
Virtual Method OnSelecting OnAccepting
Propagation Local to the view Propagates to default button, superview, or SuperMenuItem (in menus)
Use Cases Menu, MenuBar, CheckBox, FlagSelector, ListView, Button Menu, MenuBar, CheckBox, FlagSelector, Button, ListView, Dialog
State Dependency Often stateful, but includes focus for stateless views May be stateless (triggers action)

Critical Evaluation: Selecting vs. Accepting

The distinction between Selecting and Accepting is clear in theory:

  • Selecting is about state changes or preparatory actions, such as choosing an item in a ListView or toggling a CheckBox.
  • Accepting is about finalizing an action, such as submitting a selection or activating a button.

However, practical challenges arise:

  • Overlapping Triggers: In ListView, pressing Enter might both select an item (Selecting) and confirm it (Accepting), depending on the interaction model, potentially confusing developers. Similarly, in Menu, navigation (e.g., arrow keys) triggers Selecting, while Enter triggers Accepting, but the overlap in user intent can blur the lines.
  • Stateless Views: For views like Button or MenuItemv2, Selecting is limited to setting focus, which dilutes its purpose as a state-changing action and may confuse developers expecting a more substantial state change.
  • Propagation Limitations: The local handling of Command.Select restricts hierarchical coordination. For example, MenuBar relies on SelectedMenuItemChanged to manage PopoverMenu visibility, which is view-specific and not generalizable. This highlights a need for a propagation mechanism that maintains subview-superview decoupling.
  • FlagSelector Design Flaw: In FlagSelector, the CheckBox.Selecting handler incorrectly triggers both Selecting and Accepting, conflating state changes (toggling flags) with action confirmation (submitting the flag set). This violates the intended separation and requires a design fix to ensure Selecting is limited to subview state changes and Accepting is reserved for parent-level confirmation.

Recommendation: Enhance documentation to clarify the Selecting/Accepting model:

  • Define Selecting as state changes or interaction preparation (e.g., item selection, toggling, focusing) and Accepting as action confirmations (e.g., submission, activation).
  • Explicitly note that Command.Select may set focus in stateless views (e.g., Button, MenuItemv2) but is primarily for state changes.
  • Address FlagSelectors conflation by refactoring its Selecting handler to separate state changes from confirmation.

Evaluating Selected/Accepted Events

The need for Selected and Accepted events is under consideration, with Accepted showing utility in specific views (Menu, MenuBar) but not universally required across all views. These events would serve as post-events, notifying that a Selecting or Accepting action has completed, similar to other Cancellable Work Pattern post-events like ClearedViewport in View.Draw or OrientationChanged in OrientationHelper.

Need for Selected/Accepted Events

  • Selected Event:

    • Purpose: A Selected event would notify that a Selecting action has completed, indicating that a state change or preparatory action (e.g., a new item highlighted, a checkbox toggled) has taken effect.
    • Use Cases:
      • Menu and MenuBar: Notify when a new MenuItemv2 is focused, currently handled by the SelectedMenuItemChanged event, which tracks focus changes:
        protected override void OnFocusedChanged(View? previousFocused, View? focused)
        {
            base.OnFocusedChanged(previousFocused, focused);
            SelectedMenuItem = focused as MenuItemv2;
            RaiseSelectedMenuItemChanged(SelectedMenuItem);
        }
        
      • CheckBox: Notify when the CheckedState changes, handled by the CheckedStateChanged event, which is raised after a state toggle:
        private bool? ChangeCheckedState(CheckState value)
        {
            if (_checkedState == value || (value is CheckState.None && !AllowCheckStateNone))
            {
                return null;
            }
            CancelEventArgs<CheckState> e = new(in _checkedState, ref value);
            if (OnCheckedStateChanging(e))
            {
                return true;
            }
            CheckedStateChanging?.Invoke(this, e);
            if (e.Cancel)
            {
                return e.Cancel;
            }
            _checkedState = value;
            UpdateTextFormatterText();
            SetNeedsLayout();
            EventArgs<CheckState> args = new(in _checkedState);
            OnCheckedStateChanged(args);
            CheckedStateChanged?.Invoke(this, args);
            return false;
        }
        
      • FlagSelector: Notify when the Value changes due to a flag toggle, handled by the ValueChanged event, which is raised after a CheckBox state change:
        checkbox.CheckedStateChanged += (sender, args) =>
        {
            uint? newValue = Value;
            if (checkbox.CheckedState == CheckState.Checked)
            {
                if (flag == default!)
                {
                    newValue = 0;
                }
                else
                {
                    newValue = newValue | flag;
                }
            }
            else
            {
                newValue = newValue & ~flag;
            }
            Value = newValue;
        };
        
      • ListView: Notify when a new item is selected, typically handled by SelectedItemChanged or similar custom events.
      • Button: Less relevant, as Selecting typically only sets focus, and no state change occurs to warrant a Selected notification.
    • Current Approach: Views like Menu, CheckBox, and FlagSelector use custom events (SelectedMenuItemChanged, CheckedStateChanged, ValueChanged) to signal state changes, bypassing a generic Selected event. These view-specific events provide context (e.g., the selected MenuItemv2, the new CheckedState, or the updated Value) that a generic Selected event would struggle to convey without additional complexity.
    • Pros:
      • A standardized Selected event could unify state change notifications across views, reducing the need for custom events in some cases.
      • Aligns with the Cancellable Work Patterns post-event phase, providing a consistent way to react to completed Selecting actions.
      • Could simplify scenarios where external code needs to monitor state changes without subscribing to view-specific events.
    • Cons:
      • Overlaps with existing view-specific events, which are more contextually rich (e.g., CheckedStateChanged provides the new CheckState, whereas Selected would need additional data).
      • Less relevant for stateless views like Button, where Selecting only sets focus, leading to inconsistent usage across view types.
      • Adds complexity to the base View class, potentially bloating the API for a feature not universally needed.
      • Requires developers to handle generic Selected events with less specific information, which could lead to more complex event handling logic compared to targeted view-specific events.
    • Context Insight: The use of SelectedMenuItemChanged in Menu and MenuBar, CheckedStateChanged in CheckBox, and ValueChanged in FlagSelector suggests that view-specific events are preferred for their specificity and context. These events are tailored to the views state (e.g., MenuItemv2 instance, CheckState, or Value), making them more intuitive for developers than a generic Selected event. The absence of a Selected event in the current implementation indicates that it hasnt been necessary for most use cases, as view-specific events adequately cover state change notifications.
    • Verdict: A generic Selected event could provide a standardized way to notify state changes, but its benefits are outweighed by the effectiveness of view-specific events like SelectedMenuItemChanged, CheckedStateChanged, and ValueChanged. These events offer richer context and are sufficient for current use cases across Menu, CheckBox, FlagSelector, and other views. Adding Selected to the base View class is not justified at this time, as it would add complexity without significant advantages over existing mechanisms.
  • Accepted Event:

    • Purpose: An Accepted event would notify that an Accepting action has completed (i.e., was not canceled via args.Cancel), indicating that the action has taken effect, aligning with the Cancellable Work Patterns post-event phase.
    • Use Cases:
      • Menu and MenuBar: The Accepted event is critical for signaling that a menu command has been executed or a submenu action has completed, triggering actions like hiding the menu or deactivating the menu bar. In Menu, its raised by RaiseAccepted and used hierarchically:
        protected void RaiseAccepted(ICommandContext? ctx)
        {
            CommandEventArgs args = new() { Context = ctx };
            OnAccepted(args);
            Accepted?.Invoke(this, args);
        }
        
        In MenuBar, it deactivates the menu bar:
        protected override void OnAccepted(CommandEventArgs args)
        {
            base.OnAccepted(args);
            if (SubViews.OfType<MenuBarItemv2>().Contains(args.Context?.Source))
            {
                return;
            }
            Active = false;
        }
        
      • CheckBox: Could notify that the current CheckedState was confirmed (e.g., in a dialog context), though this is not currently implemented, as Accepting suffices for confirmation without a post-event.
      • FlagSelector: Could notify that the current Value was confirmed, but this is not implemented, and the incorrect triggering of Accepting by subview Selecting complicates its use.
      • Button: Could notify that the button was activated, typically handled by a custom event like Clicked.
      • ListView: Could notify that a selection was confirmed (e.g., Enter pressed), often handled by custom events.
      • Dialog: Could notify that an action was completed (e.g., OK button clicked), useful for hierarchical scenarios.
    • Current Approach: Menu and MenuItemv2 implement Accepted to signal action completion, with hierarchical handling via subscriptions (e.g., MenuItemv2.Accepted triggers Menu.RaiseAccepted, which triggers MenuBar.OnAccepted). Other views like CheckBox and FlagSelector rely on the completion of the Accepting event (i.e., not canceled) or custom events (e.g., Button.Clicked) to indicate action completion, without a generic Accepted event.
    • Pros:
      • Provides a standardized way to react to confirmed actions, particularly valuable in composite or hierarchical views like Menu, MenuBar, and Dialog, where superviews need to respond to action completion (e.g., closing a menu or dialog).
      • Aligns with the Cancellable Work Patterns post-event phase, offering a consistent mechanism for post-action notifications.
      • Simplifies hierarchical scenarios by providing a unified event for action completion, reducing reliance on view-specific events in some cases.
    • Cons:
      • May duplicate existing view-specific events (e.g., Button.Clicked, Menu.Accepted), leading to redundancy in views where custom events are already established.
      • Adds complexity to the base View class, especially for views like CheckBox or FlagSelector where Acceptings completion is often sufficient without a post-event.
      • Requires clear documentation to distinguish Accepted from Accepting and to clarify when it should be used over view-specific events.
    • Context Insight: The implementation of Accepted in Menu and MenuBar demonstrates its utility in hierarchical contexts, where it facilitates actions like menu closure or menu bar deactivation. For example, MenuItemv2 raises Accepted to trigger Menus RaiseAccepted, which propagates to MenuBar:
      protected void RaiseAccepted(ICommandContext? ctx)
      {
          CommandEventArgs args = new() { Context = ctx };
          OnAccepted(args);
          Accepted?.Invoke(this, args);
      }
      
      In contrast, CheckBox and FlagSelector do not use Accepted, relying on Acceptings completion or view-specific events like CheckedStateChanged or ValueChanged. This suggests that Accepted is particularly valuable in composite views with hierarchical interactions but not universally needed across all views. The absence of Accepted in CheckBox and FlagSelector indicates that Accepting is often sufficient for simple confirmation scenarios, but the hierarchical use in menus and potential dialog applications highlight its potential for broader adoption in specific contexts.
    • Verdict: The Accepted event is highly valuable in composite and hierarchical views like Menu, MenuBar, and potentially Dialog, where it supports coordinated action completion (e.g., closing menus or dialogs). However, adding it to the base View class is premature without broader validation across more view types, as many views (e.g., CheckBox, FlagSelector) function effectively without it, using Accepting or custom events. Implementing Accepted in specific views or base classes like Bar or Runnable (e.g., for menus and dialogs) and reassessing its necessity for the base View class later is a prudent approach. This balances the demonstrated utility in hierarchical scenarios with the need to avoid unnecessary complexity in simpler views.

Recommendation: Avoid adding Selected or Accepted events to the base View class for now. Instead:

  • Continue using view-specific events (e.g., Menu.SelectedMenuItemChanged, CheckBox.CheckedStateChanged, FlagSelector.ValueChanged, ListView.SelectedItemChanged, Button.Clicked) for their contextual specificity and clarity.
  • Maintain and potentially formalize the use of Accepted in views like Menu, MenuBar, and Dialog, tracking its utility to determine if broader adoption in a base class like Bar or Runnable is warranted.
  • If Selected or Accepted events are added in the future, ensure they fire only when their respective events (Selecting, Accepting) are not canceled (i.e., args.Cancel is false), maintaining consistency with the Cancellable Work Patterns post-event phase.

Propagation of Selecting

The current implementation of Command.Select is local, but MenuBar requires propagation to manage PopoverMenu visibility, highlighting a limitation in the systems ability to support hierarchical coordination without view-specific mechanisms.

Current Behavior

  • Selecting: Command.Select is handled locally by the target view, with no propagation to the superview or other views. If the command is unhandled (returns null or false), processing stops without further routing.

    • Rationale: Selecting is typically view-specific, as state changes (e.g., highlighting a ListView item, toggling a CheckBox) or preparatory actions (e.g., focusing a MenuItemv2) are internal to the view. This is evident in CheckBox, where state toggling is self-contained:
      private bool? AdvanceAndSelect(ICommandContext? commandContext)
      {
          bool? cancelled = AdvanceCheckState();
          if (cancelled is true)
          {
              return true;
          }
          if (RaiseSelecting(commandContext) is true)
          {
              return true;
          }
          return commandContext?.Command == Command.HotKey ? cancelled : cancelled is false;
      }
      
    • Context Across Views:
      • In Menu, Selecting sets focus and raises SelectedMenuItemChanged to track changes, but this is a view-specific mechanism:
        protected override void OnFocusedChanged(View? previousFocused, View? focused)
        {
            base.OnFocusedChanged(previousFocused, focused);
            SelectedMenuItem = focused as MenuItemv2;
            RaiseSelectedMenuItemChanged(SelectedMenuItem);
        }
        
      • In MenuBar, SelectedMenuItemChanged is used to manage PopoverMenu visibility, but this relies on custom event handling rather than a generic propagation model:
        protected override void OnSelectedMenuItemChanged(MenuItemv2? selected)
        {
            if (IsOpen() && selected is MenuBarItemv2 { PopoverMenuOpen: false } selectedMenuBarItem)
            {
                ShowItem(selectedMenuBarItem);
            }
        }
        
      • In CheckBox and FlagSelector, Selecting is local, with state changes (e.g., CheckedState, Value) handled internally or via view-specific events (CheckedStateChanged, ValueChanged), requiring no superview involvement.
      • In ListView, Selecting updates the highlighted item locally, with no need for propagation in typical use cases.
      • In Button, Selecting sets focus, which is inherently local.
  • Accepting: Command.Accept propagates to a default button (if present), the superview, or a SuperMenuItem (in menus), enabling hierarchical handling.

    • Rationale: Accepting often involves actions that affect the broader UI context (e.g., closing a dialog, executing a menu command), requiring coordination with parent views. This is evident in Menus propagation to SuperMenuItem and MenuBars handling of Accepted:
      protected override void OnAccepting(CommandEventArgs args)
      {
          if (args.Context is CommandContext<KeyBinding> keyCommandContext && keyCommandContext.Binding.Key == Application.QuitKey)
          {
              return true;
          }
          if (SuperView is null && SuperMenuItem is {})
          {
              return SuperMenuItem?.InvokeCommand(Command.Accept, args.Context) is true;
          }
          return false;
      }
      

Should Selecting Propagate?

The local handling of Command.Select is sufficient for many views, but MenuBars need to manage PopoverMenu visibility highlights a gap in the current design, where hierarchical coordination relies on view-specific events like SelectedMenuItemChanged.

  • Arguments For Propagation:

    • Hierarchical Coordination: In MenuBar, propagation would allow the menu bar to react to MenuItemv2 selections (e.g., focusing a menu item via arrow keys or mouse enter) to show or hide popovers, streamlining the interaction model. Without propagation, MenuBar depends on SelectedMenuItemChanged, which is specific to Menu and not reusable for other hierarchical components.
    • Consistency with Accepting: Command.Accepts propagation model supports hierarchical actions (e.g., dialog submission, menu command execution), suggesting that Command.Select could benefit from a similar approach to enable broader UI coordination, particularly in complex views like menus or dialogs.
    • Future-Proofing: Propagation could support other hierarchical components, such as TabView (coordinating tab selection) or nested dialogs (tracking subview state changes), enhancing the Command systems flexibility for future use cases.
  • Arguments Against Propagation:

    • Locality of State Changes: Selecting is inherently view-specific in most cases, as state changes (e.g., CheckBox toggling, ListView item highlighting) or preparatory actions (e.g., Button focus) are internal to the view. Propagating Selecting events could flood superviews with irrelevant events, requiring complex filtering logic. For example, CheckBox and FlagSelector operate effectively without propagation:
      checkbox.CheckedStateChanged += (sender, args) =>
      {
          uint? newValue = Value;
          if (checkbox.CheckedState == CheckState.Checked)
          {
              if (flag == default!)
              {
                  newValue = 0;
              }
              else
              {
                  newValue = newValue | flag;
              }
          }
          else
          {
              newValue = newValue & ~flag;
          }
          Value = newValue;
      };
      
    • Performance and Complexity: Propagation increases event handling overhead and complicates the API, as superviews must process or ignore Selecting events. This could lead to performance issues in deeply nested view hierarchies or views with frequent state changes.
    • Existing Alternatives: View-specific events like SelectedMenuItemChanged, CheckedStateChanged, and ValueChanged already provide mechanisms for superview coordination, negating the need for generic propagation in many cases. For instance, MenuBar uses SelectedMenuItemChanged to manage popovers, albeit in a view-specific way:
      protected override void OnSelectedMenuItemChanged(MenuItemv2? selected)
      {
          if (IsOpen() && selected is MenuBarItemv2 { PopoverMenuOpen: false } selectedMenuBarItem)
          {
              ShowItem(selectedMenuBarItem);
          }
      }
      
      Similarly, CheckBox and FlagSelector use CheckedStateChanged and ValueChanged to notify superviews or external code of state changes, which is sufficient for most scenarios.
    • Semantics of Cancel: Propagation would occur only if args.Cancel is false, implying an unhandled selection, which is counterintuitive since Selecting typically completes its action (e.g., setting focus or toggling a state) within the view. This could confuse developers expecting propagation to occur for all Selecting events.
  • Context Insight: The MenuBar implementation demonstrates a clear need for propagation to manage PopoverMenu visibility, as it must react to MenuItemv2 selections (e.g., focus changes) across its submenu hierarchy. The reliance on SelectedMenuItemChanged works but is specific to Menu, limiting its applicability to other hierarchical components. In contrast, CheckBox and FlagSelector show that local handling is adequate for most stateful views, where state changes are self-contained or communicated via view-specific events. ListView similarly operates locally, with SelectedItemChanged or similar events handling external notifications. Buttons focus-based Selecting is inherently local, requiring no propagation. This dichotomy suggests that while propagation is critical for certain hierarchical scenarios (e.g., menus), its unnecessary for many views, and any propagation mechanism must avoid coupling subviews to superviews to maintain encapsulation.

  • Verdict: The local handling of Command.Select is sufficient for most views, including CheckBox, FlagSelector, ListView, and Button, where state changes or preparatory actions are internal or communicated via view-specific events. However, MenuBars requirement for hierarchical coordination to manage PopoverMenu visibility highlights a gap in the current design, where view-specific events like SelectedMenuItemChanged are used as a workaround. A generic propagation model would enhance flexibility for hierarchical components, but it must ensure that subviews (e.g., MenuItemv2) remain decoupled from superviews (e.g., MenuBar) to avoid implementation-specific dependencies. The current lack of propagation is a limitation, particularly for menus, but adding it requires careful design to avoid overcomplicating the API or impacting performance for views that dont need it.

Recommendation: Maintain the local handling of Command.Select for now, as it meets the needs of most views like CheckBox, FlagSelector, and ListView. For MenuBar, continue using SelectedMenuItemChanged as a temporary solution, but prioritize developing a generic propagation mechanism that supports hierarchical coordination without coupling subviews to superviews. This mechanism should allow superviews to opt-in to receiving Selecting events from subviews, ensuring encapsulation (see appendix for a proposed solution).

Recommendations for Refining the Design

Based on the analysis of the current Command and View.Command system, as implemented in Menu, MenuBar, CheckBox, and FlagSelector, the following recommendations aim to refine the systems clarity, consistency, and flexibility while addressing identified limitations:

  1. Clarify Selecting/Accepting in Documentation:

    • Explicitly define Selecting as state changes or interaction preparation (e.g., toggling a CheckBox, focusing a MenuItemv2, selecting a ListView item) and Accepting as action confirmations (e.g., executing a menu command, submitting a dialog).
    • Emphasize that Command.Select may set focus in stateless views (e.g., Button, MenuItemv2) but is primarily intended for state changes, to reduce confusion for developers.
    • Provide examples for each view type (e.g., Menu, CheckBox, FlagSelector, ListView, Button) to illustrate their distinct roles. For instance:
      • Menu: “Selecting focuses a MenuItemv2 via arrow keys, while Accepting executes the selected command.”
      • CheckBox: “Selecting toggles the CheckedState, while Accepting confirms the current state.”
      • FlagSelector: “Selecting toggles a subview flag, while Accepting confirms the entire flag set.”
    • Document the Cancel propertys role in CommandEventArgs, noting its current limitation (implying negation rather than completion) and the planned replacement with Handled to align with input events like Key.Handled.
  2. Address FlagSelector Design Flaw:

    • Refactor FlagSelectors CheckBox.Selecting handler to separate Selecting and Accepting actions, ensuring Selecting is limited to subview state changes (toggling flags) and Accepting is reserved for parent-level confirmation of the Value. This resolves the conflation issue where subview Selecting incorrectly triggers Accepting.
    • Proposed fix:
      checkbox.Selecting += (sender, args) =>
      {
          if (RaiseSelecting(args.Context) is true)
          {
              args.Cancel = true;
          }
      };
      
    • This ensures Selecting only propagates state changes to the parent FlagSelector via RaiseSelecting, and Accepting is triggered separately (e.g., via Enter on the FlagSelector itself) to confirm the Value.
  3. Enhance ICommandContext with View-Specific State:

    • Enrich ICommandContext with a State property to include view-specific data (e.g., the selected MenuItemv2 in Menu, the new CheckedState in CheckBox, the updated Value in FlagSelector). This enables more informed event handlers without requiring view-specific subscriptions.
    • Proposed interface update:
      public interface ICommandContext
      {
          Command Command { get; }
          View? Source { get; }
          object? Binding { get; }
          object? State { get; } // View-specific state (e.g., selected item, CheckState)
      }
      
    • Example: In Menu, include the SelectedMenuItem in ICommandContext.State for Selecting handlers:
      protected bool? RaiseSelecting(ICommandContext? ctx)
      {
          ctx.State = SelectedMenuItem; // Provide selected MenuItemv2
          CommandEventArgs args = new() { Context = ctx };
          if (OnSelecting(args) || args.Cancel)
          {
              return true;
          }
          Selecting?.Invoke(this, args);
          return Selecting is null ? null : args.Cancel;
      }
      
    • This enhances the flexibility of event handlers, allowing external code to react to state changes without subscribing to view-specific events like SelectedMenuItemChanged or CheckedStateChanged.
  4. Monitor Use Cases for Propagation Needs:

    • Track the usage of Selecting and Accepting in real-world applications, particularly in Menu, MenuBar, CheckBox, and FlagSelector, to identify scenarios where propagation of Selecting events could simplify hierarchical coordination.
    • Collect feedback on whether the reliance on view-specific events (e.g., SelectedMenuItemChanged in Menu) is sufficient or if a generic propagation model would reduce complexity for hierarchical components like MenuBar. This will inform the design of a propagation mechanism that maintains subview-superview decoupling (see appendix).
    • Example focus areas:
      • MenuBar: Assess whether SelectedMenuItemChanged adequately handles PopoverMenu visibility or if propagation would streamline the interaction model.
      • Dialog: Evaluate whether Selecting propagation could enhance subview coordination (e.g., tracking checkbox toggles within a dialog).
      • TabView: Consider potential needs for tab selection coordination if implemented in the future.
  5. Improve Propagation for Hierarchical Views:

    • Recognize the limitation in Command.Selects local handling for hierarchical components like MenuBar, where superviews need to react to subview selections (e.g., focusing a MenuItemv2 to manage popovers). The current reliance on SelectedMenuItemChanged is effective but view-specific, limiting reusability.
    • Develop a propagation mechanism that allows superviews to opt-in to receiving Selecting events from subviews without requiring subviews to know superview details, ensuring encapsulation. This could involve a new event or property in View to enable propagation while maintaining decoupling (see appendix for a proposed solution).
    • Example: For MenuBar, a propagation mechanism could allow it to handle Selecting events from MenuItemv2 subviews to show or hide popovers, replacing the need for SelectedMenuItemChanged:
      // Current workaround in MenuBar
      protected override void OnSelectedMenuItemChanged(MenuItemv2? selected)
      {
          if (IsOpen() && selected is MenuBarItemv2 { PopoverMenuOpen: false } selectedMenuBarItem)
          {
              ShowItem(selectedMenuBarItem);
          }
      }
      
  6. Standardize Hierarchical Handling for Accepting:

    • Refine the propagation model for Command.Accept to reduce reliance on view-specific logic, such as Menus use of SuperMenuItem for submenu propagation. The current approach, while functional, introduces coupling:
    if (SuperView is null && SuperMenuItem is {})
    {
        return SuperMenuItem?.InvokeCommand(Command.Accept, args.Context) is true;
    }
    
    • Explore a more generic mechanism, such as allowing superviews to subscribe to Accepting events from subviews, to streamline propagation and improve encapsulation. This could be addressed in conjunction with Selecting propagation (see appendix).
    • Example: In Menu, a subscription-based model could replace SuperMenuItem logic:
      // Hypothetical subscription in Menu
      SubViewAdded += (sender, args) =>
      {
          if (args.View is MenuItemv2 menuItem)
          {
              menuItem.Accepting += (s, e) => RaiseAccepting(e.Context);
          }
      };
      

Conclusion

The Command and View.Command system in Terminal.Gui provides a robust framework for handling view actions, with Selecting and Accepting serving as opinionated mechanisms for state changes/preparation and action confirmations. The system is effectively implemented across Menu, MenuBar, CheckBox, and FlagSelector, supporting a range of stateful and stateless interactions. However, limitations in terminology (Selects ambiguity), cancellation semantics (Cancels misleading implication), and propagation (local Selecting handling) highlight areas for improvement.

The Selecting/Accepting distinction is clear in principle but requires careful documentation to avoid confusion, particularly for stateless views where Selecting is focus-driven and for views like FlagSelector where implementation flaws conflate the two concepts. View-specific events like SelectedMenuItemChanged, CheckedStateChanged, and ValueChanged are sufficient for post-selection notifications, negating the need for a generic Selected event. The Accepted event is valuable in hierarchical views like Menu and MenuBar but not universally required, suggesting inclusion in Bar or Runnable rather than View.

By clarifying terminology, fixing implementation flaws (e.g., FlagSelector), enhancing ICommandContext, and developing a decoupled propagation model, Terminal.Gui can enhance the Command systems clarity and flexibility, particularly for hierarchical components like MenuBar. The appendix summarizes proposed changes to address these limitations, aligning with a filed issue to guide future improvements.

Appendix: Summary of Proposed Changes to Command System

A filed issue proposes enhancements to the Command system to address limitations in terminology, cancellation semantics, and propagation, informed by Menu, MenuBar, CheckBox, and FlagSelector. These changes are not yet implemented but aim to improve clarity, consistency, and flexibility.

Proposed Changes

  1. Rename Command.Select to Command.Activate:

    • Replace Command.Select, Selecting event, OnSelecting, and RaiseSelecting with Command.Activate, Activating, OnActivating, and RaiseActivating.
    • Rationale: “Select” is ambiguous for stateless views (e.g., Button focus) and imprecise for non-list state changes (e.g., CheckBox toggling). “Activate” better captures state changes and preparation.
    • Impact: Breaking change requiring codebase updates and migration guidance.
  2. Replace Cancel with Handled in CommandEventArgs:

    • Replace Cancel with Handled to indicate command completion, aligning with Key.Handled (issue #3913).
    • Rationale: Cancel implies negation, not completion.
    • Impact: Clarifies semantics, requires updating event handlers.
  3. Introduce PropagateActivating Event:

    • Add event EventHandler<CancelEventArgs>? PropagateActivating to View, allowing superviews (e.g., MenuBar) to subscribe to subview propagation requests.
    • Rationale: Enables hierarchical coordination (e.g., MenuBar managing PopoverMenu visibility) without coupling subviews to superviews, addressing the current reliance on view-specific events like SelectedMenuItemChanged.
    • Impact: Enhances flexibility for hierarchical views, requires subscription management in superviews like MenuBar.

Benefits

  • Clarity: Activate improves terminology for all views.
  • Consistency: Handled aligns with input events.
  • Decoupling: PropagateActivating supports hierarchical needs without subview-superview dependencies.
  • Extensibility: Applicable to other hierarchies (e.g., dialogs, TabView).

Implementation Notes

  • Update Command enum, View, and derived classes for the rename.
  • Modify CommandEventArgs for Handled.
  • Implement PropagateActivating and test in MenuBar.
  • Revise documentation to reflect changes.

For details, refer to the filed issue in the Terminal.Gui repository.