Skip to content

Add SearchCollectionNavigator#1

Merged
tig merged 1 commit intotig:listview_keyboard_searchfrom
tznind:navigator
Oct 24, 2022
Merged

Add SearchCollectionNavigator#1
tig merged 1 commit intotig:listview_keyboard_searchfrom
tznind:navigator

Conversation

@tznind
Copy link
Copy Markdown

@tznind tznind commented Oct 24, 2022

Tests and class for new class SearchCollectionNavigator

@tig tig merged commit c38af80 into tig:listview_keyboard_search Oct 24, 2022
tig added a commit that referenced this pull request Aug 27, 2024
tig added a commit that referenced this pull request Feb 21, 2026
Refined command bubbling and dispatch logic to fix event propagation bugs:
- DefaultActivateHandler now fires Activated on bubble-up for plain views, matching Accept handler, ensuring SuperViews receive Activated notifications.
- Relay-dispatch views (Shortcut) retain deferred completion; Activated fires only after CommandView completes.
- Reset _lastDispatchOccurred at start of default handlers to prevent stale state and spurious completion events.
- Shortcut resets _activatedFiredThisCycle at start of each activation cycle to prevent stuck flag after programmatic activation.
- Renamed BubbleDown to DispatchDown throughout code and docs for clarity.
- Added unit tests for bubbling, deep hierarchy, consume-dispatch blocking, and regression scenarios.
- Updated documentation to clarify bubbling vs dispatching, routing, and composite view behaviors.
- Verified against full test suite; all new tests pass, no regressions (except known MenuBar/PopoverMenu failures).
- Command bubbling and dispatch are now robust, predictable, and correctly notify SuperViews of activation and acceptance events.
tig added a commit that referenced this pull request Feb 22, 2026
Previously, FlagSelector and OptionSelector did not update their state when activated via external dispatch (Menu → MenuItem → Selector) due to the DispatchingDown guard blocking inner CheckBox activation. This update adds a fallback: when activation arrives via DispatchingDown and the source is not a CheckBox, the currently focused inner CheckBox is used as the toggle/selection target. Unit tests were added and updated to verify this behavior. Documentation was revised to mark Gap #1 as completed and explain the solution. Minor code cleanups and formatting improvements included.
tig added a commit that referenced this pull request Feb 25, 2026
…cs#4620)

* Add AI agent validation checklists and formatting rules

- Add POST-GENERATION-VALIDATION.md with comprehensive checklist
  for validating AI-generated code before commits
- Add formatting.md with detailed spacing, brace, and blank line rules
- Update REFRESH.md to reference the validation checklist
- Update CLAUDE.md with references to new validation docs

These additions address the most common formatting violations
that AI agents make when writing code for Terminal.Gui.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add clean code review task for creating clean git histories

- Add clean-code-review.md task guide for reimplementing branches
  with narrative-quality commit histories
- Remove scenario-modernization.md (outdated task)

The clean code review task provides a workflow for AI agents to
reimplement messy branch histories into clean, reviewer-friendly
commit sequences suitable for PR review.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add command propagation plan document

Addresses: #4473 (Menu etc. with Selectors are broken)

- Add command-propagation-plan.md with phased implementation plan
- Remove command-propagation-analysis.md (superseded by plan)

The plan introduces PropagatedCommands property to enable opt-in
command propagation from SubViews to SuperViews, solving the issue
where commands from nested views (e.g., FlagSelector in MenuBar)
don't reach their containing views.

Phase breakdown:
1. Foundation - PropagatedCommands infrastructure
2. WeakReference - Lifecycle-safe CommandContext.Source
3. Shortcut propagation - Enable Command.Activate for Shortcuts
4. Test cleanup - Re-enable skipped tests
5. MenuBar propagation - Full menu hierarchy support (deferred)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add PropagatedCommands infrastructure with WeakReference support

Addresses: #4473 (Menu etc. with Selectors are broken)

This commit implements Phases 1 and 2 of the command propagation plan:

Phase 1 - PropagatedCommands Infrastructure:
- Add PropagatedCommands property to View (default: [Command.Accept])
- Add PropagateCommand helper method for command bubbling
- Refactor RaiseAccepting to use PropagateCommand helper
- Reorganize View.Command.cs regions for clarity

Phase 2 - WeakReference for CommandContext.Source:
- Change ICommandContext.Source from View? to WeakReference<View>?
- Update CommandContext to use WeakReference for lifecycle safety
- Update InvokeCommand overloads to wrap 'this' in WeakReference
- Update all views using ctx.Source to use TryGetTarget pattern:
  - Dialog, DialogTResult
  - MenuBar, PopoverMenu
  - ComboBox, OptionSelector
  - ScrollSlider, Shortcut

The PropagatedCommands property enables opt-in command propagation:
when a SubView raises a command that isn't handled and the command
is in the SuperView's PropagatedCommands list, the command bubbles up.

BREAKING CHANGE: ICommandContext.Source is now WeakReference<View>?
Code accessing ctx.Source must use TryGetTarget pattern:
  if (ctx?.Source?.TryGetTarget (out View? view) == true) { ... }

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add ShortcutTest example application

Add a standalone test application for verifying Command.Activate
propagation through the Shortcut → Window hierarchy.

The example demonstrates:
- CheckBox (CanFocus=false) in Shortcut → propagates to Window
- CheckBox (CanFocus=true) in Shortcut → propagates to Window
- Button in Shortcut → propagates to Window

This serves as a manual test bed for the PropagatedCommands feature
and helps verify that command context (Source) is properly preserved
when commands bubble up through the view hierarchy.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add comprehensive command propagation tests

Add tests to verify PropagatedCommands and WeakReference changes:

CommandPropagationTests.cs (NEW - 588 lines):
- Tests for command propagation through view hierarchies
- Tests for WeakReference lifecycle safety
- Tests for PropagatedCommands customization
- Tests for Command.Accept and Command.Activate propagation

ViewCommandTests.cs (updated):
- Add tests for PropagatedCommands default value
- Add tests for PropagateCommand helper behavior
- Add tests for IsDefault button propagation

CommandContextTests.cs (updated):
- Update tests for WeakReference-based Source property
- Add TryGetTarget pattern tests

InputBindingTests.cs (updated):
- Update tests for WeakReference compatibility

All tests follow Terminal.Gui patterns and are added to
UnitTestsParallelizable for parallel execution.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Update documentation for command propagation

command.md:
- Document PropagatedCommands property
- Explain command propagation behavior
- Add examples for customizing propagated commands

events.md:
- Add section on command events and propagation
- Document CommandEventArgs and ICommandContext
- Explain WeakReference pattern for Source property

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Update UICatalog scenarios for WeakReference changes

Update scenarios to use TryGetTarget pattern for accessing
CommandContext.Source after the WeakReference change:

Menus.cs:
- Update command handlers to use TryGetTarget

MouseTester.cs:
- Update mouse event handlers for new pattern

UICatalogRunnable.cs:
- Update command context handling

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix ShortcutTest project path in solution file

Change absolute path to relative path for cross-machine compatibility.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* cleanup

* Improve Shortcut event propagation and add tests

Clarify and strengthen event forwarding between Shortcut and its CommandView, ensuring Activating and Accepting events propagate correctly without recursion. MouseHighlightStates now defaults to MouseState.In for better UI feedback. Refactor property implementations and clean up code. Add comprehensive unit tests verifying CheckBox state changes, event propagation, and default behaviors. Enhance ShortcutTestWindow to log detailed event info and demonstrate propagation scenarios.

* Improve null safety and event handling in Shortcut & ComboBox

- Updated Key equality operators to handle nulls safely and avoid NullReferenceExceptions.
- ComboBox Accept command now uses non-nullable View in TryGetTarget and passes a WeakReference<View> to CommandContext for consistency.
- Shortcut.Key property now always returns Key.Empty if unset, and setter no longer throws on null.
- Simplified GetWidthDimAuto by removing unnecessary null-forgiving operators.
- Fixed CommandViewOnActivating logic to prevent recursion and ensure correct event propagation.
- Cleaned up redundant key initialization and clarified KeyView.Text assignment.
- Overall, these changes improve code safety, event handling, and clarity.

* Refactor Shortcut to use auto-properties with initializers

