mirror of
https://github.com/gui-cs/Terminal.Gui.git
synced 2026-03-26 04:41:10 +00:00
v2_develop
36 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
de15647db0 | fixed claude settings | ||
|
|
cf94c0a677 |
Fixes #4473 - Re-engineerCommand system and Fix Menus (#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
|
||
|
|
e9976da95e |
Reapply "Merge branch 'v2_develop' of tig:gui-cs/Terminal.Gui into v2_develop"
This reverts commit
|
||
|
|
845c05ff47 |
Revert "Merge branch 'v2_develop' of tig:gui-cs/Terminal.Gui into v2_develop"
This reverts commit |
||
|
|
5efbfe1be4 |
Fixes #4562 - DocFX documentation link warnings (#4564)
* updates * commiting to avoid crruption * Fix DocFX documentation link warnings (#4562) Fixed 197 out of 226 DocFX warnings (87% reduction) by correcting invalid API documentation links across multiple documentation files. Changes: - Fixed namespace issues: Updated links to use correct namespaces (Drawing, Input, ViewBase, Views, App, Configuration, Drivers) - Fixed missing type mappings: - RunState → SessionToken - IConsoleDriver → IDriver - MouseEventArgs → Mouse - Converted 100+ invalid bookmark-style links to xref format - Changed from: [Property](~/api/Class.yml#bookmark) - Changed to: <xref:Namespace.Class.Property> - Fixed generic type format in links (e.g., FlagSelector`1, TreeView`1) - Fixed nested member links (e.g., Shortcut.Key, MenuBarItem.PopoverMenu) Files modified: - docfx/docs/View.md (60+ link fixes) - docfx/docs/newinv2.md (30+ link fixes) - docfx/docs/arrangement.md (20+ link fixes) - docfx/docs/config.md (10+ link fixes) - docfx/includes/arrangement-lexicon.md (2 link fixes) - docfx/docs/mouse.md (minor fixes) Remaining 29 warnings are primarily in views.md (excluded per guidance), missing image files, and internal document bookmarks. Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * removed local packages * built --------- Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com> |
||
|
|
cc8ff633fa |
Fixes #4417 - Updates UI Catalog & Scenarios to instance-based app model (#4547)
* Add ScenarioRunner project and extract Runner class (#4417) - Create Examples/ScenarioRunner project with CLI for running scenarios - Extract Runner class to UICatalog with RunScenario and benchmark methods - Refactor UICatalog.cs to use the shared Runner class - CLI supports: list, run <scenario>, benchmark [scenario] Part of issue #4417 - Phase 4 implementation. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * tweaks * Extract interactive mode loop and config watcher to Runner class - Move RunInteractive<T>() method to Runner class for reusable scenario browser loop with config file watching - Add Force16Colors option to ScenarioRunner and UICatalog CLI - Add ApplyRuntimeConfig() to Runner for consistent driver/color settings - Refactor UICatalog to delegate to Runner.RunInteractive<UICatalogRunnable>() - Remove duplicated config watcher and verification code from UICatalog Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Refactor to use IApplication; remove static Application usage Refactored the codebase to adopt the new IApplication interface and instance-based application lifecycle management. Replaced static Application.Init/Shutdown/Run calls with Application.Create()/app.Init()/app.Run() patterns for proper disposal and flexibility. Updated usages of Application.Driver and Application.IsMouseDisabled to use instance-based access via App or Driver. Modernized event handler patterns, made UI fields nullable and non-readonly, and improved scenario launching logic. Switched driver name retrieval to DriverRegistry.GetDriverNames(). Cleaned up command-line parsing and removed obsolete suppressions. Added "Dont" to the user dictionary. These changes reduce reliance on static state, improve maintainability, and align the codebase with current Terminal.Gui best practices. * Modernize scenarios to use instance-based Application model and add lifecycle events Update all UICatalog scenarios to use the modern instance-based Application pattern (Application.Create() / app.Init()) instead of the legacy static pattern. Add thread-local static events (InstanceCreated, InstanceInitialized, InstanceDisposed) to Application for monitoring application lifecycle in tests. Update ScenarioTests to use new events and fix documentation examples in arrangement.md and config.md. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add FSharpExample project to solution Added a new F# example project (FSharpExample) to the solution under the Examples folder. Updated the solution file to include the project, its GUID, and configuration mappings for Debug and Release builds. This improves language coverage in the example set. * Remove FSharpExample project from solution * Remove custom handling of Application.QuitKey Eliminated code that saved, restored, and modified Application.QuitKey. The application no longer changes the QuitKey to Ctrl+F4 on load, and no longer restores the original QuitKey after execution. * Fix LineDrawing.PromptForColor to use IApplication and add try/catch to scenario tests - Add IApplication parameter to PromptForColor method so dialogs can run properly with the modern instance-based Application model - Update all callers in LineDrawing.cs, RegionScenario.cs, and ProgressBarStyles.cs - Add try/catch around scenario execution in ScenarioTests to prevent test host crashes when scenarios throw exceptions Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add in-memory log capture for scenario debugging with error dialog - Add ScenarioLogCapture class (ILoggerProvider) for capturing logs in-memory - Integrate LogCapture into UICatalog logger factory - Add MarkScenarioStart/GetScenarioLogs for scenario-scoped log capture - Track HasErrors flag for Error-level and above logs - Add unit tests for ScenarioLogCapture (17 tests) - Add unit tests for Runner class (8 tests) - Various refactoring and cleanup Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Fix benchmark mode to use instance-based Application model - Update Scenario.StartBenchmark to use Application.InstanceInitialized and Application.InstanceDisposed instead of legacy InitializedChanged - Store app instance and use it for timeouts, events, and InjectKey - Fix UICatalog.cs to pass options.Benchmark instead of hardcoded false - Add XML documentation to BenchmarkResults and Scenario benchmark APIs - Use expression-bodied members for simple Scenario methods Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * fixed bug. * fixed bug * Fix Release build failures - Wrap View.VerifyViewsWereDisposed() calls in #if DEBUG_IDISPOSABLE (method only exists in Debug builds) - Change SelfContained and NativeAot to always use ProjectReference (fixes build order issues in Release configuration) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com> * tweaked gitignore --------- Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com> |
||
|
|
94ed1aed8a |
Add devcontainer config for GitHub Codespaces (#4545)
Enables cloud-based development with .NET 8.0, Node.js 20, and Claude Code CLI pre-installed. Removes .devcontainer/ from .gitignore so the config is shared with all contributors. Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com> |
||
|
|
258529c05d |
Modernize UICatalog scenarios and fix ReSharper warnings (#4544)
* Modernize ContextMenus scenario and add upgrade guide - Add #nullable enable to ContextMenus.cs - Move _cultureInfos initialization after Application.Init() - Replace var with explicit types for Label - Convert if statements to switch statement with not-null patterns - Change local constants to SCREAMING_CASE per project conventions - Add SCENARIO_UPGRADE_GUIDE.md with modernization checklist Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Modernize TextInputControls scenario - Add #nullable enable and fix all nullable warnings - Use modern IApplication pattern with using IApplication app - Replace var with explicit types for non-built-in types - Use target-typed new () syntax throughout - Add null checks for nullable fields and parameters - Fix event handler sender parameter nullability - Remove Application.Shutdown() (handled by IApplication disposal) - Run ReSharper full cleanup for formatting Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Fix ReSharper hints in TextInputControls and modernize Editor TextInputControls.cs: - Fix captured variable issue by using sender parameter - Rename local function to camelCase (textViewDrawContent) - Replace unused lambda parameters with discards (_) - Convert List initializer to collection expression - Remove unnecessary null check Editor.cs: - Add modern IApplication pattern with using IApplication app - Replace Application.Run with app.Run - Replace Application.RequestStop with _appWindow?.RequestStop - Remove Application.Shutdown() (handled by IApplication disposal) - Run ReSharper full cleanup for formatting Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Update SCENARIO_UPGRADE_GUIDE with ReSharper hint fixes Add guidance for: - Lambda parameter discards (replace unused with _) - Captured variable closures (use sender or disable warning) - Local function naming (camelCase) - Collection expressions (use [...] syntax) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Restructure AI guidance for drift prevention Create .claude/ directory with focused rule files: - REFRESH.md - Pre-edit checklist (read before every file) - rules/type-declarations.md - No var except built-in types - rules/target-typed-new.md - Use new() syntax - rules/terminology.md - SubView/SuperView vs Parent/Child - rules/event-patterns.md - Lambdas, closures, handlers - rules/collection-expressions.md - [...] syntax - rules/cwp-pattern.md - Cancellable Workflow Pattern - tasks/scenario-modernization.md - Moved from Examples/ Simplify CLAUDE.md to reference .claude/ structure instead of duplicating detailed guidance. This helps AI agents stay on track by providing focused, re-readable micro-documents. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add Claude Code settings to .gitignore These are user-local settings files that shouldn't be tracked. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add code layout guidance for ReSharper backing field bug Document known ReSharper bug (RSRP-484963) where "Properties w/ Backing Field" layout doesn't work. AI agents must manually place backing fields immediately before their associated properties. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Fix ReSharper warnings across UICatalog scenarios - Replace `is { }` with `is not null` for simple null checks - Fix unused lambda parameters: `(s, e)` → `(_, _)` or `(_, e)` - Change `var` to explicit types (Label, Window, FrameView, etc.) - Remove redundant null-forgiving operators and self-assignments - Modernize Application.Init pattern with `using IApplication app` - Use pattern matching: `if (sender is not OptionSelector x)` - Preserve `is { } variable` pattern matching where variable capture needed Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Fixed two scenarios. --------- Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com> |
||
|
|
28971a50bb |
Fixes broken v1 to v2 migration documentation link (#4532)
* Initial plan * Re-add migratingfromv1.md and remove from .gitignore Co-authored-by: tig <585482+tig@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: tig <585482+tig@users.noreply.github.com> |
||
|
|
b9f55a5a96 |
Fixes #4410, #4413, #4414, #4415 - MessageBox nullable, Clipboard refactor, fence for legacy/modern App, and makes internal classes thread safe. (#4411)
* Initial plan * Change MessageBox to return nullable int instead of -1 Co-authored-by: tig <585482+tig@users.noreply.github.com> * Initial plan * Add fencing to prevent mixing Application models Co-authored-by: tig <585482+tig@users.noreply.github.com> * Fix fence logic to work with parallel tests Co-authored-by: tig <585482+tig@users.noreply.github.com> * WIP: Fixing Application issues. * Refactor error messages into constants Co-authored-by: tig <585482+tig@users.noreply.github.com> * Refactor ConfigurationProperty properties to use static backing fields and raise events Co-authored-by: tig <585482+tig@users.noreply.github.com> * Reset static Application properties in ResetStateStatic Co-authored-by: tig <585482+tig@users.noreply.github.com> * Refactor tests to decouple from global Application state Commented out `driver ??= Application.Driver` assignments in `DriverAssert` to prevent automatic global driver assignment. Removed `Application.ResetState(true)` calls and commented out state validation assertions in `GlobalTestSetup` to reduce dependency on global state. Reintroduced `ApplicationForceDriverTests` and `ApplicationModelFencingTests` to validate `ForceDriver` behavior and ensure proper handling of legacy and modern Application models. Skipped certain `ToAnsiTests` that rely on `Application`. Removed direct `Application.Driver` assignments in `ViewDrawingClippingTests` and `ViewDrawingFlowTests`. Performed general cleanup of redundant code and unused imports to simplify the codebase. * WIP: Fixed Parallel tests; non-Parallel still broken Refactor application model usage tracking Refactored `ApplicationModelUsage` into a public enum in the new `Terminal.Gui.App` namespace, making it accessible across the codebase. Replaced the private `_modelUsage` field in `ApplicationImpl` with a public static `ModelUsage` property to improve clarity and accessibility. Renamed error message constants for consistency and updated methods like `SetInstance` and `MarkInstanceBasedModelUsed` to use the new `ModelUsage` property. Removed the private `ApplicationModelUsage` enum from `ApplicationImpl`. Updated test cases to use `ApplicationImpl.Instance` instead of `Application.Create` to enforce the legacy static model. Skipped obsolete tests in `ApplicationForceDriverTests` and added null checks in `DriverAssert` and `SelectorBase` to handle edge cases. Commented out an unused line in `WindowsOutput` and made general improvements to code readability, maintainability, and consistency. * WIP: Almost there! Refactored tests and code to align with the modern instance-based application model. Key changes include: - Disabled Sixel rendering in `OutputBase.cs` due to dependency on legacy static `Application` object. - Hardcoded `force16Colors` to `false` in `WindowsOutput.cs` with a `BUGBUG` note. - Updated `ApplicationImplTests` to use `ApplicationImpl.SetInstance` and return `ApplicationImpl.Instance`. - Refactored `ApplicationModelFencingTests` to use `Application.Create()` and added `ResetModelUsageTracking()` for model switching. - Removed legacy `DriverTests` and reintroduced updated versions with cross-platform driver tests. - Reverted `ArrangementTests` and `ShortcutTests` to use legacy static `ApplicationImpl.Instance`. - Reintroduced driver tests in `DriverTests.cs` with modern `Application.Create()` and added `TestTop` for driver content verification. - General cleanup, including removal of outdated code and addition of `BUGBUG` notes for temporary workarounds. * Fixed all modelusage bugs? Replaced static `Application` references with instance-based `App` context across the codebase. Updated calls to `Application.RequestStop()` and `Application.Screen` to use `App?.RequestStop()` and `App?.Screen` for better encapsulation and flexibility. Refactored test infrastructure to align with the new context, including reintroducing `FakeApplicationFactory` and `FakeApplicationLifecycle` for testing purposes. Improved logging, error handling, and test clarity by adding `logWriter` support and simplifying test setup. Removed redundant or obsolete code, such as `NetSequences` and the old `FakeApplicationFactory` implementation. Updated documentation to reflect the new `IApplication.RequestStop()` usage. * merged * Refactor KeyboardImpl and modernize MessageBoxTests Refactored the `KeyboardImpl` class to remove hardcoded default key values, replacing them with uninitialized fields for dynamic configuration. Updated key binding logic to use `ReplaceCommands` instead of `Add` for better handling of dynamic changes. Removed unnecessary `KeyBindings.Clear()` calls to avoid side effects. Rewrote `MessageBoxTests.cs` to improve readability, maintainability, and adherence to modern C# standards. Enabled nullable reference checks, updated the namespace, and restructured test methods for clarity. Marked non-functional tests with `[Theory(Skip)]` and improved test organization with parameterized inputs. Enhanced test assertions, lifecycle handling, and error handling across the test suite. Updated `UICatalog_AboutBox` to use multiline string literals for expected outputs. These changes improve the overall maintainability and flexibility of the codebase. * Atempt to fix windows only CI/CD Unit tests failure Refactor Application lifecycle and test cleanup Refactored the `Application` class to phase out legacy static properties `SessionStack` and `TopRunnable` from `Application.Current.cs`. These were reintroduced in a new file `Application.TopRunnable.cs` for better modularity, while retaining their `[Obsolete]` status. Updated `ApplicationPopoverTests.cs` to replace `Application.ResetState(true)` with `Application.Shutdown()` for consistent application state cleanup. Added explicit cleanup for `Application.TopRunnable` in relevant test cases to ensure proper resource management. Adjusted namespaces and `using` directives to support the new structure. These changes improve code organization and align with updated application lifecycle management practices. * Fixes #<Issue> - Dispose TopRunnable in cleanup logic Updated the `finally` block in `ApplicationPopoverTests` to dispose of the `Application.TopRunnable` object if it is not null, ensuring proper resource cleanup. Previously, the property was being set to `null` without disposal. The `Application.Shutdown()` call remains unchanged. * Improve thread safety, reduce static dependencies, and align the codebase with the updated `IApplication` interface. Refactored the `MainThreadId` property to improve encapsulation: - Updated `Application.MainThreadId` to use `ApplicationImpl.Instance` directly. - Added `MainThreadId` to `ApplicationImpl` and `IApplication`. - Removed redundant `MainThreadId` from `ApplicationImpl.Run.cs`. Updated `EnqueueMouseEvent` to include an `IApplication?` parameter: - Modified `FakeInputProcessor`, `InputProcessorImpl`, and `WindowsInputProcessor` to support the new parameter. - Updated `IInputProcessor` interface to reflect the new method signature. - Adjusted `GuiTestContext` and `EnqueueMouseEventTests` to pass `IApplication` where required. Improved test coverage and code maintainability: - Added test cases for negative positions and empty mouse events. - Commented out legacy code in `GraphView` and `FakeDriverBase`. - Enhanced readability in `EnqueueMouseEventTests`. These changes improve thread safety, reduce static dependencies, and align the codebase with the updated `IApplication` interface. * Fixed more bugs. Enabled nullable reference types across multiple files to improve code safety. Refactored and modularized test classes, improving readability and maintainability. Removed outdated test cases and added new tests for edge cases, including culture-specific and non-Gregorian calendar handling. Addressed timeout issues in `ScenarioTests` with a watchdog timer and improved error handling. Updated `ApplicationImplTests` to use instance fields instead of static references for better test isolation. Refactored `ScenarioTests` to dynamically load and test all UI Catalog scenarios, with macOS-specific skips for known issues. Aligned `MessageBox.Query` calls with updated API signatures. Performed general code cleanup, including removing unused directives, improving formatting, and consolidating repetitive logic into helper methods. * Made the `InputBindings<TEvent, TBinding>` class thread-safe by replacing the internal `Dictionary<TEvent, TBinding>` with `ConcurrentDictionary<TEvent, TBinding>`. This fixes parallel test failures where "Collection was modified; enumeration operation may not execute" exceptions were thrown. ## Changes Made ### 1. InputBindings.cs - **File**: `Terminal.Gui/Input/InputBindings.cs` - **Change**: Replaced `Dictionary` with `ConcurrentDictionary` - **Key modifications**: - Changed `_bindings` from `Dictionary<TEvent, TBinding>` to `ConcurrentDictionary<TEvent, TBinding>` - Updated `Add()` methods to use `TryAdd()` instead of checking with `TryGet()` then `Add()` - Updated `Remove()` to use `TryRemove()` (no need to check existence first) - Updated `ReplaceCommands()` to use `ContainsKey()` instead of `TryGet()` - Added `.ToList()` to `GetAllFromCommands()` to create a snapshot for safe enumeration - Added comment explaining that `ConcurrentDictionary` provides snapshot enumeration in `GetBindings()` - Added `.ToArray()` to `Clear(Command[])` to create snapshot before iteration ### 2. Thread Safety Test Suite - **File**: `Tests/UnitTestsParallelizable/Input/InputBindingsThreadSafetyTests.cs` - **New file** with comprehensive thread safety tests: - `Add_ConcurrentAccess_NoExceptions` - Tests concurrent additions - `GetBindings_DuringConcurrentModification_NoExceptions` - Tests enumeration during modifications - `TryGet_ConcurrentAccess_ReturnsConsistentResults` - Tests concurrent reads - `Clear_ConcurrentAccess_NoExceptions` - Tests concurrent clearing - `Remove_ConcurrentAccess_NoExceptions` - Tests concurrent removals - `Replace_ConcurrentAccess_NoExceptions` - Tests concurrent replacements - `GetAllFromCommands_DuringModification_NoExceptions` - Tests LINQ queries during modifications - `MixedOperations_ConcurrentAccess_NoExceptions` - Tests mixed operations (add/read/remove) - `KeyBindings_ConcurrentAccess_NoExceptions` - Tests actual `KeyBindings` class - `MouseBindings_ConcurrentAccess_NoExceptions` - Tests actual `MouseBindings` class ## Benefits of ConcurrentDictionary Approach 1. **Lock-Free Reads**: Most read operations don't require locks, improving performance 2. **Snapshot Enumeration**: Built-in support for safe enumeration during concurrent modifications 3. **Simplified Code**: No need for explicit `lock` statements or lock objects 4. **Better Scalability**: Multiple threads can read/write simultaneously 5. **No "Collection was modified" Exceptions**: Enumeration creates a snapshot ## Performance Characteristics - **Read Operations**: Lock-free, very fast - **Write Operations**: Uses fine-grained locking internally, minimal contention - **Memory Overhead**: Slightly higher than `Dictionary` but negligible in practice - **Enumeration**: Creates a snapshot, safe for concurrent modifications ## Test Results - **Original failing test now passes**: `ApplicationImplTests.Init_CreatesKeybindings` - **10 new thread safety tests**: All passing - **All 11,741 parallelizable tests**: All passing (11,731 passed, 10 skipped) - **All 1,779 non-parallelizable tests**: All passing (1,762 passed, 17 skipped) - **No compilation errors**: Clean build with no xUnit1031 warnings (suppressed with pragmas) ## Verification The original failure was: ``` System.InvalidOperationException: Collection was modified; enumeration operation may not execute. ``` This occurred in parallelizable tests when multiple threads accessed `KeyBindings.GetBindings()` simultaneously. The `ConcurrentDictionary` implementation resolves this by providing thread-safe operations and snapshot enumeration. ## Notes - The xUnit1031 warnings about using `Task.WaitAll` instead of `async/await` have been suppressed with `#pragma warning disable xUnit1031` directives, as these are intentional blocking operations in stress tests that test concurrent scenarios - All existing functionality is preserved; this is a drop-in replacement - No changes to public API surface - Existing tests continue to pass * Make InputBindings and KeyboardImpl thread-safe for concurrent access Replace Dictionary with ConcurrentDictionary in InputBindings<TEvent, TBinding> and KeyboardImpl to enable safe parallel test execution and multi-threaded usage. Changes: - InputBindings: Replace Dictionary with ConcurrentDictionary for _bindings - InputBindings: Make Replace() atomic using AddOrUpdate instead of Remove+Add - InputBindings: Make ReplaceCommands() atomic using AddOrUpdate - InputBindings: Add IsValid() check to both Add() overloads - InputBindings: Add defensive .ToList()/.ToArray() for safe LINQ enumeration - KeyboardImpl: Replace Dictionary with ConcurrentDictionary for _commandImplementations - KeyboardImpl: Change AddKeyBindings() to use ReplaceCommands for idempotent initialization - Add 10 comprehensive thread safety tests for InputBindings - Add 9 comprehensive thread safety tests for KeyboardImpl The ConcurrentDictionary implementation provides: - Lock-free reads for better performance under concurrent access - Atomic operations for Replace/ReplaceCommands preventing race conditions - Snapshot enumeration preventing "Collection was modified" exceptions - No breaking API changes - maintains backward compatibility All 11,750 parallelizable tests pass (11,740 passed, 10 skipped). Fixes race conditions that caused ApplicationImplTests.Init_CreatesKeybindings to fail intermittently during parallel test execution. * Decouple ApplicationImpl from Application static props Removed initialization of `Force16Colors` and `ForceDriver` from `Application` static properties in the `ApplicationImpl` constructor. The class still subscribes to the `Force16ColorsChanged` and `ForceDriverChanged` events, but no longer sets initial values for these properties. This change simplifies the constructor and reduces coupling between `ApplicationImpl` and `Application`. * Refactored keyboard initialization in `ApplicationImpl` to use `Application` static properties for default key assignments, ensuring synchronization with pre-`Init()` changes. Improved `KeyboardImpl` initialization to avoid premature `ApplicationImpl.Instance` access, enhancing testability. Standardized constant naming conventions and improved code readability in thread safety tests for `KeyboardImpl` and `InputBindings`. Updated `TestInputBindings` implementation for clarity and conciseness. Applied consistent code style improvements across files, including spacing, formatting, and variable naming, to enhance maintainability and readability. * Fix race conditions in parallel tests - thread-safe ApplicationImpl and KeyboardImpl Fixes intermittent failures in parallel tests caused by three separate race conditions: 1. **KeyboardImpl constructor race condition** - Constructor was accessing Application.QuitKey/ArrangeKey/etc which triggered ApplicationImpl.Instance getter, setting ModelUsage=LegacyStatic before Application.Create() was called - Changed constructor to initialize keys with hard-coded defaults instead - Added synchronization from Application static properties during Init() 2. **InputBindings.Replace() race condition** - Between GetOrAdd(oldEventArgs) and AddOrUpdate(newEventArgs), another thread could modify bindings, causing stale data to overwrite valid bindings - Added early return for same-key case (oldEventArgs == newEventArgs) - Kept atomic operations with proper updateValueFactory handling - Added detailed thread-safety documentation 3. **ApplicationImpl model usage fence checks race condition** - Two threads calling Init() simultaneously could both pass fence checks before either set ModelUsage, allowing improper model mixing - Added _modelUsageLock for thread-safe synchronization - Made all ModelUsage operations atomic (Instance getter, SetInstance, MarkInstanceBasedModelUsed, ResetModelUsageTracking, Init fence checks) **Files Changed:** - Terminal.Gui/App/ApplicationImpl.cs - Added _modelUsageLock, made all ModelUsage access thread-safe - Terminal.Gui/App/ApplicationImpl.Lifecycle.cs - Thread-safe fence checks in Init(), sync keyboard keys from Application properties - Terminal.Gui/App/Keyboard/KeyboardImpl.cs - Fixed constructor to not trigger ApplicationImpl.Instance - Terminal.Gui/Input/InputBindings.cs - Fixed Replace() race condition with proper atomic operations **Testing:** - All 11 ApplicationImplTests pass - All 9 KeyboardImplThreadSafetyTests pass - All 10 InputBindingsThreadSafetyTests pass - No more intermittent "Cannot use modern instance-based model after using legacy static Application model" errors in parallel test execution The root cause was KeyboardImpl constructor accessing Application static properties during object creation, which would lazily initialize ApplicationImpl.Instance and set the wrong ModelUsage before Application.Create() could mark it as InstanceBased. * Warning cleanup * docs: Add comprehensive MessageBox and Clipboard API documentation - Updated MessageBox class docs with nullable return value explanation - Created docfx/docs/messagebox-clipboard-changes-v2.md migration guide - Updated migratingfromv1.md with quick links to major changes - Created PR-SUMMARY.md documenting all changes - Added examples for both instance-based and legacy patterns - Documented application model fencing and thread safety improvements The documentation covers: • MessageBox nullable int? returns (null = cancelled) • Clipboard refactoring from static to instance-based • Application model usage fencing to prevent pattern mixing • Thread safety improvements in KeyboardImpl and InputBindings • Complete migration guide with code examples • Benefits and rationale for all changes * Refactor static properties to use backing fields Refactored static properties in multiple classes (`Button`, `CheckBox`, `Dialog`, `FrameView`, `MessageBox`, `StatusBar`, and `Window`) to use private backing fields for better encapsulation and configurability. Default values are now stored in private static fields, allowing overrides via configuration files (e.g., `Resources/config.json`). Updated property definitions to use `get`/`set` accessors interacting with the backing fields. Retained the `[ConfigurationProperty]` attribute to ensure runtime configurability. Removed redundant code, improved XML documentation, adjusted namespace declarations for consistency, and performed general code cleanup to enhance readability and maintainability. * Fix Windows-only parallel test failure by preventing ConfigurationManager from triggering ApplicationImpl.Instance Problem: `MessageBoxTests.Location_And_Size_Correct` was failing only on Windows in parallel tests with: System.InvalidOperationException: Cannot use modern instance-based model (Application.Create) after using legacy static Application model (Application.Init/ApplicationImpl.Instance). Root Cause (maybe): View classes (MessageBox, Dialog, Window, Button, CheckBox, FrameView, StatusBar) had `[ConfigurationProperty]` decorated auto-properties with inline initializers. When ConfigurationManager's module initializer scanned assemblies using reflection, accessing these auto-properties could trigger lazy initialization of other static members, which in some cases indirectly referenced `ApplicationImpl.Instance`, marking the model as "legacy" before parallel tests called `Application.Create()`. Solution: Converted all `[ConfigurationProperty]` auto-properties in View classes to use private backing fields with explicit getters/setters, matching the pattern used by `Application.QuitKey`. This prevents any code execution during reflection-based property discovery. Files Changed: - Terminal.Gui/Views/MessageBox.cs - 4 properties converted - Terminal.Gui/Views/Dialog.cs - 6 properties converted - Terminal.Gui/Views/Window.cs - 2 properties converted - Terminal.Gui/Views/Button.cs - 2 properties converted - Terminal.Gui/Views/CheckBox.cs - 1 property converted - Terminal.Gui/Views/FrameView.cs - 1 property converted - Terminal.Gui/Views/StatusBar.cs - 1 property converted Test Reorganization: - Moved `ConfigurationManagerTests.GetConfigPropertiesByScope_Gets` from UnitTestsParallelizable to UnitTests (defines custom ConfigurationProperty which affects global state) - Moved `SourcesManagerTests.Sources_StaysConsistentWhenUpdateFails` from UnitTestsParallelizable to UnitTests (modifies static ConfigurationManager.ThrowOnJsonErrors property) Best Practice: All `[ConfigurationProperty]` decorated static properties should use private backing fields to avoid triggering lazy initialization during ConfigurationManager's module initialization. Fixes: Windows-only parallel test failure in MessageBoxTests * Add thread-safety to CollectionNavigator classes - Add lock-based synchronization to CollectionNavigatorBase for _searchString and _lastKeystroke fields - Add lock-based synchronization to CollectionNavigator for Collection property access - Protect ElementAt and GetCollectionLength methods with locks - Add 6 comprehensive thread-safety tests covering: - Concurrent SearchString access - Concurrent Collection property access - Concurrent navigation operations (50 parallel tasks) - Concurrent collection modification with readers/writers - Concurrent search string changes - Stress test with 100 tasks × 1000 operations each All tests pass (31/31) including new thread-safety tests. The implementation uses lock-based synchronization rather than concurrent collections because: - IList interface is not thread-safe by design - CollectionNavigator is internal and used by UI components (ListView/TreeView) - Matches existing Terminal.Gui patterns (Scope<T>, ConfigProperty) - Provides simpler and more predictable behavior Fixes thread-safety issues when CollectionNavigator is accessed from multiple threads. * cleanup * Run parallel unit tests 10 times with varying parallelization to expose concurrency issues Co-authored-by: tig <585482+tig@users.noreply.github.com> * Fix parallel unit tests workflow - use proper xUnit parallelization parameters Co-authored-by: tig <585482+tig@users.noreply.github.com> * Fix environment variable reference in workflow - use proper bash syntax Co-authored-by: tig <585482+tig@users.noreply.github.com> * Run parallel tests 10 times sequentially instead of matrix expansion Co-authored-by: tig <585482+tig@users.noreply.github.com> * Make ConfigurationManager thread-safe - use ConcurrentDictionary and add locks Co-authored-by: tig <585482+tig@users.noreply.github.com> * Add Debug.Fail to detect legacy Application usage in parallelizable tests Co-authored-by: tig <585482+tig@users.noreply.github.com> * Move ScrollSliderTests to UnitTests project - they access legacy Application model Co-authored-by: tig <585482+tig@users.noreply.github.com> * Revert ScrollSliderTests move and document root cause analysis Co-authored-by: tig <585482+tig@users.noreply.github.com> * Remove Debug.Fail and move ScrollSliderTests to UnitTests project Co-authored-by: tig <585482+tig@users.noreply.github.com> * Re-add Debug.Fail to detect legacy Application usage in parallelizable tests Co-authored-by: tig <585482+tig@users.noreply.github.com> * Refactor tests and improve parallelization support Commented out `Debug.Fail` statements in `Application.Lifecycle.cs` and `ApplicationImpl.cs` to prevent interruptions during parallel tests. Refactored `ToString` in `ApplicationImpl.cs` to use an expression-bodied member and removed unused imports. Rewrote tests in `ClipRegionTests.cs` and `ScrollSliderTests.cs` to remove global state dependencies and migrated them to the `UnitTests_Parallelizable` namespace. Enabled nullable annotations and updated assertions for clarity and modern patterns. Improved test coverage by adding scenarios for clamping, layout, and size calculations. Updated `README.md` to include `[SetupFakeApplication]` in the list of patterns that block parallelization and clarified migration guidelines. Replaced `[SetupFakeDriver]` with `[SetupFakeApplication]` in examples. Added `<Folder Include="Drivers\" />` to `UnitTests.csproj` for better organization. Adjusted test project references to reflect test migration. Enhanced test output validation in `ScrollSliderTests.cs`. Removed redundant test cases and improved documentation to align with modern C# practices and ensure maintainability. * marked as a "TODO" for potential future configurability. --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: tig <585482+tig@users.noreply.github.com> Co-authored-by: Tig <tig@users.noreply.github.com> |
||
|
|
d53fcd7485 | Fixes #4374 - Nukes all (?) legacy Driver and Application stuff; revamps tests (#4376) | ||
|
|
5984a3c564 |
Fixes #3941 - v2win/v2net: UICatalog crash - Fixes warnings (#3946)
* Tons of API doc updates * Adjust timeout * Code cleanuyp * Disabled All_Scenarios_Benchmark * Removed logs * Fixed a bunch of warnings * Fixed a bunch of warnings2 * Disabled All_Scenarios_Benchmark again...just to make sure * Enabled All_Scenarios_Benchmark again...It is not the culprit |
||
|
|
b0f32811eb |
Fixes #3930 - Splits tests to Tests/UnitTests, Tests/IntegrationTests, Tests/StressTests (#3954)
* Tons of API doc updates * Removed stale test * Removed stale tests * Fixed Skipped Shadow test 1 * Fixed Skipped Shadow test 2 * Fixed Skipped Shadow test 3 * Removed stale test * Removed stale test2 * Explicit unregister of event handler on Application.Driver!.ClearedContents * Added Toplevels to dict * code cleanup * spelling error * Removed stale test3 * Removed stale test4 * Removed stale test5 * added script * tweaked script * tweaked script * Created StressTests project; moved some tests * Created IntegrationTests project; moved some tests * New yml * made old yml just unit tests * Tweaked Button_IsDefault_Raises_Accepted_Correctly * tweaked script * cleaned up ymls * tweakled up ymls * stress tests... * stress tests on ubuntu only * Fixed WindowsDriver in InvokeLeakTest * Fixed WindowsDriver in InvokeLeakTest2 * Added Directory.Packages.props. Added Directory.Build.props * Shortened StressTest time * Removed dupe file. * DemoFiles * Moved all tests to ./Tests dir. * Fixed release build issue * Fixed .sln file * Fixed .sl* files * Fixing ymls * Fixing interation tests * Create link to the file TestHelpers. * Created Tests/UnitTestsParallelizable. Moved all obviously parallelizable tests. Updated yml. * fixing logs * fixing logs2 * fixing logs3 * don't require stress to pass for PRs * Fix a failure? * tweaked script * Coudl this be it? * Moved tons of tests to parallelizable * Fixed some stuff * Script to find duplicate tests * Testing workflows * Updated to v4 * Fix RelativeBasePath issue * Replace powershell to pwsh * Add ignore projects. * Removed dupe unit tests * Code cleanup of tests * Cleaned up test warnings * yml tweak * Moved setter * tweak ymls * just randomly throwing spaghetti at a wall * Enable runing 5 test runners in par * Turned off DEBUG_DISPOSABLE for par tests * RunningUnitTests=true * code cleanup (forcing more Action runs) * DISABLE_DEBUG_IDISPOSABLE * Added View.DebugIDisposable. False by default. * Remobed bogus tareet * Remobed bogus tareet2 * fixed warning * added api doc * fixed warning * fixed warning * fixed warning2 * fixed warning3 * fixed warning4 --------- Co-authored-by: BDisp <bd.bdisp@gmail.com> |
||
|
|
79cd4e92b7 |
Adds Logging level control to UICatalog (#3938)
* Tons of API doc updates * Added logging control to UICatalog * Added logging control to UICatalog - more * fixed minor issues * removed logs from .gitignore * Fixed log file path * Fixed app desc |
||
|
|
8f1954f16c | Fixes #3790. Can't build v2_develop RELEASE - "The local source 'C:\Users\Tig\s\gui-cs\Terminal.Gui\local_packages' doesn't exist." (#3794) | ||
|
|
9c6a3058d4 |
Fixes #3784. SelfContained and NativeAot projects should use the local package in the release mode. (#3785)
* Fixes #3784. SelfContained and NativeAot projects should use the local package in the release mode. * Run dotnet restore before build. * Using local_packages folder for CI. * Add build_release_consumer. * Remove build_release_consumer. * Fix folder for CI. * Fix System.Text.Json vulnerability. * Fix local_packageslocation. * Add package sources to the packageSourceMapping tag. * Using the original configuration. * Only add the Terminal.Gui pattern in the LocalPackages. * Fix the path folder separator with unit style. * Using pack instead of build. * Create LocalPackages Directory * Add local_packages source. * Using scripts to build release for NativeAot and SelfContained. * Trying to fix path. * Again. * Fix the path for the package, * Need to build before pack. * Needs also build before pack locally. * Fix build path. |
||
|
|
47d3762ee2 | Fixed .gitignore | ||
|
|
49da66ab4f |
Added some stuff to gitignore to cover other common configurations
The ReSharper additions, especially. If you keep caches local to the solution, that's a big one. |
||
|
|
ab5848902a | new docfx! | ||
|
|
0df485a890 |
Fixes #666. Refactor ConsoleDrivers to simplify and remove duplicated code (#2612)
* Added ClipRegion; cleaned up driver code * clip region unit tests * api docs * Moved color stuff from ConsoleDriver to Color.cs * Removes unused ConsoleDriver APIs * Code cleanup and Removes unused ConsoleDriver APIs * Code cleanup and Removes unused ConsoleDriver APIs * Work around https://github.com/gui-cs/Terminal.Gui/issues/2610 * adjusted unit tests * initial commit * Made Rows, Cols, Top, Left virtual * Made Clipboard non-virtual * Made EnableConsoleScrolling non-virtual * Made Contents non-virtual * Pulled Row/Col up * Made MoveTo virtual; fixed stupid FakeDriver cursor issue * Made CurrentAttribute non-virtual * Made SetAttribute non-virtual * Moved clipboard code out * Code cleanup * Removes dependecy on NStack from ConsoleDrivers - WIP * Fixed unit tests * Fixed unit tests * Added list of unit tests needed * Did some perf testing; tweaked code and charmap to address * Brough in code from PR #2264 (but commented) * Tons of code cleanup * Fighting with ScrollView * Fixing bugs * Fixed TabView tests * Fixed View.Visible test that was not really working * Fixed unit tests * Cleaned up clipboard APIs in attempt to track down unit test failure * Add Cut_Preserves_Selection test * Removed invalid code * Removed invalid test code; unit tests now pass * EscSeq* - Adjusted naming, added more sequences, made code more consistent, simplified, etc... * Added CSI_SetGraphicsRendition * NetDriver code cleanup * code cleanup * Cleaned up color handling in NetDriver * refixed tabview unit test * WindowsDriver color code cleanup * WindowsDriver color code cleanup * CursesDriver color code cleanup * CursesDriver - Adding _BOLD has no effect. Further up the stack we cast the return of ColorToCursesColor from int to short and the _BOLD values don't fit in a short. * CursesDriver color code - make code more accurate * CursesDriver color code - make code more accurate * Simplified ConsoleDriver.GetColors API * Simplified ConsoleDriver.GetColors API further * Improved encapslation of Attribute; prep for TrueColor & other attributes like blink * Fixes #2249. CharacterMap isn't refreshing well non-BMP code points on scroll. * Use GetRange to take some of the runes before convert to string. * Attempting to fix unit tests not being cleaned up * Fixes #2658 - ConsoleDriver.IsRuneSupported * Fixes #2658 - ConsoleDriver.IsRuneSupported (for WindowsDriver) * Check all the range values and not only the max value. * Reducing code. * Fixes #2674 - Unit test process doesn't exit * Changed Cell to support IsDirty and list of Runes * add support for rendering TrueColor output on Windows merging veeman & tznind code * add colorconverter changes * fixed merged v2_develop * Fixing merge bugs * Fixed merge bugs * Fixed merge bugs - all unit tests pass * Debugging netdriver * More netdriver diag * API docs for escutils * Update unicode scenario to stress more stuff * Contents: Now a 2D array of Cells; WIP * AddRune and ClearContents no longer virtual/abstract * WindowsDriver renders correctly again * Progress on Curses * Progress on Curses * broke windowsdriver * Cleaned up FakeMainLoop * Cleaned up some build warnings * Removed _init from AutoInitShutdown as it's not needed anymore * Removed unused var * Removed unused var * Fixed nullabiltiy warning in LineCanvas * Fixed charmap crash * Fixes #2758 in v2 * Port testonfail fix to v2 * Remove EnableConsoleScrolling * Backport #2764 from develop (clear last line) * Remove uneeded usings * Progress on unicode * Merged in changes from PR #2786, Fixes #2784 * revamp charmap rendering * Charmap option to show glyph widths * Fixed issue with wide glpyhs being overwritten * Fixed charmap startcodepoint change issue * Added abiltiy to see ncurses verison/lib * Fought with CursesDriver; giving up for now. See notes. * Leverage Wcwidth nuget library instaed of our own tables * enhanced charmap Details dialog * Final attempt at fixing curses --------- Co-authored-by: BDisp <bd.bdisp@gmail.com> Co-authored-by: adstep <stephensonadamj@gmail.com> |
||
|
|
9425b2a720 | Fixes #2181 - (Really) Adds configuration manager (#2365) | ||
|
|
2ab68cc38b | Removed docs folder | ||
|
|
cc04bb37f5 |
Release v1.6.0 (#1722)
* Change log for Release v1.6.0 * Regenerated API docs for v1.6.0 * Merged #1724 * Relnotes update * Fixed minor issues in readme * Updated changelog * New sample.gif for README.md * Ignore demo artifacts |
||
|
|
b29240f362 |
Code coverage (#1235)
* tweaked version # for v1.0.0-beta.10 * tweaked version # for v1.0.0-beta.11 * Updated readme and revision history for 1.0 * excluding test results * Added support for viewing code coverage results with Fine Code Coverage * add generating CC to CI/CD * refactored unit test namespaces * more refactoring. commented out failing test. * Removed UnitTests and UICatalog from code coverage reporting * made Application and test more deterministic * disabled Multi_Thread_Toplevels because it is currently broken and don't understand why * updated threading test per @bdisp * testing cc badge stuff * another test * using coverlet.settings * trying copy * trying cp. duh. * trying mv. * wrong path * print * chaging badge output for testing * yaml error * fixed code coverage * moved dimtests to core |
||
|
|
cb4091108d | removed deb file | ||
|
|
dd92a07fb0 | updated readmes; bumped nuget version | ||
|
|
06687962cd | ignore vscode files | ||
|
|
fddfcf8802 |
Charlie's Mondo Patch (#600)
This PR includes: #586 - Fixed Clipping #587 - LayoutComplete #591 - Sys Console Scenario #590 - Significantly improves MessageBox, Dialog, Frame drawning and more See the PRs above for all the details. Here are the issues this closes: Closes #299 - MessageBox now auto sizes Closes #557 - MessageBoxes on small screens Closes #432 - MessageBox does not deal with long text; width/height params are goofy Closes #521 - MessageBox should take ustrings (BREAKING CHANGE) Closes #35 - Dialog should have 1 char padding around edges Closes #570 - Dialog should use computed layout for buttons Closes #470 - UI Catalog: Add Dialogs Scenario Closes #569 - LayoutComplete event Plus probably more. |
||
|
|
20d4ed6cb6 | delete dotfx build files | ||
|
|
8a6c2a9fc1 |
Mouse events menu (#401)
* Fixes an issue in the sln file that despite not having been changed, git reports as changed. * Adding some settings for crlf and user specific. * Prevent button clicked event if the point of the pressed and released don't match. Also decreases the delay for the triple click. * Changes the menu button clicked event to button pressed to improve mouse clicks. * Removed the action that was running all the time after the first running. |
||
|
|
49cd29853f |
All my pull-request at once (#345)
* Fixed key events traversal for modal dialogs The key must be propagated initially to the first chain element before evaluating if we should stop because of the handled or the Modal condition. Otherwise the modal dialog won't get any process key notification. This fixes |
||
|
|
303508b4f3 | Fix demo | ||
|
|
eef6ccb452 | Ignore | ||
|
|
a0175bd531 | Update | ||
|
|
01739e7df9 | Clerical stuff | ||
|
|
28afe26ba2 | First commit |