* Refactor selectors and improve UI components Refactored `MarginEditor` and `UICatalogTop` to use new `OptionSelector` and `FlagSelector` classes, introducing type-safe generic versions for better flexibility and maintainability. Added `SelectorBase` as a shared foundation for these components, along with the `SelectorStyles` enum for customizable styles. Enhanced unit tests to cover new implementations and edge cases. Enabled nullable reference types for improved null safety. Improved code readability, reduced redundancy, and enhanced user experience with better hotkey management, focus handling, and layout adjustments. * Refactor UI components and remove unused classes Significant refactoring and simplification of the codebase: - Updated `CharacterMap` to use `OptionSelector<UnicodeCategory>`. - Removed `FlagSelector`, `FlagSelector<TEnum>`, and `FlagSelectorStyles`. - Replaced `OptionSelector.Options` with `Labels` in `MenuBarv2`. - Removed `OptionSelector` and its associated properties/methods. - Updated terminology from "Activate" to "Select" across components. - Refactored `SelectorBase` to align with new "Select" behavior. - Removed redundant methods, properties, and event handlers. These changes streamline the codebase, reduce complexity, and align with updated design principles. * Fixes #4374 - 'Application.Screen' is empty when 'Init' returns Refactor and enhance testability of ApplicationImpl Refactored `ApplicationImpl` and related classes to improve modularity and testability. Replaced `FakeConsoleOutput` with `FakeOutput` and introduced `FakeInput` for better test isolation. Added platform-specific factories (`FakeNetComponentFactory`, `FakeWindowsComponentFactory`) to simplify fake component creation. Refactored `GuiTestContext` into partial classes, adding methods for simulating user interactions and improving initialization logic. Enhanced error handling and logging during test setup. Updated tests to use the new `FakeOutput` and `FakeInput` implementations. Standardized driver initialization with `Application.Init(null, "fake")`. Skipped tests relying on the fake driver due to known issues. Performed general cleanup, modernized syntax, and removed redundant code to improve readability and maintainability. * Disable "windows" test case in SynchronizationContextTests The `InlineData("windows")` attribute in the `SynchronizationContext_Post` test method has been commented out. This change temporarily excludes the `"windows"` driverName from the test suite while retaining other test cases (`"fake"`, `"dotnet"`, and `"unix"`). The exclusion may be for debugging, deprecation, or other maintenance purposes. * Disable "windows" test case in SynchronizationContextTests The `[InlineData("windows")]` attribute in the `SynchronizationContextTests` class has been commented out, disabling the test case for the `"windows"` driver name. This change may have been made for debugging, deprecation, or because the test is no longer relevant. Other test cases (`"fake"`, `"dotnet"`, and `"unix"`) remain active. * Update Terminal.Gui/Drivers/FakeDriver/FakeConsole.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Terminal.Gui/Views/Selectors/SelectorStyles.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Terminal.Gui/Views/Selectors/SelectorBase.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Terminal.Gui/Views/Selectors/OptionSelector.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Terminal.Gui/Views/Selectors/OptionSelector.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Terminal.Gui/Views/Selectors/OptionSelector.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Terminal.Gui/Views/Selectors/SelectorBase.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Backported Checkbox from Activate PR * Backported Checkbox from Activate PR 2 * Backported Checkbox from Activate PR 3 * Backported Selctors Scenario * Backported Bars Scenario * Backported AllViewsTester Scenario * Backported Dialogs Scenario * Backported MessageBoxes Scenario * Backported ArrangementEditor * Backported mouse binding fix * Update Terminal.Gui/Views/Selectors/OptionSelector.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Terminal.Gui/Drivers/WindowsDriver/WindowsOutput.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Terminal.Gui/Views/CheckBox.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Fixed typo * Refactor ArrangementEditor event handling Removed the `ArrangementFlagsOnValueChanged` method, which previously handled updates to `ViewToEdit` properties based on arrangement flags. Updated `ArrangementEditor_Initialized` to attach the event handler to `_arrangementSelector.ValueChanged`. The logic for handling arrangement changes has been refactored or relocated. * Refactor AlignKeys for type safety and readability Updated the `AlignKeys` method in the `Shortcuts` class to replace generic `View` references with the more specific `Shortcut` type. Improved type safety by using `IEnumerable<Shortcut>` and `.Cast<Shortcut>()`. Simplified the `max` calculation logic with a single LINQ query and removed redundant casting in the `foreach` loop. These changes enhance code readability, maintainability, and ensure better type safety. * Refactor ArrangementEditor for clarity and consistency Refactored `ArrangementEditor` to improve code readability and maintainability: - Enabled nullable reference types with `#nullable enable`. - Removed unused `using` directives. - Adjusted namespace declaration for formatting consistency. - Reformatted `_arrangementSelector` initialization and property assignment. - Simplified `OnViewToEditChanged` logic with a ternary expression. - Refactored `ArrangementEditor_Initialized` into a single-line block. * Update Examples/UICatalog/Scenarios/Shortcuts.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Terminal.Gui/Views/Selectors/OptionSelector.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Refactor and enhance OptionSelector and SelectorBase Refactored `OptionSelector` and `SelectorBase` to simplify logic, improve hotkey assignment, and ensure robust behavior. Updated `Shortcuts.cs` and `DialogTests.cs` to address nullability issues. Added comprehensive unit tests for `OptionSelector` and `SelectorBase`, covering properties, methods, edge cases, and layout behaviors. These changes improve code readability, maintainability, and functionality while adhering to modern C# practices. * add FlagSelector comprehensive tests Refactored `UncheckNone` and `UncheckAll` methods in `FlagSelector` to improve clarity and prevent concurrent modifications using a new `_updatingChecked` flag. Removed the old `UncheckNone` implementation and reorganized logic for maintainability. Added extensive unit tests in `FlagSelectorTests` to validate functionality, including edge cases and generic implementations. Tests cover flag combination, toggling, "None" flag behavior, and enum-based generic handling. Improved overall maintainability and test coverage for the `FlagSelector` class. * Fixes #4375. UnixDriver fails Toplevel_TabGroup_Forward_Backward Fluent Tests * Refactor RadioGroup to use OptionSelector The `RadioGroup` class has been refactored to inherit from the `OptionSelector` class instead of `View`, marking it as `[Obsolete]` and recommending the use of `OptionSelector`. The previous implementation of `RadioGroup` has been entirely removed, including its properties, methods, events, and internal logic. This includes initialization logic, key bindings, layout management, and event handling. The new `RadioGroup` is now a thin wrapper around `OptionSelector` and implements the `IDesignable` interface. The `EnableForDesign` method has been simplified to set default options for design purposes. This change simplifies the codebase and encourages the use of `OptionSelector` for managing mutually exclusive options. * Backported focus tests and add bug-exposing test case Refactored `AdvanceFocusTests` to improve assertion clarity by replacing `Assert.True`/`Assert.False` with `Assert.Equal`. Enhanced test documentation with detailed view hierarchy comments for better readability. Added a new test case, `FocusNavigation_Should_Cycle_Back_To_Top_Level_Views`, which exposes a bug in focus navigation logic where focus does not cycle back to top-level views after traversing nested views. Updated existing tests to ensure consistent handling of `TabBehavior` and made minor adjustments for improved validation of focus navigation logic. * Remove all tests for RadioGroup component The `RadioGroupTests.cs` file has been completely cleared of all test cases and associated code. This includes the removal of unit tests that validated the `RadioGroup` component's functionality, behavior, and edge cases. The deleted tests covered: - Default constructor behavior and initialization. - Handling of the `SelectedItem` property, including edge cases. - Hotkey bindings and their behavior under different focus states. - Command handling for focus, selection, and acceptance. - Orientation changes and their impact on layout. - Event handling for `SelectedItemChanged`, `Selecting`, and `Accepting`. - Mouse interactions, including single-click and double-click events. This removal eliminates all automated validation for the `RadioGroup` component, leaving it untested and increasing the risk of regressions or undetected issues in future changes. * Fix unix and fake fluent tests. * More fixes for unix and fake drivers * Change classes names for more consistency * Fix typos in docs and method signature Updated XML documentation in `FakeConsole.cs` to replace `<see cref="FakeDriver"/>` with `<exception cref="FakeDriver"></exception>` for clarity. Corrected a parameter name in `WindowsOutput.cs`'s `WriteConsole` method from `numberOfCharsToWritten` to `numberOfCharsToWrite` to fix a typo and improve readability. * Refactor: Replace RadioGroup with OptionSelector Replaced all instances of `RadioGroup` with `OptionSelector` across the codebase to standardize the control for mutually exclusive options. Updated associated properties, methods, and event handlers to align with the `OptionSelector` API, including replacing `RadioLabels` with `AssignHotKeys` and `SelectedItemChanged` with `ValueChanged`. Removed the `RadioGroup` class, marking it as obsolete. Updated documentation, comments, and test cases to reflect the new control. Adjusted layout and positioning logic in various scenarios to ensure UI consistency. Refactored scenarios such as `Buttons`, `ColorPickers`, `DynamicMenuBar`, `FileDialogExamples`, `Images`, `PosAlignDemo`, `ProgressBarStyles`, `RegionScenario`, `Themes`, and others to use `OptionSelector`. Updated `Glyphs` and `View` classes to reflect the terminology change. Cleaned up redundant code and ensured compatibility across the application. * Refactor OptionSelector to use Value instead of SelectedItem Replaced the SelectedItem property with a nullable Value property across the codebase to simplify the API and improve consistency. Updated event handlers from SelectedItemChanged to ValueChanged and adjusted logic accordingly. Refactored UI scenarios (e.g., Buttons, CharacterMap, ColorPickers) and dependent classes (e.g., BorderEditor, DimEditor, PosEditor) to use the new Value property. Improved null handling and streamlined initialization of controls. Updated tests to validate the Value property and renamed test methods for clarity. Removed the RegionOpSelector class as it was no longer needed. Performed general code cleanup, including formatting and removal of redundant code. * Refactor OptionSelector: Replace RadioLabels with Labels Updated the `OptionSelector` class and its derived classes to replace the `RadioLabels` property with a more generic `Labels` property, aligning with the base class `SelectorBase`. This change standardizes the API and simplifies label-related functionality. Refactored all instances of `RadioLabels` across the codebase, including property assignments, method calls, and references in scenarios, tests, and examples. Updated classes include `ColorPickers`, `Dialogs`, `DimAutoDemo`, `DynamicMenuBar`, `FileDialogExamples`, `Images`, `PosAlignDemo`, `Selectors`, `Shortcuts`, `TextAlignmentAndDirection`, `Themes`, `UnicodeInMenu`, `Wizards`, `UICatalogTop`, and `ScenarioTests`. Modified `OptionSelector<TEnum>` to initialize `Labels` directly using `Enum.GetValues<TEnum>()`. Removed the `RadioLabels` property from `OptionSelector`, consolidating functionality under `Labels`. Verified functionality through updated tests and scenarios to ensure consistent behavior with the previous implementation. * Refactor: Replace "radio group" with "option selector" Updated terminology across multiple classes to replace "radio group" with "option selector" for improved clarity and consistency. - Removed unused `OptionSelector` in `ColorPickers`. - Renamed `Title` in `DimAutoDemo` to "Options" and updated `BorderStyle`. - Replaced `_radioItems` with `_optionLabels` in `DimEditor` and `PosEditor`. - Renamed `styleRadioGroup` to `styleOptionSelector` in `MessageBoxes`. - Renamed `radioGroup` to `optionSelector` in `UnicodeInMenu` and `OrientationTests`. - Adjusted related references, event handlers, and UI properties. These changes align the codebase with updated terminology and improve readability. * Replace RadioGroup with OptionSelector and update docs The `RadioGroup` control has been replaced or renamed to `OptionSelector`. Documentation has been updated to reflect this change, including the behavior of raising the `Selecting` event when an option is selected. The navigation table now describes `OptionSelector` as supporting multiple options with actions like `Advance`, `SetValue+OnAccept`, and `Focus+SetValue`. A new section introduces the `OptionSelector` view, which displays mutually-exclusive items with hotkeys. Enhancements to `Menuv2` and `MenuBarv2` include setting focus on `MenuItemv2` selections and raising the `SelectedMenuItemChanged` event. Additionally, a progress bar view has been introduced to visually indicate activity progress. * Fixed `EndAfterFirstIteration` Renamed the `EndAfterFirstIteration` property to `StopAfterFirstIteration` across the codebase for improved clarity and consistency. Updated all references in the `Application`, `ApplicationImpl`, `IApplication`, and `ITimedEvents` classes, as well as related tests and documentation. Modified the application loop logic to use `StopAfterFirstIteration` for controlling the termination of the application after the first iteration. Set its default value to `false`. Updated test cases, demo applications, and XML documentation to reflect the new property name. Added a new project, `OutputView`, to the solution with appropriate configuration entries. Performed minor code cleanup to ensure consistency in naming and behavior. * Enhance selectors and clean up documentation - Added `args.Handled = true` to `CheckBox` event handlers in `FlagSelector` and `OptionSelector` to mark events as handled. - Introduced `_value` field in `FlagSelector` and added a `Cycle` method in `OptionSelector` for better value management. - Updated `OptionSelector` documentation to reference `OptionSelector<TEnum>` for type-safe enum usage. - Improved `UpdateChecked` method documentation in `OptionSelector` to clarify exception behavior. - Enabled nullable reference types in `FlagSelectorTests` and `SelectorBaseTests` and moved them to a new namespace. - Removed outdated auto-generated content from `views.md`. - Removed `CheckBox.DefaultHighlightStyle` from the default theme configuration in `OutputView.cs`. * Update event handling and expand UI documentation Modified `args.Handled` in `FlagSelector` and `OptionSelector` to allow `Accepting` event propagation, improving event handling behavior. Added comments to clarify the changes. Expanded `views.md` with detailed documentation for built-in views and controls in *Terminal.Gui*, including descriptions, examples, and rendered outputs for components like `Bar`, `Button`, `CheckBox`, and more. This update enhances developer guidance for building terminal-based UIs. * Fixed `EndAfterFirstIteration` in `ApplicationImpl` Renamed the `EndAfterFirstIteration` property to `StopAfterFirstIteration` across the codebase for improved clarity. Updated its implementation to use a getter and setter that interact with the `ApplicationImpl.Instance` singleton for centralized management. Modified the `RunLoop` method to check the new `StopAfterFirstIteration` property. Updated the default value to `false` in the `Application` class. Added a private `_stopAfterFirstIteration` field and a corresponding public property in the `ApplicationImpl` class. Updated the `Run` method in `ApplicationImpl` to stop after the first iteration if the property is set to `true`, with appropriate logging. Updated the `IApplication` interface to include the `StopAfterFirstIteration` property and clarified the behavior of the `RequestStop` method. Revised XML documentation comments to reflect these changes. * Fixed EndfterFirstIteration in ApplicaitonImpl Refactored `StopAfterFirstIteration` in `ApplicationImpl` to use an auto-property for simplicity. Updated `RunIteration` to call `view.RequestStop()` instead of modifying `view.Running`. Replaced references to `Application.EndAfterFirstIteration` with `Application.StopAfterFirstIteration` across the codebase, including `ITimedEvents`, `ApplicationTests`, and `GlobalTestSetup`. Added a new test, `InitRunShutdown_StopAfterFirstIteration_Stops`, to verify the application stops correctly after the first iteration. Updated related documentation and assertions for consistency. * Refactor Value handling and improve type safety Refactored `Value` handling across multiple classes to use nullable generic types, improving type safety and eliminating unnecessary casting. Simplified `ValueChanged` event handlers with concise lambda expressions. Enhanced `FlagSelector<TFlagsEnum>` and `OptionSelector<TEnum>` with generic `ValueChanged` events and type-safe event handling. Added nullable reference type annotations to align with modern C# practices. Improved test code by using null-forgiving operators and more descriptive assertions. Cleaned up redundant code and ensured consistency in `Value` handling. Updated `FlagSelectorTests` and `SelectorBaseTests` for better readability and maintainability. Added the `System` namespace to `FlagSelectorTEnum.cs` for compatibility. Overall, these changes enhance code readability, maintainability, and robustness. * Merged v2_develop * Update README badges for v2_develop branch Updated the `.NET Core` badge to reference the `v2_develop` branch. Adjusted the `codecov` badge to remove branch-specific paths and added a token parameter. Reorganized the `codecov` badge position in the README. Retained other badges without modification. * codcov2 * fixed pos tests * Improve cleanup, coverage config, and SpinnerStyle tests Enhanced resource cleanup in `Pos.CombineTests.cs` by disposing of `Application.Top` to prevent leaks. Updated `codecov.yml` to focus coverage on `Terminal.Gui`, simplified path patterns, and clarified configurations. Added `SpinnerStyleTests` with extensive unit tests for `SpinnerStyle` and its variants, covering default properties, behaviors, edge cases, and immutability. Organized tests for readability and ensured thorough validation of all spinner styles. Enabled nullable reference types for improved safety. * Remove .NET Core badge; add comprehensive boundary tests The `.NET Core` workflow badge was removed from the `README.md` file. Added a comprehensive suite of unit tests for the `Region.DrawOuterBoundary` method in `DrawOuterBoundaryTests.cs`. These tests validate the method's behavior across various scenarios, including: - Intersected, unioned, and complex shapes. - Edge cases like empty regions, zero-width/height rectangles, and single-pixel rectangles. - Specific shapes such as L-shaped, T-shaped, and hollow rectangles. - Overlapping, adjacent, and separate rectangles. - Thread safety with parallel drawing. - Different line styles, custom attributes, and very large regions. - Various positions, sizes, and multiple calls on the same canvas. The tests use the `Xunit` framework and include both `[Fact]` and `[Theory]` test cases. These changes enhance the codebase's robustness and ensure correctness in a wide range of scenarios. --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: BDisp <bd.bdisp@gmail.com>
50 KiB
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 view’s 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 Menuv2, MenuItemv2, MenuBarv2, CheckBox, and FlagSelector. These implementations highlight the system’s 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.,StartOfPagefor navigation). - Command Handlers: Views register handlers using
View.AddCommand, specifying aCommandImplementationdelegate that returnsbool?(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 raisingCommandNotBoundif 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, withCancelindicating 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.,
EntertriggersAcceptin 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 delegate’s 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.,
CheckBoxfor state toggling,MenuItemv2for 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.,SelectedMenuItemChangedinMenuv2) for hierarchical coordination.Command.Accept: Propagates to a default button (ifIsDefault = true), superview, orSuperMenuItem(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 view’s 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.Gui’s 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:
Selectingrepresents a user action that changes a view’s state or prepares it for further interaction, such as selecting an item in aListView, toggling aCheckBox, or focusing aMenuItemv2. It is associated withCommand.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
Selectingevent is raised byRaiseSelecting, allowing external code to modify or cancel the state change. -
Virtual Method:
OnSelectingenables 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
CanFocusis true (viaSetupCommands). - Cancellation:
args.CancelorOnSelectingreturningtruehalts the command. - Context:
ICommandContextprovides invocation details.
- Default Behavior: Sets focus if
-
Use Cases:
- ListView: Selecting an item (e.g., via arrow keys or mouse click) raises
Selectingto update the highlighted item. - CheckBox: Toggling the checked state (e.g., via spacebar) raises
Selectingto change the state, as seen in theAdvanceAndSelectmethod: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
Selectingto update the selected option. - Menuv2 and MenuBarv2: Selecting a
MenuItemv2(e.g., via mouse enter or arrow keys) sets focus, tracked bySelectedMenuItemand raisingSelectedMenuItemChanged:protected override void OnFocusedChanged(View? previousFocused, View? focused) { base.OnFocusedChanged(previousFocused, focused); SelectedMenuItem = focused as MenuItemv2; RaiseSelectedMenuItemChanged(SelectedMenuItem); } - FlagSelector: Selecting a
CheckBoxsubview toggles a flag, updating theValueproperty and raisingValueChanged, though it incorrectly triggersAccepting: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,Selectingtypically sets focus but does not change state, making it less relevant.
- ListView: Selecting an item (e.g., via arrow keys or mouse click) raises
-
Propagation:
Command.Selectis handled locally by the target view. If the command is unhandled (nullorfalse), processing stops without propagating to the superview or other views. This is evident inMenuv2, whereSelectedMenuItemChangedis used for hierarchical coordination, and inCheckBoxandFlagSelector, where state changes are internal.
Accepting
-
Definition:
Acceptingrepresents a user action that confirms or finalizes a view’s state or triggers an action, such as submitting a dialog, activating a button, or confirming a selection in a list. It is associated withCommand.Accept, typically triggered by the Enter key or double-click. -
Event: The
Acceptingevent is raised byRaiseAccepting, allowing external code to modify or cancel the action. -
Virtual Method:
OnAcceptingenables subclasses to preprocess or cancel the action. -
Implementation: As shown above in
RaiseAccepting.- Default Behavior: Raises
Acceptingand propagates to a default button (if present in the superview withIsDefault = true) or the superview if not canceled. - Cancellation:
args.CancelorOnAcceptingreturningtruehalts the command. - Context:
ICommandContextprovides invocation details.
- Default Behavior: Raises
-
Use Cases:
- Button: Pressing Enter raises
Acceptingto activate the button (e.g., submit a dialog). - ListView: Double-clicking or pressing Enter raises
Acceptingto confirm the selected item(s). - TextField: Pressing Enter raises
Acceptingto submit the input. - Menuv2 and MenuBarv2: Pressing Enter on a
MenuItemv2raisesAcceptingto execute a command or open a submenu, followed by theAcceptedevent 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
Acceptingto confirm the currentCheckedStatewithout modifying it, as seen in its command setup:AddCommand(Command.Accept, RaiseAccepting); - FlagSelector: Pressing Enter raises
Acceptingto confirm the currentValue, though its subviewSelectinghandler incorrectly triggersAccepting, which should be reserved for parent-level confirmation. - Dialog:
Acceptingon a default button closes the dialog or triggers an action.
- Button: Pressing Enter raises
-
Propagation:
Command.Acceptpropagates to:- A default button (if present in the superview with
IsDefault = true). - The superview, enabling hierarchical handling (e.g., a dialog processes
Acceptif no button handles it). - In
Menuv2, propagation extends to theSuperMenuItemfor submenus in popovers, as seen inOnAccepting: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,
MenuBarv2customizes 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; }
- A default button (if present in the superview with
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 | Menuv2, MenuBarv2, CheckBox, FlagSelector, ListView, Button |
Menuv2, MenuBarv2, 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:
Selectingis about state changes or preparatory actions, such as choosing an item in aListViewor toggling aCheckBox.Acceptingis 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, inMenuv2, navigation (e.g., arrow keys) triggersSelecting, while Enter triggersAccepting, but the overlap in user intent can blur the lines. - Stateless Views: For views like
ButtonorMenuItemv2,Selectingis 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.Selectrestricts hierarchical coordination. For example,MenuBarv2relies onSelectedMenuItemChangedto managePopoverMenuvisibility, 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, theCheckBox.Selectinghandler incorrectly triggers bothSelectingandAccepting, conflating state changes (toggling flags) with action confirmation (submitting the flag set). This violates the intended separation and requires a design fix to ensureSelectingis limited to subview state changes andAcceptingis reserved for parent-level confirmation.
Recommendation: Enhance documentation to clarify the Selecting/Accepting model:
- Define
Selectingas state changes or interaction preparation (e.g., item selection, toggling, focusing) andAcceptingas action confirmations (e.g., submission, activation). - Explicitly note that
Command.Selectmay set focus in stateless views (e.g.,Button,MenuItemv2) but is primarily for state changes. - Address
FlagSelector’s conflation by refactoring itsSelectinghandler 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 (Menuv2, MenuBarv2) 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
Selectedevent would notify that aSelectingaction has completed, indicating that a state change or preparatory action (e.g., a new item highlighted, a checkbox toggled) has taken effect. - Use Cases:
- Menuv2 and MenuBarv2: Notify when a new
MenuItemv2is focused, currently handled by theSelectedMenuItemChangedevent, 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
CheckedStatechanges, handled by theCheckedStateChangedevent, 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
Valuechanges due to a flag toggle, handled by theValueChangedevent, which is raised after aCheckBoxstate 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
SelectedItemChangedor similar custom events. - Button: Less relevant, as
Selectingtypically only sets focus, and no state change occurs to warrant aSelectednotification.
- Menuv2 and MenuBarv2: Notify when a new
- Current Approach: Views like
Menuv2,CheckBox, andFlagSelectoruse custom events (SelectedMenuItemChanged,CheckedStateChanged,ValueChanged) to signal state changes, bypassing a genericSelectedevent. These view-specific events provide context (e.g., the selectedMenuItemv2, the newCheckedState, or the updatedValue) that a genericSelectedevent would struggle to convey without additional complexity. - Pros:
- A standardized
Selectedevent could unify state change notifications across views, reducing the need for custom events in some cases. - Aligns with the Cancellable Work Pattern’s post-event phase, providing a consistent way to react to completed
Selectingactions. - Could simplify scenarios where external code needs to monitor state changes without subscribing to view-specific events.
- A standardized
- Cons:
- Overlaps with existing view-specific events, which are more contextually rich (e.g.,
CheckedStateChangedprovides the newCheckState, whereasSelectedwould need additional data). - Less relevant for stateless views like
Button, whereSelectingonly sets focus, leading to inconsistent usage across view types. - Adds complexity to the base
Viewclass, potentially bloating the API for a feature not universally needed. - Requires developers to handle generic
Selectedevents with less specific information, which could lead to more complex event handling logic compared to targeted view-specific events.
- Overlaps with existing view-specific events, which are more contextually rich (e.g.,
- Context Insight: The use of
SelectedMenuItemChangedinMenuv2andMenuBarv2,CheckedStateChangedinCheckBox, andValueChangedinFlagSelectorsuggests that view-specific events are preferred for their specificity and context. These events are tailored to the view’s state (e.g.,MenuItemv2instance,CheckState, orValue), making them more intuitive for developers than a genericSelectedevent. The absence of aSelectedevent in the current implementation indicates that it hasn’t been necessary for most use cases, as view-specific events adequately cover state change notifications. - Verdict: A generic
Selectedevent could provide a standardized way to notify state changes, but its benefits are outweighed by the effectiveness of view-specific events likeSelectedMenuItemChanged,CheckedStateChanged, andValueChanged. These events offer richer context and are sufficient for current use cases acrossMenuv2,CheckBox,FlagSelector, and other views. AddingSelectedto the baseViewclass is not justified at this time, as it would add complexity without significant advantages over existing mechanisms.
- Purpose: A
-
Accepted Event:
- Purpose: An
Acceptedevent would notify that anAcceptingaction has completed (i.e., was not canceled viaargs.Cancel), indicating that the action has taken effect, aligning with the Cancellable Work Pattern’s post-event phase. - Use Cases:
- Menuv2 and MenuBarv2: The
Acceptedevent 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. InMenuv2, it’s raised byRaiseAcceptedand used hierarchically:Inprotected void RaiseAccepted(ICommandContext? ctx) { CommandEventArgs args = new() { Context = ctx }; OnAccepted(args); Accepted?.Invoke(this, args); }MenuBarv2, 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
CheckedStatewas confirmed (e.g., in a dialog context), though this is not currently implemented, asAcceptingsuffices for confirmation without a post-event. - FlagSelector: Could notify that the current
Valuewas confirmed, but this is not implemented, and the incorrect triggering ofAcceptingby subviewSelectingcomplicates 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.
- Menuv2 and MenuBarv2: The
- Current Approach:
Menuv2andMenuItemv2implementAcceptedto signal action completion, with hierarchical handling via subscriptions (e.g.,MenuItemv2.AcceptedtriggersMenuv2.RaiseAccepted, which triggersMenuBarv2.OnAccepted). Other views likeCheckBoxandFlagSelectorrely on the completion of theAcceptingevent (i.e., not canceled) or custom events (e.g.,Button.Clicked) to indicate action completion, without a genericAcceptedevent. - Pros:
- Provides a standardized way to react to confirmed actions, particularly valuable in composite or hierarchical views like
Menuv2,MenuBarv2, andDialog, where superviews need to respond to action completion (e.g., closing a menu or dialog). - Aligns with the Cancellable Work Pattern’s 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.
- Provides a standardized way to react to confirmed actions, particularly valuable in composite or hierarchical views like
- Cons:
- May duplicate existing view-specific events (e.g.,
Button.Clicked,Menuv2.Accepted), leading to redundancy in views where custom events are already established. - Adds complexity to the base
Viewclass, especially for views likeCheckBoxorFlagSelectorwhereAccepting’s completion is often sufficient without a post-event. - Requires clear documentation to distinguish
AcceptedfromAcceptingand to clarify when it should be used over view-specific events.
- May duplicate existing view-specific events (e.g.,
- Context Insight: The implementation of
AcceptedinMenuv2andMenuBarv2demonstrates its utility in hierarchical contexts, where it facilitates actions like menu closure or menu bar deactivation. For example,MenuItemv2raisesAcceptedto triggerMenuv2’sRaiseAccepted, which propagates toMenuBarv2:In contrast,protected void RaiseAccepted(ICommandContext? ctx) { CommandEventArgs args = new() { Context = ctx }; OnAccepted(args); Accepted?.Invoke(this, args); }CheckBoxandFlagSelectordo not useAccepted, relying onAccepting’s completion or view-specific events likeCheckedStateChangedorValueChanged. This suggests thatAcceptedis particularly valuable in composite views with hierarchical interactions but not universally needed across all views. The absence ofAcceptedinCheckBoxandFlagSelectorindicates thatAcceptingis 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
Acceptedevent is highly valuable in composite and hierarchical views likeMenuv2,MenuBarv2, and potentiallyDialog, where it supports coordinated action completion (e.g., closing menus or dialogs). However, adding it to the baseViewclass is premature without broader validation across more view types, as many views (e.g.,CheckBox,FlagSelector) function effectively without it, usingAcceptingor custom events. ImplementingAcceptedin specific views or base classes likeBarorToplevel(e.g., for menus and dialogs) and reassessing its necessity for the baseViewclass later is a prudent approach. This balances the demonstrated utility in hierarchical scenarios with the need to avoid unnecessary complexity in simpler views.
- Purpose: An
Recommendation: Avoid adding Selected or Accepted events to the base View class for now. Instead:
- Continue using view-specific events (e.g.,
Menuv2.SelectedMenuItemChanged,CheckBox.CheckedStateChanged,FlagSelector.ValueChanged,ListView.SelectedItemChanged,Button.Clicked) for their contextual specificity and clarity. - Maintain and potentially formalize the use of
Acceptedin views likeMenuv2,MenuBarv2, andDialog, tracking its utility to determine if broader adoption in a base class likeBarorToplevelis warranted. - If
SelectedorAcceptedevents are added in the future, ensure they fire only when their respective events (Selecting,Accepting) are not canceled (i.e.,args.Cancelisfalse), maintaining consistency with the Cancellable Work Pattern’s post-event phase.
Propagation of Selecting
The current implementation of Command.Select is local, but MenuBarv2 requires propagation to manage PopoverMenu visibility, highlighting a limitation in the system’s ability to support hierarchical coordination without view-specific mechanisms.
Current Behavior
-
Selecting:
Command.Selectis handled locally by the target view, with no propagation to the superview or other views. If the command is unhandled (returnsnullorfalse), processing stops without further routing.- Rationale:
Selectingis typically view-specific, as state changes (e.g., highlighting aListViewitem, toggling aCheckBox) or preparatory actions (e.g., focusing aMenuItemv2) are internal to the view. This is evident inCheckBox, 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
Menuv2,Selectingsets focus and raisesSelectedMenuItemChangedto 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
MenuBarv2,SelectedMenuItemChangedis used to managePopoverMenuvisibility, 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
CheckBoxandFlagSelector,Selectingis local, with state changes (e.g.,CheckedState,Value) handled internally or via view-specific events (CheckedStateChanged,ValueChanged), requiring no superview involvement. - In
ListView,Selectingupdates the highlighted item locally, with no need for propagation in typical use cases. - In
Button,Selectingsets focus, which is inherently local.
- In
- Rationale:
-
Accepting:
Command.Acceptpropagates to a default button (if present), the superview, or aSuperMenuItem(in menus), enabling hierarchical handling.- Rationale:
Acceptingoften 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 inMenuv2’s propagation toSuperMenuItemandMenuBarv2’s handling ofAccepted: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; }
- Rationale:
Should Selecting Propagate?
The local handling of Command.Select is sufficient for many views, but MenuBarv2’s 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
MenuBarv2, propagation would allow the menu bar to react toMenuItemv2selections (e.g., focusing a menu item via arrow keys or mouse enter) to show or hide popovers, streamlining the interaction model. Without propagation,MenuBarv2depends onSelectedMenuItemChanged, which is specific toMenuv2and not reusable for other hierarchical components. - Consistency with Accepting:
Command.Accept’s propagation model supports hierarchical actions (e.g., dialog submission, menu command execution), suggesting thatCommand.Selectcould 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 theCommandsystem’s flexibility for future use cases.
- Hierarchical Coordination: In
-
Arguments Against Propagation:
- Locality of State Changes:
Selectingis inherently view-specific in most cases, as state changes (e.g.,CheckBoxtoggling,ListViewitem highlighting) or preparatory actions (e.g.,Buttonfocus) are internal to the view. PropagatingSelectingevents could flood superviews with irrelevant events, requiring complex filtering logic. For example,CheckBoxandFlagSelectoroperate 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
Selectingevents. 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, andValueChangedalready provide mechanisms for superview coordination, negating the need for generic propagation in many cases. For instance,MenuBarv2usesSelectedMenuItemChangedto manage popovers, albeit in a view-specific way:Similarly,protected override void OnSelectedMenuItemChanged(MenuItemv2? selected) { if (IsOpen() && selected is MenuBarItemv2 { PopoverMenuOpen: false } selectedMenuBarItem) { ShowItem(selectedMenuBarItem); } }CheckBoxandFlagSelectoruseCheckedStateChangedandValueChangedto notify superviews or external code of state changes, which is sufficient for most scenarios. - Semantics of
Cancel: Propagation would occur only ifargs.Cancelisfalse, implying an unhandled selection, which is counterintuitive sinceSelectingtypically completes its action (e.g., setting focus or toggling a state) within the view. This could confuse developers expecting propagation to occur for allSelectingevents.
- Locality of State Changes:
-
Context Insight: The
MenuBarv2implementation demonstrates a clear need for propagation to managePopoverMenuvisibility, as it must react toMenuItemv2selections (e.g., focus changes) across its submenu hierarchy. The reliance onSelectedMenuItemChangedworks but is specific toMenuv2, limiting its applicability to other hierarchical components. In contrast,CheckBoxandFlagSelectorshow that local handling is adequate for most stateful views, where state changes are self-contained or communicated via view-specific events.ListViewsimilarly operates locally, withSelectedItemChangedor similar events handling external notifications.Button’s focus-basedSelectingis inherently local, requiring no propagation. This dichotomy suggests that while propagation is critical for certain hierarchical scenarios (e.g., menus), it’s unnecessary for many views, and any propagation mechanism must avoid coupling subviews to superviews to maintain encapsulation. -
Verdict: The local handling of
Command.Selectis sufficient for most views, includingCheckBox,FlagSelector,ListView, andButton, where state changes or preparatory actions are internal or communicated via view-specific events. However,MenuBarv2’s requirement for hierarchical coordination to managePopoverMenuvisibility highlights a gap in the current design, where view-specific events likeSelectedMenuItemChangedare 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.,MenuBarv2) 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 don’t 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 MenuBarv2, 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 Menuv2, MenuBarv2, CheckBox, and FlagSelector, the following recommendations aim to refine the system’s clarity, consistency, and flexibility while addressing identified limitations:
-
Clarify Selecting/Accepting in Documentation:
- Explicitly define
Selectingas state changes or interaction preparation (e.g., toggling aCheckBox, focusing aMenuItemv2, selecting aListViewitem) andAcceptingas action confirmations (e.g., executing a menu command, submitting a dialog). - Emphasize that
Command.Selectmay 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.,
Menuv2,CheckBox,FlagSelector,ListView,Button) to illustrate their distinct roles. For instance:Menuv2: “Selectingfocuses aMenuItemv2via arrow keys, whileAcceptingexecutes the selected command.”CheckBox: “Selectingtoggles theCheckedState, whileAcceptingconfirms the current state.”FlagSelector: “Selectingtoggles a subview flag, whileAcceptingconfirms the entire flag set.”
- Document the
Cancelproperty’s role inCommandEventArgs, noting its current limitation (implying negation rather than completion) and the planned replacement withHandledto align with input events likeKey.Handled.
- Explicitly define
-
Address FlagSelector Design Flaw:
- Refactor
FlagSelector’sCheckBox.Selectinghandler to separateSelectingandAcceptingactions, ensuringSelectingis limited to subview state changes (toggling flags) andAcceptingis reserved for parent-level confirmation of theValue. This resolves the conflation issue where subviewSelectingincorrectly triggersAccepting. - Proposed fix:
checkbox.Selecting += (sender, args) => { if (RaiseSelecting(args.Context) is true) { args.Cancel = true; } }; - This ensures
Selectingonly propagates state changes to the parentFlagSelectorviaRaiseSelecting, andAcceptingis triggered separately (e.g., via Enter on theFlagSelectoritself) to confirm theValue.
- Refactor
-
Enhance ICommandContext with View-Specific State:
- Enrich
ICommandContextwith aStateproperty to include view-specific data (e.g., the selectedMenuItemv2inMenuv2, the newCheckedStateinCheckBox, the updatedValueinFlagSelector). 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
Menuv2, include theSelectedMenuIteminICommandContext.StateforSelectinghandlers: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
SelectedMenuItemChangedorCheckedStateChanged.
- Enrich
-
Monitor Use Cases for Propagation Needs:
- Track the usage of
SelectingandAcceptingin real-world applications, particularly inMenuv2,MenuBarv2,CheckBox, andFlagSelector, to identify scenarios where propagation ofSelectingevents could simplify hierarchical coordination. - Collect feedback on whether the reliance on view-specific events (e.g.,
SelectedMenuItemChangedinMenuv2) is sufficient or if a generic propagation model would reduce complexity for hierarchical components likeMenuBarv2. This will inform the design of a propagation mechanism that maintains subview-superview decoupling (see appendix). - Example focus areas:
MenuBarv2: Assess whetherSelectedMenuItemChangedadequately handlesPopoverMenuvisibility or if propagation would streamline the interaction model.Dialog: Evaluate whetherSelectingpropagation 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.
- Track the usage of
-
Improve Propagation for Hierarchical Views:
- Recognize the limitation in
Command.Select’s local handling for hierarchical components likeMenuBarv2, where superviews need to react to subview selections (e.g., focusing aMenuItemv2to manage popovers). The current reliance onSelectedMenuItemChangedis effective but view-specific, limiting reusability. - Develop a propagation mechanism that allows superviews to opt-in to receiving
Selectingevents from subviews without requiring subviews to know superview details, ensuring encapsulation. This could involve a new event or property inViewto enable propagation while maintaining decoupling (see appendix for a proposed solution). - Example: For
MenuBarv2, a propagation mechanism could allow it to handleSelectingevents fromMenuItemv2subviews to show or hide popovers, replacing the need forSelectedMenuItemChanged:// Current workaround in MenuBarv2 protected override void OnSelectedMenuItemChanged(MenuItemv2? selected) { if (IsOpen() && selected is MenuBarItemv2 { PopoverMenuOpen: false } selectedMenuBarItem) { ShowItem(selectedMenuBarItem); } }
- Recognize the limitation in
-
Standardize Hierarchical Handling for Accepting:
- Refine the propagation model for
Command.Acceptto reduce reliance on view-specific logic, such asMenuv2’s use ofSuperMenuItemfor 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
Acceptingevents from subviews, to streamline propagation and improve encapsulation. This could be addressed in conjunction withSelectingpropagation (see appendix). - Example: In
Menuv2, a subscription-based model could replaceSuperMenuItemlogic:// Hypothetical subscription in Menuv2 SubViewAdded += (sender, args) => { if (args.View is MenuItemv2 menuItem) { menuItem.Accepting += (s, e) => RaiseAccepting(e.Context); } };
- Refine the propagation model for
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 Menuv2, MenuBarv2, CheckBox, and FlagSelector, supporting a range of stateful and stateless interactions. However, limitations in terminology (Select’s ambiguity), cancellation semantics (Cancel’s 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 Menuv2 and MenuBarv2 but not universally required, suggesting inclusion in Bar or Toplevel 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 system’s clarity and flexibility, particularly for hierarchical components like MenuBarv2. 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 Menuv2, MenuBarv2, CheckBox, and FlagSelector. These changes are not yet implemented but aim to improve clarity, consistency, and flexibility.
Proposed Changes
-
Rename
Command.SelecttoCommand.Activate:- Replace
Command.Select,Selectingevent,OnSelecting, andRaiseSelectingwithCommand.Activate,Activating,OnActivating, andRaiseActivating. - Rationale: “Select” is ambiguous for stateless views (e.g.,
Buttonfocus) and imprecise for non-list state changes (e.g.,CheckBoxtoggling). “Activate” better captures state changes and preparation. - Impact: Breaking change requiring codebase updates and migration guidance.
- Replace
-
Replace
CancelwithHandledinCommandEventArgs:- Replace
CancelwithHandledto indicate command completion, aligning withKey.Handled(issue #3913). - Rationale:
Cancelimplies negation, not completion. - Impact: Clarifies semantics, requires updating event handlers.
- Replace
-
Introduce
PropagateActivatingEvent:- Add
event EventHandler<CancelEventArgs>? PropagateActivatingtoView, allowing superviews (e.g.,MenuBarv2) to subscribe to subview propagation requests. - Rationale: Enables hierarchical coordination (e.g.,
MenuBarv2managingPopoverMenuvisibility) without coupling subviews to superviews, addressing the current reliance on view-specific events likeSelectedMenuItemChanged. - Impact: Enhances flexibility for hierarchical views, requires subscription management in superviews like
MenuBarv2.
- Add
Benefits
- Clarity:
Activateimproves terminology for all views. - Consistency:
Handledaligns with input events. - Decoupling:
PropagateActivatingsupports hierarchical needs without subview-superview dependencies. - Extensibility: Applicable to other hierarchies (e.g., dialogs,
TabView).
Implementation Notes
- Update
Commandenum,View, and derived classes for the rename. - Modify
CommandEventArgsforHandled. - Implement
PropagateActivatingand test inMenuBarv2. - Revise documentation to reflect changes.
For details, refer to the filed issue in the Terminal.Gui repository.