Refactored the Shortcut class to replace explicit backing fields
(_alignmentModes and _minimumKeyTextSize) with auto-implemented
properties for AlignmentModes and MinimumKeyTextSize. Set default
values directly in the property declarations and used the C# field
keyword in setters. This streamlines property definitions and
simplifies the codebase.

* WIP - Refactoring Shortcut->MenuItem etc...

Improve command/event handling for menus and shortcuts

Refactor Shortcut, Menu, MenuBar, and PopoverMenu to enhance command propagation, event handling, and resource management. Set PropagatedCommands by default, improve design-time support, and clarify event subscriptions. Add helper methods for event origin detection, enforce proper menu hierarchy, and update documentation and logging for better maintainability and debugging.

* Merged

* Enabled VSCode debugging of UICatalog

* updated command.md

* Refactor command propagation: use CommandsToBubbleUp

Renames PropagatedCommands to CommandsToBubbleUp for clarity and consistency across all view classes. Command bubbling (for Accept/Activate) is now opt-in via this property; by default, no commands bubble up. Event handling is clarified: Accepted is only raised if Accepting is not handled, and bubbling only occurs for commands listed in CommandsToBubbleUp. Updates all affected classes, refactors and expands tests to cover new bubbling logic, and revises documentation and planning guides. This is a breaking change for code using the old PropagatedCommands property.

* Update Enter key and Accept command behavior in TextView

Pressing Enter now triggers Accepted event in single-line mode.
Accept command is no longer added but returns true when invoked.
Tests updated for new behavior. Minor list initialization cleanup.

* Update Accept command to return null if not handled

Changed Accept command to return null when unhandled instead of true.
Updated related unit tests to expect null/false.
Renamed test method for clarity.

* Update TextFieldTests to use Accepting event

Renamed test methods and variables to reflect the switch from Accepted to Accepting event. Updated assertions and event handler logic to test Accepting event firing and handling, including changes to command handling behavior.

* Improve EventLog and command event logging details

- EventLog width is now responsive and resizable from the left.
- Added logging for Accepted event and improved context formatting.
- Log output now includes detailed ICommandContext info.
- Added ToString() to InputBinding, KeyBinding, MouseBinding for clearer logs.
- SelectorBase now bubbles up the Accept command.
- Updated comments and performed minor code cleanups.

* Refactor Button/Shortcut event model and command handling

Clarifies event raising for Button and Shortcut: Button now raises Accepting/Accepted (not Activating) for hotkey, Enter, Space, and mouse actions. Updates key/mouse bindings to use Command.Accept. Shortcut no longer handles commands directly, preventing double-bubbling of events. Refactors tests to match new event model and improves code clarity with object initializers and auto-properties.

* Refactor Dialog Accept command handling and event flow

- Dialog buttons now bubble Accept to the dialog, which distinguishes default vs. non-default buttons.
- DefaultAcceptView property added for explicit default button selection.
- Non-default buttons set result and stop dialog without raising Accepted; default buttons raise Accepted.
- Dialog<TResult> and Prompt now use OnAccepted for result extraction.
- Improved event propagation and command bubbling logic.
- Expanded and clarified unit tests for Accept event scenarios.
- Enhanced XML docs and performed minor code cleanups.

* Refactor command/event system and improve logging

Major overhaul of command/event handling in Terminal.Gui:
- Refactored View/Shortcut command APIs for clarity and correctness
- Explicit default handlers for Activate, Accept, HotKey
- Improved event bubbling and separation of event sources
- Shortcut now properly forwards/handles CommandView events
- IValue now includes ValueChangedUntyped for generic value change logging
- Added ViewExtensions/WeakReferenceExtensions for better debug output
- KeyBinding/MouseBinding now track source and improve diagnostics
- EventLog and scenarios updated for new event flow and logging
- Tests expanded and updated for new behaviors
- General code cleanup and improved maintainability

* Documented

* Fixed merge issues

* Clarify command/event handling in Button, CheckBox, Shortcut

Update and expand tests to reflect clarified command and event handling for Button, CheckBox, and Shortcut controls. Tests now distinguish between direct command invocation and invocation via keyboard/mouse bindings, ensuring only the correct events and actions are triggered in each scenario. Adjust assertions for DefaultActivateHandler return values, clarify HotKey behavior (focus only, no toggle), and update test names and comments for accuracy. Update default CommandView Id and ensure mouse release (not press) toggles CheckBox state. References to documentation and issue #4473 included for context.

* updated progress

* Shortcut: add deep-dive docs, tweak mouse routing, log events

Added shortcut.md with detailed documentation on Shortcut's event routing, command forwarding, and interaction patterns, including diagrams and advanced usage notes. Changed Shortcut's default MouseHighlightStates to None so subviews receive mouse events directly. Updated EventLog to also write log entries to the debug logger.

* new plan

* updated plan

* Fix ButtonTests: Button no longer raises Activating events

- Updated tests that expected Activating event to assert it does NOT fire
- Added superView context for Enter/Space key tests to properly route events
- Fixed driver injection tests to only expect Accepting events
- Added explicit tests verifying Button does NOT raise Activating for:
  - HotKey command invocation
  - Accept command invocation
  - Mouse click events
- All 54 ButtonTests now pass

This aligns tests with the documented behavior in Button.cs line 19:
"Button does not raise View.Activating events."

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>

* Update ButtonTests names to reflect behavior

Rename tests to more clearly describe what they verify:
- Enter_InvokesHotKeyCommand_RaisesAccepting → Enter_Raises_Accepting_Not_Activating
- Space_InvokesHotKeyCommand_RaisesAccepting → Space_Raises_Accepting_Not_Activating

These names better reflect that the tests verify Button raises Accepting
but does NOT raise Activating events.

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>

* updated broken test. still broken.

* tweaks

* merged v2_develop

* fixed xml doc bug.

* Improve Shortcut activation source handling and docs

Refactor Shortcut activation logic to distinguish between activations from the CommandView (e.g., clicking a color picker) and other sources (e.g., hotkey). Use args.Context.TryGetSource in Activating event handlers to determine the activation source, enabling context-sensitive behavior (such as cycling values only when not activated from the CommandView).

Update Shortcuts.cs to apply this pattern to ColorPicker16, CheckBox, and OptionSelector examples. Refactor Shortcut.cs to prevent recursion and ensure correct event bubbling. Add new tests in ShortcutTests.cs to verify source detection and custom logic execution. Update shortcut.md with documentation and code examples for this pattern.

Also includes minor code cleanups and modern C# syntax improvements.

* Refactor shortcut and progress bar handling

- Replaced `Accepting` events with `Activated` for shortcuts, simplifying event logic and direct action invocation.
- Improved `ProgressBar` with auto-initialized style, updated segment character, and revised drawing to use `Normal` visual role.
- Progress bar shortcut now cycles display format on activation.
- Quit shortcut uses `Key.Esc.WithShift` and direct `Action` property, removing event-based quit handling.
- Status bar quit shortcut now uses `Action` property.
- Updated keyboard binding logic to set binding source before command invocation.
- Simplified test code with object initializers.
- Minor code cleanups and consistency improvements.

* Fixed click on margin bug and added test.

* Fixed TextView Hotkey handling

* Fixed label hotkey test

* Fixed TreeView test

* Code cleanup

* Fixed keybaord test

* combobox and treeview

* Refactor.

* Renamed IInputBinding etc...

* Robustness improvements.

* Selector tweaks

* add TabBehavior to Selectors

* Selector progress

* Refactor KeyBindings & Shortcut command/event handling

Major overhaul of keyboard and command APIs:
- KeyBindings decoupled from View, now general-purpose
- AddApp replaces Add for app-level key bindings
- KeyBinding struct supports both source and target views
- Command invocation and bubbling logic clarified and simplified
- HotKey handling refactored: new HotKeyCommand event, OnHotKeyCommand virtual
- Shortcut view event flow and command dispatching improved
- CheckBox and ColorPicker16 updated for new command infrastructure
- Tests updated and expanded for new APIs and event flow
- Miscellaneous code cleanup and formatting improvements

These changes modernize keyboard/command handling, improve event predictability, and make APIs more robust and explicit.

* Add comprehensive unit tests for CommandContext and View

Significantly expand test coverage for CommandContext and View command/event handling.
- Add constructor, property, and equality tests for CommandContext, including WeakReference behavior.
- Refactor event handler tests in ViewCommandTests to use counters for more precise assertions.
- Add tests for GetSupportedCommands, InvokeCommands, context passing, event bubbling, and DefaultAcceptView logic.
- Improve reliability and clarity of event propagation tests.
No changes to production code; all changes are test-only.

* Refactor ListView command handling and HotKey behavior

Refactored ListView to use OnHotKeyCommand and OnActivated overrides instead of private command handlers, aligning with modern command patterns. HotKey command now ensures SelectedItem is set to 0 if null. ValueChangedUntyped event is now properly implemented and raised. Updated tests for new property names and added tests for HotKey command behavior. Cleaned up command handler return values and improved event consistency.

* Refactor CharMap commands, events, and AOT support

- Refactored CharMap to use OnAccepted/OnActivated overrides for Accept/Activate commands, removing custom handlers and unifying input handling.
- Updated SelectedCodePoint to raise both ValueChanged and ValueChangedUntyped events, fixing missing untyped notifications.
- Switched to C# field-backed auto-properties for SelectedCodePoint and StartCodePoint.
- Added CharMapJsonContext for source-generated, AOT-friendly JSON serialization; updated details dialog to use it.
- Expanded and clarified documentation on command bubbling, event flow, and Shortcut dispatching in View.md and command.md.
- Added unit tests to verify ValueChangedUntyped event behavior and IValue contract.
- Improves AOT compatibility, event consistency, and documentation.

* Fixed warnings

* Updated NumericUpDown

* Add BubbleDown to View and simplify Shortcut command dispatch

Introduces IsBubblingDown flag on ICommandContext to prevent re-entry
when dispatching commands downward to SubViews. TryBubbleToSuperView
checks this flag and skips bubbling, eliminating the need to manually
save/restore CommandsToBubbleUp.

- Add IsBubblingDown to ICommandContext and CommandContext
- Add View.BubbleDown() helper that creates a context with
  IsBubblingDown=true and invokes the command on the target
- Modify TryBubbleToSuperView to skip bubbling when IsBubblingDown
- Simplify Shortcut.OnActivating/OnAccepting to use BubbleDown
- Remove DispatchCommandFromSelf, DispatchCommandFromSubview,
  IsBindingFromSelf, IsBindingFromKeyView, IsBindingFromHelpView,
  and IsFromCommandView from Shortcut

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* tweaks

* Fix Shortcut Key not activating CommandView via HotKey

DefaultHotKeyHandler called InvokeCommand(Command.Activate) without
passing the original binding, so Shortcut.OnActivating could not
distinguish a user-initiated HotKey press from a programmatic invoke.
This caused BubbleDown to be skipped, leaving the CommandView (e.g. a
CheckBox) untoggled when the Shortcut's Key was pressed.

Fix: pass ctx?.Binding through to InvokeCommand so the Activate
command preserves the HotKey binding context.

Add Shortcut_Key_Activates_CheckBox_CommandView test covering both
CanFocus=true and CanFocus=false.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* cleanup

* Add comprehensive BubbleDown tests to ViewCommandTests

11 View-level tests verify the BubbleDown mechanism: context flags,
binding clearing, source/command preservation, and bubble suppression
at single and multi-level hierarchies.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Add Shortcut key/action tests and update BubbleDown docs

- Add unit tests for Shortcut.Action invocation via key events, covering both focus and application-level binding scenarios
- Add test for Accept/Activate event routing when clicking Button CommandView
- Clarify in docs the distinction between Shortcut integration tests and ViewCommandTests for BubbleDown
- Move SelectorBase BubbleDown refactor to a later phase in the plan
- Add instructions to update deep dive and Shortcut architecture docs for new dispatch pattern

* SelectorBase fixed!

* Fix OptionSelector/FlagSelector HotKey command handling

Update SelectorBase to use IsBubblingDown guard for BubbleDown, allowing programmatic InvokeCommand calls and preventing recursion. Remove OnHandlingHotKey override to avoid double-Activate bugs. Add custom HotKey handler to FlagSelector: restores focus, no flag toggle when focused. Rewrite OptionSelector and FlagSelector tests for correct HotKey/Activate behavior. Update command.md docs and table to match keyboard spec. Skip unrelated Menu HotKey test.

* Refactor command acceptance API to use ICommandContext

Update OnAccepted to use ICommandContext instead of CommandEventArgs across View and related classes. Revise all overrides and usages in Dialogs, CharMap, MenuBar, MenuItem, Prompt, OptionSelector, SelectorBase, Shortcut, and tests. Add logging to command handlers for improved debugging. Improve OptionSelector activation and cycling logic. Modernize and streamline command event handling throughout the codebase.

* Fixed OptionSelector Tests

* WIP

* Fixed NumericUpDown activating bug

* Improve context menu and flag selector event handling

Refactor context menu lifecycle in TextField and TextView to create, register, and dispose menus on focus changes, improving resource management and preventing leaks. Update mouse event handling to avoid null reference errors. In debug builds, assign unique Ids to context menus for easier debugging.

In FlagSelector, streamline checkbox event handling by attaching handlers in OnSubViewAdded and removing the _updatingChecked flag. Move activation and value change logic to dedicated methods for clarity. Clean up redundant and commented code.

Update SelectorBase to prevent double event bubbling. These changes enhance robustness, maintainability, and debuggability of UI components.

* WIP: Trying to fix final FlagSelector issues

* WIP: Sruggling with command bubling and IsDefault

* Improve Accept command bubbling and dialog event handling

Updated Dialog<TResult> to use command binding source for Accept actions. Added and revised tests in ViewCommandTests and DialogTests to verify Accept command bubbling to DefaultAcceptView and dialog acceptance from DatePicker, including event count assertions. Adjusted test expectations for new bubbling behavior.

* Refine Accept command bubbling and DefaultAcceptView logic

- Always forward Accept to DefaultAcceptView after Accepting, regardless of bubbling source
- Dialog sets Result based on pressed button or default before base Accepting
- Use command context Source consistently in Accepting logic
- Update tests to reflect new Accept bubbling and event firing behavior
- Ensure dialog Accepted event is not fired for handled Cancel actions
- Improves consistency and clarity of Accept handling and event order

* Improve dialog command handling and keyboard propagation

Refactored View, Dialog, and Wizard command logic to ensure Accept/Enter key events propagate correctly and dialogs are properly accepted. Updated input injection and dialog acceptance tests for accuracy. Removed obsolete ProgressBar and SpinnerView command tests. Code refactored for clarity and maintainability.

* Improve FlagSelector hotkey and activation behavior

Align FlagSelector with spec: hotkey now only restores focus and never toggles value, even when focused. Refactor activation logic to ensure correct event bubbling and value changes, especially for user interactions and programmatic activation. Update tests to reflect new double-click behavior. Minor code cleanups and documentation improvements.

* Refactor FlagSelector HotKey handling per spec

HotKey now only restores focus and never toggles the flag value.
A new Command.HotKey handler is added to skip activation.
OnHandlingHotKey is simplified to be a no-op when focused.
Comments and documentation are updated for clarity.

* Refactor FlagSelector HotKey and "None" checkbox logic

Refactored HotKey handling in FlagSelector to properly restore focus without toggling when not focused, using a new _suppressHotKeyActivate flag and method overrides. Removed the old AddCommand HotKey handler. Also fixed logic for removing the "None" checkbox to only do so when ShowNoneFlag is not set, and cleaned up related redundant code.

* test cleanup

* Fixed TreeView

* Cleanup

* Fix TextField HotKey: allow input of HotKey char when focused

Previously, typing a character matching the TextField's HotKey (e.g., 'E' in "_Enter Path") would trigger the HotKey even when the TextField was focused, preventing normal text input. Now, when the TextField has focus, the HotKey is canceled and the character is inserted as expected. This is achieved by overriding OnHandlingHotKey in TextField and updating the View base logic to allow key processing when the HotKey is canceled. Includes code cleanups, improved null checks, and a new unit test to verify correct behavior. Minor formatting and style improvements are also included.

* Fix Space key handling for text input in TextField/TextView

Removed Space key binding from PopoverMenu to allow text input. Improved TextView hotkey handling so Space and other printable characters are not consumed by Command.Activate. Added unit tests to verify correct insertion of all printable characters and proper Space key behavior. Clarified hotkey handling differences between TextField and TextView.

* Updated docs

* Fix Shortcut BubbleDown and separate Accept/Activate paths

- Uncomment BubbleDown conditionals in OnActivating and OnAccepting so
  commands only bubble down when triggered by a binding (not programmatic)
  and the source is not the CommandView itself
- Remove incorrect InvokeCommand(Activate) from OnAccepting, keeping
  Accept and Activate as separate command paths per design
- Add custom Activate handler that returns false when IsBubblingUp is true,
  allowing SubViews like CheckBox to complete their own activation
- Split ShortcutTests into partial classes (Command, KeyDown, Mouse)
- Add 5 new tests covering Accept/Activate separation, BubbleDown via
  Space key, Enter key Accept path, and Action invocation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Fix ColorPicker16 click in Shortcuts scenario and update docs

Don't set Handled when activation comes from the CommandView so
ColorPicker16.OnActivated runs and picks the color from the mouse
position. Only set Handled when cycling via HotKey or other sources.
Fix the matching code example in shortcut.md which had the logic
inverted.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Refactor Menu hierarchy: migrate Command/TargetView to Shortcut, fix Menu, add tests

- Move TargetView and Command properties from MenuItem down to Shortcut base class
- Move OnAccepted logic (TargetView invocation) from MenuItem to Shortcut
- Fix Menu.OnSubViewAdded: replace AddCommand with Accepting event (collision fix)
- Remove dead code from MenuItem (~65 lines) and Menu (OnAccepting, OnVisibleChanged)
- Simplify Menu.SelectedMenuItem to getter-only property
- Add 9 Shortcut.Command tests, 8 MenuItem tests, 10 Menu tests, 5 Bar tests
- Update command.md with Shortcut/MenuItem/Menu/Bar command table rows
- Add menus-refactor.md plan for upcoming MenuBar/PopoverMenu work
- Clean up stale plan files

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Fix MenuBar mouse click: walk SuperView chain to find MenuBarItem

Mouse clicks on a MenuBarItem land on its CommandView SubView, so the
event source is CommandView, not MenuBarItem. Added OnActivating override
that walks the SuperView chain via FindMenuBarItemForSource to find the
containing MenuBarItem and toggle its PopoverMenu.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Update menus-refactor plan: MenuItem click, integration tests

- Added MenuItem click non-functional issue to Phase 6d
- Added Phase 8: fix integration tests (MenuBar/PopoverMenu, FileDialog)
- Updated execution order and verification steps

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Fix Menu command bubbling: MenuItem HotKey action, menu closing, and MenuBarItem switching

Three root causes fixed:

1. Menu consumed bubbled-up Activate/Accept commands, preventing MenuItem's
   RaiseActivated/RaiseAccepted from firing (Action never invoked). Fix: Menu's
   custom handlers run DefaultHandler (events fire) but return false for
   IsBubblingUp so originating MenuItem completes its processing.

2. HotKey→Activate path didn't trigger menu closing (Accept chain needed).
   Fix: Menu.OnSubViewAdded subscribes to menuItem.Activated → RaiseAccepted,
   triggering PopoverMenu.MenuAccepted → close.

3. Switching MenuBarItems via HotKey caused open-then-close race between
   OnSelectedMenuItemChanged (from SetFocus) and OnActivating (from Activate).
   Fix: MenuBarItem overrides Command.HotKey to skip SetFocus before
   InvokeCommand(Activate) — ShowItem handles focus.

All 18 MenuBarTests pass (was 9/20), 13,928 parallel tests pass.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* warnings

* cleanup

* deleted plans

* Fix TreeView Enter key: bind to Accept instead of Activate

TreeView's Enter key was bound to Command.Activate, but the guard in
ActivateSelectedObjectIfAny only calls RaiseAccepting for Command.Accept.
This prevented Accept from bubbling to FileDialog, leaving Canceled=true.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* removed dupe test

* Fix Release build: replace WasDisposed with SubMenu null check

WasDisposed is only available under DEBUG_IDISPOSABLE. Check that
MenuItem.Dispose sets SubMenu to null instead.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Add EnableForDesign event verification tests

Tests that Bar, MenuBar, and PopoverMenu EnableForDesign hierarchies
raise correct events when commands are invoked on their subviews.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* tweaked menu examples

* Defer Shortcut.Activated on bubble-up

Fixes event ordering when activation bubbles up from a compound CommandView (e.g., CheckBox) to a Shortcut. Previously, Shortcut.Activated and Action could fire before the CommandView's own activation logic, causing stale state to be observed. Now, RaiseActivated is deferred until the CommandView's Activated event, ensuring state is up-to-date.

Shortcut now subscribes/unsubscribes to CommandView.Activated for this purpose. The activation command handler is updated to support deferred activation and correct BubbleDown logic.

Adds three regression tests to verify:
- Action sees updated CheckBox value after bubble-up activation
- Correct event ordering for bubble-up from CommandView
- Correct event ordering for BubbleDown from non-CommandView subviews

These changes improve reliability and predictability of event handling in compound Shortcut scenarios.

* Fix command resource strings and Shortcut.OnActivated TargetView invocation

- Shortcut.OnActivated now invokes TargetView.InvokeCommand (fixes context
  menus not working when activated via mouse click)
- Remove duplicate ctxXXX resource strings; use cmdXXX pattern consistently
- Add missing command resources: Undo, Redo, DeleteAll, Edit, Close_Help
- Fix cmdQuit_Help value and cmdNew value
- Rename .Help keys to _Help in all .resx files for consistency with
  generated Designer property names
- Update all localized .resx files (fr-FR, ja-JP, pt-PT, zh-Hans) with
  translations for new command strings
- Update Editor.cs, ResourceManagerTests to use cmdXXX instead of ctxXXX

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Remove analyzers and related test projects from solution

Removed Terminal.Gui.Analyzers and Terminal.Gui.Analyzers.Tests projects, including all analyzer source files, documentation, and test infrastructure. Updated Terminal.sln and Terminal.Gui.csproj to remove all references to these projects. Also made sender parameter nullable in Button_TitleChanged for consistency.

* Fix integration tests: update expected strings and remove fragile ShowHidePopovers test

- Update "_New file" to "_New" to match corrected cmdNew resource
- Remove ShowHidePopovers test (used reflection on non-existent ShowPopover method)
- Clean up formatting

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Update command.md and command-diagrams.md for Shortcut TargetView changes

- Document that Shortcut.OnActivated and OnAccepted now invoke TargetView
- Update OnActivating code snippet to match current implementation
  (IsBubblingUp check, return BubbleDown result)
- Fix command-diagrams.md: args.Cancel → args.Handled for command events
- Fix command-diagrams.md: Activate bubbling is opt-in, not "no propagation"
- Fix command-diagrams.md: DefaultAcceptView terminology

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Code cleanup. Doc updates.

* Refactor event logging to use new EventLog component

Replaces ad-hoc event logging (ListView/ObservableCollection) with a reusable EventLog view in Bars, Menus, and Selectors scenarios. EventLog is now styled, resizable, and logs events from Bars, Menus, Selectors, and related controls via SetViewToLog. Refactors UI initializations for clarity and consistency. Also updates menu item activation logic in UICatalogRunnable for theme and log level selectors, and improves event handler management. This unifies and modernizes event logging across the UI Catalog sample.

* Fix duplicate activations for Shortcut CommandView subviews

Refactor event handling in Shortcut, SelectorBase, and FlagSelector to prevent duplicate activations and ValueChanged events when activating subviews (e.g., CheckBox in FlagSelector) within a Shortcut's CommandView. Introduce IsWithinCommandView to correctly detect and avoid redundant BubbleDown calls. Modernize event wiring to use ValueChanged handlers, add debug logging, and improve code clarity. Add a unit test to verify the fix.

* Improve focus and visual roles for Shortcut CommandViews

- Set CanFocus=false for single-select CommandViews (CheckBox, Button) and CanFocus=true for multi-select (OptionSelector) to ensure correct focus visuals.
- Add handler to customize CommandView visual roles based on focus state, improving highlight and active state feedback.
- Reduce event log minimum width for better UI flexibility.
- Add theme selector OptionSelector when ConfigurationManager.IsEnabled.
- Enable word wrap in Shortcut HelpView for better help text display.
- Update MenuBar controls to use new CanFocus logic and add explanatory comments.
- Clarify and expand help texts and code comments.

* Fix: Enter key now activates & accepts in OptionSelector

Pressing Enter on a focused OptionSelector or FlagSelector item now both activates (selects) and accepts it, per spec. Previously, only Accept was triggered, so Activating did not fire and Value did not update. The Accept handler now invokes Activate when Enter is pressed on a CheckBox or Accept is called directly. Added tests verify correct behavior for both keyboard and programmatic Accept scenarios.

* Remove manual bubbling workarounds in selectors

Eliminate custom event handlers in OptionSelector and FlagSelector that manually re-invoked Command.Activate and Command.Accept in response to CheckBox events. SelectorBase's CommandsToBubbleUp now correctly handles bubbling, making these subclass workarounds unnecessary. This simplifies the selector hierarchy and clarifies event flow, with no change to user-facing behavior.

* Refactor subview creation in SelectorBase and FlagSelector

Consolidate subview creation logic into a new virtual CreateSubViews
method, removing OnCreatingSubViews and OnCreatedSubViews hooks.
FlagSelector now overrides CreateSubViews to manage the "None"
checkbox more cleanly, adding or removing it as needed based on
ShowNoneFlag and Values. SetLayout is now protected and documented.
Includes minor code cleanup and improved extensibility for subview
management.

* Progress on AddCommand cleanup

* code cleanup

* Fixed tests

* Code cleanup

* Refactor menu and bar APIs for flexibility and testability

- Generalize MenuBar.GetMenuItemsWith to accept predicates, replacing GetMenuItemsWithTitle throughout the codebase
- Allow PopoverMenu.GetMenuItemsOfAllSubMenus to filter with a predicate
- Improve Bar, Menu, MenuBar, and PopoverMenu initialization and design-time support
- Enhance event handling for MenuBarItem and PopoverMenu (activation, acceptance, bubbling)
- Refactor Shortcut command invocation logic for clarity and fallback to app-level bindings
- Clarify and document View.GetTopSuperView; refactor subview movement methods
- Update UICatalog scenarios to use new APIs and improve OptionSelector integration
- Set debug IDs for menus/popovers for easier debugging
- Miscellaneous code cleanups, improved comments, and C# convention adherence

These changes modernize the menu infrastructure, improve maintainability, and lay groundwork for more dynamic menu systems in Terminal.Gui.

* Bar command bubbling: clarify, document, and test behavior

- Simplified Bars scenario setup; commented out menu/status bar code
- Renamed and updated modal event handler in Bars
- Improved context menu logging in Menus; added "TestMenu" and helper
- Added comments in Bar about command bubbling (issue #4473)
- Reorganized and renamed BarTests; added tests for command bubbling
- Documented current Bar command bubbling behavior; may change in future

* Add plan to fix Bar command bubbling and PopoverMenu bridge

This commit adds bar-command-bubbling.md, a detailed, test-driven plan to resolve broken command bubbling in the Bar view (base of Menu/MenuBar) and to bridge Activate commands across the PopoverMenu overlay in Terminal.Gui. The plan covers enabling CommandsToBubbleUp in Bar, implementing custom handlers to allow Activate/Accept to bubble from child views (e.g., Shortcut, CheckBox) without interfering with their logic, and ensuring bubbling works through overlays. It also outlines comprehensive test coverage, phased implementation, and coding style guidelines to avoid regressions in Menu, MenuBar, and Shortcut behaviors.

* Fix command bubbling: clean design for Bar, Menu, Selectors

Core design: DefaultActivateHandler returns false for IsBubblingUp
(notification), eliminating custom AddCommand boilerplate from Bar,
Menu, and MenuBar. Views that need consumption (OptionSelector,
FlagSelector) override OnActivating to return true.

- Bar: Enable CommandsToBubbleUp, remove custom handlers
- Menu/MenuBar: Remove custom Activate/Accept handlers
- DefaultAcceptHandler: Add CommandWillBubbleToAncestor guard to
  prevent double-path (bubble + DefaultAcceptView redirect)
- OptionSelector: Move value logic to OnActivating (bubble) +
  OnActivated (direct), shared via ApplyActivation helper
- FlagSelector: OnActivating toggles checkbox for bubble path
- Shortcut: CommandView_Activated handles IsBubblingUp context
  for views that consume in OnActivating
- Add PopoverMenuTests.cs (3 skipped pending Phase 5 bridging)
- Add 10 new Bar command bubbling tests
- Update command.md and shortcut.md documentation

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Skip ContextMenu_OpenSubmenu integration test pending Phase 5

This test fails because Activate doesn't bridge across the PopoverMenu
boundary yet. Will be unskipped when Phase 5 event bridging is done.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Restore Shortcut activation logic and add bubbling tests

Restores the Shortcut.HandleActivate method and the Command/TargetView properties to support correct activation and bubbling behavior. Improves Shortcut.Action documentation and adds debug logging. Introduces comprehensive unit tests for bubbling and event handling in Bar, Menu, and MenuItem classes, ensuring correct propagation, prevention of double-firing, and proper handling of Accept/Activate commands. Updates existing tests for more precise assertions.

* Add command system redesign requirements and minor fix

Added command-system-redesign-requirements.md documenting all current command routing behaviors, invariants, and pain points, and proposing a clean-slate redesign with new abstractions (CommandRouting enum, GetDispatchTarget, CommandBridge, etc.). Also fixed OptionSelector.OnActivating to return true if base or args.Handled, removing redundant return false. This prepares for a future refactor to improve clarity and maintainability.

* Simplify command routing in composite views

Redesigned Shortcut, OptionSelector, and FlagSelector to use declarative command dispatch overrides (`GetDispatchTarget`, `ConsumeDispatch`). Removed complex activation/bubbling logic and suppress flags, centralizing activation handling in `OnActivated`. Business logic remains unchanged; leaf views are unaffected. This reduces code complexity and improves reliability by leveraging uniform framework command dispatch.

* Synthesize command system redesign: rigorous requirements + pragmatic design

Merges the 172 behavioral parity requirements from the Clean Slate Redesign
plan with a small-surface-area design approach:

- CommandOutcome enum replaces ambiguous bool? returns
- CommandRouting enum (Direct/BubblingUp/DispatchingDown/Bridged) replaces
  two boolean flags
- Immutable CommandContext (readonly record struct with WithCommand/WithRouting)
- GetDispatchTarget + ConsumeDispatch virtuals on View for composite pattern
- CommandBridge class for cross-boundary routing (WeakRef-based)
- ICommandBinding.Source fixed to WeakReference<View>? (memory leak fix)
- ItemSelected event separates menu close from command routing
- Route tracing with duplicate/cycle detection

Net effect: ~200 lines deleted from Shortcut/OptionSelector/FlagSelector,
replaced by 1-2 declarative overrides per view. Leaf views unchanged.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* deleted

* Phase A: Add foundation types for command system redesign

- Add CommandOutcome enum (NotHandled/HandledStop/HandledContinue) with bool? conversion shims
- Add CommandRouting enum (Direct/BubblingUp/DispatchingDown/Bridged)
- Make CommandContext a readonly record struct with WithCommand/WithRouting methods
- ICommandContext properties now read-only; Routing property added alongside compat IsBubblingUp/IsBubblingDown
- Change ICommandBinding.Source from View? to WeakReference<View>? to prevent memory leaks
- Update all binding types (KeyBinding, MouseBinding, CommandBinding) for WeakReference Source
- Update Shortcut.cs pattern matching for WeakReference binding Source
- Update all test assertions for the new types

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Fix RecordEquality test for WeakReference Source

Two WeakReference instances to the same target are not reference-equal,
so use a shared instance for record equality testing.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* WIP Phase B: Add GetDispatchTarget/ConsumeDispatch framework

- Add GetDispatchTarget and ConsumeDispatch virtual members to View
- Integrate dispatch into RaiseActivating and RaiseAccepting
- Migrate Shortcut to use GetDispatchTarget => CommandView (relay dispatch)
- Migrate OptionSelector to use GetDispatchTarget + ConsumeDispatch=true
- Migrate FlagSelector to use GetDispatchTarget + ConsumeDispatch=true
- Update DefaultActivateHandler and DefaultAcceptHandler for dispatch completion
- Update tests for new dispatch ordering (Activating fires before dispatch)
- 3 test failures remain (event ordering, FlagSelector value, PopoverMenu integration)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Phase B: Implement GetDispatchTarget/ConsumeDispatch dispatch pattern

Framework changes (View.Command.cs):
- Add GetDispatchTarget virtual (returns SubView to dispatch to, null to skip)
- Add ConsumeDispatch virtual (true = consume originator, false = relay)
- Integrate TryDispatchToTarget into RaiseActivating and RaiseAccepting
- DefaultActivateHandler fires RaiseActivated for composite views on bubble
- DefaultAcceptHandler handles composite view completion on bubble
- IsSourceWithinView helper prevents dispatch loops

Shortcut migration (~120 lines deleted):
- GetDispatchTarget => CommandView (relay pattern)
- Deleted HandleActivate, IsWithinCommandView, _activationBubbledUp,
  _deferredActivationContext, OnActivating override, OnAccepting override
- Simplified CommandView_Activated to deferred completion callback
- OnActivated/OnAccepted preserved (Action + InvokeOnTargetOrApp)

OptionSelector migration (~23 lines deleted):
- GetDispatchTarget => source CheckBox or Focused (Activate only)
- ConsumeDispatch => true
- Deleted OnActivating override
- OnActivated calls ApplyActivation uniformly

FlagSelector migration (~50 lines deleted):
- GetDispatchTarget => source CheckBox or Focused (Activate only)
- ConsumeDispatch => true
- Retained _suppressHotKeyActivate for HotKey no-op semantics
- OnActivated toggles CheckBox directly for bubble path

All 14,981 tests pass (0 failures, 44 pre-existing skips).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Phase C: Implement CommandBridge for cross-boundary routing

- Add CommandBridge class that bridges Accepted/Activated events across
  non-containment boundaries with CommandRouting.Bridged context
- Migrate MenuBarItem to use CommandBridge.Connect for PopoverMenu→MenuBarItem
  Accept bridging (replaces manual OnPopoverMenuOnAccepted handler)
- Remove dead OnPopoverMenuOnActivated (was a no-op)
- Make RaiseAccepted/RaiseActivated internal protected for CommandBridge access
- CommandBridge uses WeakReference for both owner and remote views

All 13,980 parallelizable tests pass (0 failures).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Phase E: Remove IsBubblingUp/IsBubblingDown compat properties

- Remove IsBubblingUp and IsBubblingDown from ICommandContext interface
- Remove backward-compat properties from CommandContext record struct
- Replace all usages with CommandRouting enum checks:
  - ctx?.IsBubblingUp == true → ctx?.Routing == CommandRouting.BubblingUp
  - ctx?.IsBubblingDown == true → ctx?.Routing == CommandRouting.DispatchingDown
  - { IsBubblingUp = true } → { Routing = CommandRouting.BubblingUp }
  - { IsBubblingDown = true } → { Routing = CommandRouting.DispatchingDown }
- Update CommandContext.ToString to use Routing directly
- Update test assertions to use CommandRouting enum

All 13,980 parallelizable tests pass (0 failures).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* chore: initialize work for #4728

* Update plan with implementation status and deviations

Documents all deviations from the original plan discovered during
implementation, including:
- Shortcut still needs CommandView_Activated callback for ordering
- ConsumeDispatch=true skips BubbleDown for IsBubblingUp
- Selectors dispatch Activate-only (Accept bubbles normally)
- Context-dependent dispatch targets (source vs Focused)
- FlagSelector retains _suppressHotKeyActivate
- Event ordering: Activating fires before dispatch
- Phase D deferred (267 call sites, mechanical)
- Phase C scoped to cross-boundary only (MenuBarItem)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Fix: only set _lastDispatchOccurred when BubbleDown actually fires

When relay dispatch (ConsumeDispatch=false) skips BubbleDown because
the source is within the target (e.g., CommandView clicking itself),
_lastDispatchOccurred was incorrectly set to true. This prevented
RaiseActivated from firing in DefaultActivateHandler, breaking the
completion path for views like MenuBarItem where the activation comes
from CommandView bubbling up.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: add ambient scoped logging for parallel tests

* fix: create logging scope on owning test thread

* Fix OptionSelector value in DispatchingDown path (SubMenu scenario)

When OptionSelector is a CommandView inside a MenuItem/Shortcut and
activation arrives via DispatchingDown from the Shortcut, ctx.Source
is the OptionSelector itself (not the clicked CheckBox). ApplyActivation
now uses the Focused CheckBox for DispatchingDown routing, falling back
to Cycle() only for programmatic invocations.

This fixes the Menus scenario where clicking a CheckBox inside an
OptionSelector in a PopoverMenu SubMenu would set Value to 1 instead
of the correct index.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Revert "Fix OptionSelector value in DispatchingDown path (SubMenu scenario)"

This reverts commit 2dee550bdddecab6290140bb4df28f515bb97046.

* Add TODO and tests for OptionSelector in SubMenu dispatch issue

- Revert the incorrect OptionSelector fix (ApplyActivation Focused fallback)
- Add TODO documenting the root cause: when activation arrives via
  DispatchingDown from Shortcut, ctx.Source is the OptionSelector, not
  the clicked CheckBox, causing Cycle() instead of direct selection
- Add 3 tests (mouse click, Space, Enter) for OptionSelector<Schemes>
  in MenuBar.EnableForDesign's Preferences SubMenu. Tests currently pass
  because they bypass the Shortcut dispatch path — the bug only manifests
  in the full PopoverMenu display flow where LeftButtonReleased propagates
  to the parent Shortcut instead of being handled by the CheckBox directly.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Add FAILING integration test for mouse click on OptionSelector in SubMenu

OptionSelector_In_SubMenu_Click_Sets_Correct_Value clicks directly on
the Error checkbox in a PopoverMenu SubMenu. FAILS: Expected Error (4),
Actual Menu (1). The LeftButtonReleased event propagates from the
CheckBox (which only handles LeftButtonClicked) to the parent
Shortcut/MenuItem, which dispatches with Source=OptionSelector.
ApplyActivation sees non-CheckBox source and calls Cycle() (0→1)
instead of selecting Error (4). The menu also closes unexpectedly.

OptionSelector_In_RootMenu_Space_Sets_Correct_Value passes (keyboard
path works correctly).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Add Bar-with-Shortcuts integration test (PASSES)

Bar_CommandView_In_Menu_Click_Activates_Correct_Shortcut tests a Bar
with 3 Shortcuts as CommandView of a MenuItem. Mouse click on the second
Shortcut correctly activates only that Shortcut. This PASSES, proving
the dispatch issue is specific to ConsumeDispatch=true views
(OptionSelector, FlagSelector), not a general compound CommandView issue.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Fixed PopvoerMenu issue - Now checkbox is broke.

* Fixed tons of activatiion issues. MenuBar hiding is not working.

* Code cleanup

* Broke MenuBar/PopoverMenu but progress

* fixed plans

* plans

* Fixes #1 - Command bubbling/dispatch event propagation

Refined command bubbling and dispatch logic to fix event propagation bugs:
- DefaultActivateHandler now fires Activated on bubble-up for plain views, matching Accept handler, ensuring SuperViews receive Activated notifications.
- Relay-dispatch views (Shortcut) retain deferred completion; Activated fires only after CommandView completes.
- Reset _lastDispatchOccurred at start of default handlers to prevent stale state and spurious completion events.
- Shortcut resets _activatedFiredThisCycle at start of each activation cycle to prevent stuck flag after programmatic activation.
- Renamed BubbleDown to DispatchDown throughout code and docs for clarity.
- Added unit tests for bubbling, deep hierarchy, consume-dispatch blocking, and regression scenarios.
- Updated documentation to clarify bubbling vs dispatching, routing, and composite view behaviors.
- Verified against full test suite; all new tests pass, no regressions (except known MenuBar/PopoverMenu failures).
- Command bubbling and dispatch are now robust, predictable, and correctly notify SuperViews of activation and acceptance events.

* Fixes #4728 - Add ambient scoped logging with AsyncLocal for parallel test isolation

- Add Logging.PushLogger() API for per-test/per-context log routing
- Use AsyncLocal<ILogger> to flow logger across async boundaries
- Preserve global Logging.Logger for backward compatibility
- Add TestLogging helper (BindTo/Verbose) for easy xUnit integration
- Default test logging shows only Warning+ (Verbose for debugging)
- Update InitTests to use verbose logging
- Update docfx/docs/logging.md with comprehensive user guide

* Add command routing trace infrastructure (Phase E)

Introduces a new CommandTrace system for structured, runtime-controllable tracing of command routing in the View system. Replaces all commented-out Logging.Debug statements in View.Command.cs with TraceRoute calls, enabling detailed tracing in DEBUG builds with zero overhead in release builds.

Implements pluggable backends (NullBackend, LoggingBackend, ListBackend) for flexible logging and test capture. Adds RouteTraceEntry record and CommandTracePhase enum to describe trace events. Includes unit tests for the tracing infrastructure and documents the design and rationale in command-manager-exploration.md.

Completes Phase E of the command system redesign, improving debugging, testability, and maintainability of command flow.

* Fix SubMenu command bridging and add CommandView propagation tests

- Remove redundant menuItem.Accepting subscription in Menu.OnSubViewAdded
  that caused double-fire of Accepted (CommandsToBubbleUp already handles it)
- Add CommandBridge in MenuItem.SubMenu setter to bridge Activate and Accept
  completion events from SubMenu to parent MenuItem across non-containment boundary
- Add 7 SubMenu command propagation tests in MenuItemTests.cs
- Add 9 CommandView propagation tests in MenuTests.cs covering CheckBox (relay
  dispatch), Button (Accept path), and FlagSelector (ConsumeDispatch) through
  single Menu and SubMenu hierarchies with value verification

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Add CommandTrace.IsEnabled config property and UICatalog menu toggle

- Add ConfigurationProperty IsEnabled to CommandTrace for runtime control
- Add 'Command Trace' CheckBox to UICatalog's Logging menu
- Update command.md with Command Route Tracing section
- Update logging.md with command tracing reference
- Use AsyncLocal for thread-safe backend storage in parallel tests

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* plans

* Add unified ViewTrace system with independent category controls

- Create ViewTrace class in Terminal.Gui/App/Tracing/ with:
  - CommandEnabled, MouseEnabled, KeyboardEnabled properties
  - TraceCategory flags enum
  - TraceEntry record with generic Data payload
  - ITraceBackend interface with NullBackend, LoggingBackend, ListBackend
- Update CommandTrace to delegate to ViewTrace while maintaining backward compatibility
- Add Trace.Mouse() calls to View.Mouse.cs and MouseImpl.cs
- Add Trace.Keyboard() call to View.Keyboard.cs
- Update UICatalog Logging menu with 3 separate trace toggles
- Add ViewTraceTests with 13 tests

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Remove commented Logging.Debug calls from various files

Clean up dead commented-out debug logging from:
- ApplicationPopover.cs
- Configuration/Scope.cs, SourcesManager.cs, ThemeManager.cs
- CollectionNavigatorBase.cs
- FlagSelector.cs, OptionSelector.cs
- Shortcut.cs

Note: Menu-related Logging.Debug comments preserved as Menu system
is still being debugged (pre-existing test failures).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Update documentation for unified ViewTrace system

- Update logging.md with View Event Tracing section covering Command/Mouse/Keyboard
- Update command.md to reference ViewTrace as the unified system
- Add custom backend example and legacy API note

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Fix CommandBridge pipeline, add Menu.OnActivating dispatch, update docs

Gap 2: CommandBridge now calls InvokeCommand instead of RaiseAccepted/
RaiseActivated, enabling bridged commands to re-enter the full command
pipeline and propagate through the owner's SuperView hierarchy. Added
Bridged routing guard in TryDispatchToTarget and DefaultAcceptHandler.

Gap 3: Menu.OnActivating dispatches Command.Activate to the focused
MenuItem, enabling menu.InvokeCommand(Activate) to reach the selected
MenuItem and its CommandView (e.g., CheckBox toggles).

Updated command.md and plan with implementation details.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Simplify trace system: rename ViewTrace to Trace, remove CommandTrace

- Rename ViewTrace class to Trace (covers Driver→App→View tracing)
- Remove CommandTrace, ICommandTraceBackend, RouteTraceEntry, CommandTracePhase
- Replace CommandTrace.TraceRoute calls with Trace.Command in View.Command.cs
- Auto-enable LoggingBackend when any trace category is enabled
- Add string-based overloads for Driver/Application-level traces
- Add tests for auto-enable behavior
- Update documentation (logging.md, command.md)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Refactor tracing to Terminal.Gui.Tracing namespace

Moved all tracing infrastructure (Trace, ITraceBackend, TraceEntry, and backends) into a new Terminal.Gui.Tracing namespace. Split NullBackend, LoggingBackend, and ListBackend into separate files. Updated all usages to reference the new namespace, including tests and application code. Simplified and clarified Trace method signatures. Added more detailed trace calls to mouse and keyboard event handling for improved debugging. LoggingBackend now uses Logging.Trace for output. This refactor improves modularity, clarity, and testability of the tracing system.

* Update trace documentation for namespace and Logging.Trace

- Update LoggingBackend doc comment to reference Logging.Trace
- Update logging.md: Add namespace info, using statements, fix backend examples
- Update command.md: Add namespace info, using statements, fix examples
- Add Mouse Tracing section to mouse.md
- Add Keyboard Tracing section to keyboard.md
- All docs now reference Terminal.Gui.Tracing namespace

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Fixes #4620 - Composite selector activation fallback

Previously, FlagSelector and OptionSelector did not update their state when activated via external dispatch (Menu → MenuItem → Selector) due to the DispatchingDown guard blocking inner CheckBox activation. This update adds a fallback: when activation arrives via DispatchingDown and the source is not a CheckBox, the currently focused inner CheckBox is used as the toggle/selection target. Unit tests were added and updated to verify this behavior. Documentation was revised to mark Gap #1 as completed and explain the solution. Minor code cleanups and formatting improvements included.

* Fix MenuBar/PopoverMenu command routing — resolve 12 test failures

MenuBar.OnActivating was a no-op, causing all command-based activation
(keyboard, HotKey, InvokeCommand) to fail while mouse clicks worked.
The fix applies the same dispatch pattern established in Menu.OnActivating:
guard against BubblingUp, toggle Active state, and show the first
MenuBarItem with a PopoverMenu.

Additional fixes:
- MenuBarItem: guard against Bridged commands toggling PopoverMenu
- MenuBarItem: guard MakeVisible when App/init unavailable
- CommandBridge: replace Logging.Debug with Trace.Command
- SelectorBase: replace Logging.Debug with Trace.Command
- Trace: add Command overload accepting view+phase+message
- PopoverMenuTests: skip Phase 5 test blocked by ConsumeDispatch

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Fixes #4620 - Reengineer MenuBar activation & tests

Major overhaul of MenuBar activation, command routing, and state logic to fix long-standing bugs and enable robust, parallelizable testing.

- Replaced `_isOpen` with `_popoverBrowsingMode` for accurate popover tracking.
- Fixed bug where QuitKey/Escape did not fully deactivate MenuBar or close all popovers; now ensures `Active` is false and focus is restored when all popovers close.
- Added guards in `OnActivating` to prevent activation when MenuBar is not visible or enabled.
- Improved bubbling logic: MenuBar now correctly activates and shows the relevant MenuBarItem when a child activation bubbles up, and deactivates when popovers close.
- Ensured reliable switching between MenuBarItems via HotKey or arrow keys, with correct popover and focus state.
- Refactored code for clarity, removed dead code, and improved comments.

Testing:
- Deleted legacy, non-parallelizable MenuBar tests.
- Added a comprehensive suite of parallelizable tests covering all old scenarios and new edge cases (arrow navigation, focus restoration, property changes, event firing).
- All tests now use modern VirtualTimeProvider/IApplication patterns.

Documentation:
- Added `menubar-reengineer.md` detailing the bugs fixed, rationale, test mapping, and verification steps.

MenuBar, MenuBarItem, and PopoverMenu now have robust, predictable activation and focus behavior. All legacy and new tests pass.

* Consolidate plan docs — definitive command system reference

Delete command-system-redesign-requirements.md, command-manager-exploration.md,
and logging-implementation-status.md. Rewrite finalizing-command-system.md as the
single definitive reference for the re-engineered command system. Update
menubar-reengineer.md to reflect all phases complete.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Removed dupe test

* removed dupe test.

* Add failing tests: QuitKey and MenuItem activation don't fully deactivate MenuBar

Two tests documenting MenuBar bugs:
- QuitKey_With_PopoverMenu_Visible_Fully_Deactivates: Escape closes PopoverMenu
  but menuBar.Active stays true
- MenuItem_Activate_Fully_Deactivates_MenuBar: MenuItem action fires but MenuBar
  stays active instead of closing

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Fix MenuBar not deactivating on QuitKey and MenuItem activation

When a PopoverMenu closed (via QuitKey or MenuItem activation), MenuBar
stayed Active because OnMenuBarItemPopoverMenuOpenChanged ignored the
close case. Added _isNavigating guard so arrow-key switching (where old
popover closes before new opens) still works correctly.

Fixes the two failing tests from previous commit.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Still throws an exception on move over menubaritems.

* MenuBar 99% fixed.

* Code cleanup

* More code cleanup

* Refactored MenuBar, MenuBarItem, and PopoverMenu to fix subtle bugs in menu activation, hotkey handling, and focus management. Introduced robust tracing with Trace.Command and Trace.Keyboard for diagnostics. Replaced legacy event-based bridging in PopoverMenu with a single CommandBridge and clarified command routing logic. Improved focus invariants and prevented transient/intermediate menu openings during hotkey activation.

Added comprehensive regression tests to verify correct menu activation (e.g., Alt+E opens Edit, not File), focus chain integrity, and correct propagation of Activate/Accept through menu bridges. Updated spelling/grammar exceptions and improved code comments for clarity. This significantly improves reliability and maintainability of the menu system.

* Fix CursorRight/Left not switching MenuBarItem popovers when open

MoveRight/MoveLeft in MenuBar were wrapping AdvanceFocus with
_isSwitchingItem=true, which blocked OnSelectedMenuItemChanged from
calling ShowItem on the newly focused MenuBarItem. Removed the flag
from MoveRight/MoveLeft — ShowItem already has its own internal
_isSwitchingItem guard for the focus transfer it performs.

Added CursorRight_While_PopoverOpen_Switches_To_Next_MenuBarItem unit
test covering full left/right navigation with wrapping. Removed unused
outerMenuActivatedCount variable from MenuTests.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Fix submenu not removed when PopoverMenu hidden, causing key leaks

HideAndRemoveSubMenu's _isHiding re-entrancy guard blocked its own
recursive call for nested submenus. Only the root Menu was removed;
visible submenus remained as orphaned SubViews. This caused the
inactive PopoverMenu to still dispatch HotKeys (B, D, E, M, R) to
submenu MenuItems after the MenuBar was deactivated.

Fix: temporarily reset _isHiding before the recursive call so nested
s…
tig added a commit that referenced this pull request Mar 9, 2026
Fix two bugs that broke InputInjectionMode.Pipeline:
1. InputProcessorImpl used DateTime.Now instead of _timeProvider.Now for
   stale escape detection, causing immediate release with VirtualTimeProvider
2. AnsiInputProcessor.InjectKeyDownEvent/InjectMouseEvent routed through
   the background input thread; now enqueues directly to InputQueue

Simplify InputInjector.ProcessQueue() by removing the VirtualTimeProvider
60ms-advance workaround (no longer needed with bug #1 fixed).

Un-skip two Pipeline tests and add 27 kitty protocol pipeline tests
covering event types, modifiers, functional keys, standalone modifier
keys, CSI ~/cursor variants, full press-repeat-release cycles, and
negative cases (invalid event types, malformed sequences, recovery).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
tig added a commit that referenced this pull request Mar 10, 2026
…ent model (gui-cs#4816)

* Start Phase 2: Rich keyboard event model

Mark Phase 2 as in-progress in the kitty keyboard protocol plan.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Complete Phase 2: Rich keyboard event model with KeyUp, EventType, and ModifierKey

- Add KeyEventType enum (Press/Repeat/Release) and ModifierKey enum for standalone modifier identity
- Extend Key with EventType, ModifierKey, and IsModifierOnly properties (additive, non-breaking)
- Add KeyUp event pipeline: IInputProcessor → IDriver → IKeyboard → Application → View
- Enable kitty flag 2 (report event types) alongside flag 1 (disambiguate escape codes)
- Extract shared ApplyModifiersAndEventType helper in AnsiKeyboardParserPattern base class
- Update CsiKeyPattern and CsiCursorPattern regexes to accept kitty modifiers:event_type format
- Map kitty modifier key codepoints (57358-57451) to ModifierKey enum in KittyKeyboardPattern
- Rename KittyKeyboardPhase1Flags → KittyKeyboardRequestedFlags
- Update Keys scenario to display event type, modifier key identity, and KeyUp events
- Update keyboard.md and drivers.md documentation
- Add 44 new tests (KeyEventTypeTests + KittyKeyboardPhase2Tests)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Fix pipeline injection mode and add kitty protocol pipeline tests

Fix two bugs that broke InputInjectionMode.Pipeline:
1. InputProcessorImpl used DateTime.Now instead of _timeProvider.Now for
   stale escape detection, causing immediate release with VirtualTimeProvider
2. AnsiInputProcessor.InjectKeyDownEvent/InjectMouseEvent routed through
   the background input thread; now enqueues directly to InputQueue

Simplify InputInjector.ProcessQueue() by removing the VirtualTimeProvider
60ms-advance workaround (no longer needed with bug #1 fixed).

Un-skip two Pipeline tests and add 27 kitty protocol pipeline tests
covering event types, modifiers, functional keys, standalone modifier
keys, CSI ~/cursor variants, full press-repeat-release cycles, and
negative cases (invalid event types, malformed sequences, recovery).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Fixes gui-cs#4582 - Windows console input encoding for accented chars

Previously, input bytes from the Windows console were always decoded as UTF-8, but ReadFile returns bytes in the console's input code page (e.g., Windows-1252). This caused accented and non-ASCII characters to be misread. This commit introduces a ConsoleInputEncoding property in WindowsVTInputHelper to dynamically use the correct encoding, and updates AnsiInput to use it. Adds unit tests to verify correct decoding of accented characters. Also includes minor test cleanups and improved naming.

* fixed test name

* Fixes link bug that was causing Windows tests to hang.

* Add support for standalone modifier key events (kitty)

Include kitty flag 8 to enable reporting of standalone modifier key events (e.g., Shift, Ctrl, Alt) as escape codes. Update tests to verify correct handling of modifier-only key press and release events, and assert that the requested kitty flags include "report all keys as escape codes." This improves compatibility with terminals supporting the kitty keyboard protocol.

* Update AI agent instructions with comprehensive Copilot guide and new coding conventions

- Replaced .github/copilot-instructions.md stub with full reference covering
  build/test commands, architecture overview, code style, terminology, and
  testing conventions
- Added early return/guard clause convention across all AI instruction files
- Added one-type-per-file convention for public and internal types
- Updated CONTRIBUTING.md (source of truth), CLAUDE.md, and AGENTS.md

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Refactor: use KittyKeyboardFlags enum for protocol flags

Replaces raw int usage with strongly-typed KittyKeyboardFlags enum for kitty keyboard protocol flags throughout the codebase. Adds KittyKeyboardFlags.cs and moves KittyKeyboardProtocolResult to its own file, updating it to use the new enum. Updates all related logic, methods, and tests for improved type safety, clarity, and maintainability.

* Kitty protocol: add alternate key reporting (flag 4)

Adds full support for kitty keyboard protocol "alternate key reporting" (flag 4) in Terminal.Gui. The Key model now exposes ShiftedKeyCode and BaseLayoutKeyCode, populated by the kitty parser for each key event. Updates the parser, documentation, and tests to cover alternate key fields, international layouts, and end-to-end propagation. Replaces old phase 2 tests with new, comprehensive suites for parsing, pipeline, and Key object behavior. Improves operator and parsing logic in Key, and updates docs to guide usage of new features.

* Fix race condition in ResetState Driver disposal

Two threads (test + AppTestHelper background) could race into Dispose() →
ResetState() concurrently. Thread A nulls Driver between Thread B's null-check
and Driver.Dispose(), causing NullReferenceException.

Fix: capture Driver to local, null the property, then unsubscribe and dispose
using the captured local. Concurrent callers see null and skip cleanup.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants