Files
Terminal.Gui/Tests/UnitTests/Application/ApplicationPopoverTests.cs
Copilot e199063a31 Introduce IRunnable interface architecture with Fluent API (Phase 1) (#4405)
* Initial plan

* Add IRunnable interface, Runnable base class, and RunnableSessionToken

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Add comprehensive parallelizable unit tests for IRunnable

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Add 41 more unit tests for comprehensive IRunnable coverage

- Added ApplicationRunnableIntegrationTests with 29 integration tests covering Begin/End/Run lifecycle
- Added RunnableEdgeCasesTests with 24 edge case and error condition tests
- Tests cover event propagation, cancellation scenarios, nested runnables, result handling
- Fixed App property not being set in Begin() method
- Total test count increased from 23 to 64 tests for IRunnable functionality

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Fix parallel test failures in CI/CD

- Fixed IsModal property to check RunnableSessionStack instead of just TopRunnable
- Added "fake" driver parameter to Application.Init() in integration tests
- Fixed Begin() to capture old IsModal value before pushing to stack
- Moved App property assignment before stack operations to ensure proper state
- Skipped 2 tests that use Run() with main loop (not suitable for parallel tests)
- All 11,654 parallelizable tests now pass (4 skipped)

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Refactor Application with IRunnable and session management

Modernized `Application` and `ApplicationImpl` by introducing `IRunnable` and `RunnableSessionToken` for improved session management. Deprecated legacy methods and added `Obsolete` attributes to indicate their removal. Simplified method bodies using expression-bodied members and null-coalescing assignments.

Enhanced lifecycle management in `ApplicationImpl` by removing redundant code and improving `SessionStack` iteration. Introduced `IToplevelTransitionManager` to handle top-level state changes.

Updated `Runnable<TResult>` to implement `IRunnable<TResult>` with lifecycle event handling for `IsRunning` and `IsModal` states. Improved result management during lifecycle transitions.

Removed legacy classes like `SessionToken` and consolidated their functionality into the new constructs. Updated and expanded the test suite to cover `IRunnable` lifecycle events, `RunnableSessionToken` behavior, and integration with `Application`.

Performed code cleanup, improved readability, and updated documentation with detailed remarks and examples. Added new unit tests for edge cases and lifecycle behavior.

* Implement fluent API for Init/Run/Shutdown with automatic disposal

- Changed Init() to return IApplication for fluent chaining
- Changed Run<TRunnable>() to return IApplication (breaking change from TRunnable)
- Changed Shutdown() to return object? (extracts and returns result from last Run<T>())
- Added FrameworkOwnedRunnable property to track runnable created by Run<T>()
- Shutdown() automatically disposes framework-owned runnables
- Created FluentExample demonstrating: Application.Create().Init().Run<ColorPickerView>().Shutdown()
- Disposal semantics: framework creates → framework disposes; caller creates → caller disposes

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* New Example: Demonstrates new Fluent API using ColorPicker

Conditional compilation (`#if POST_4148`) to support both a new Fluent API and a traditional approach for running `ColorPickerView`. The Fluent API simplifies the application lifecycle with method chaining and automatic disposal, while the traditional approach retains explicit lifecycle management.

Refactor `ColorPickerView` to support both approaches:
- Add an `instructions` label for user guidance.
- Replace `_okButton` and `_cancelButton` with local `Button` instances.
- Use a new `ColorPicker` with enhanced styling options.

Add a warning log for WIP issue (#4148) in `ApplicationImpl.Run.cs` to highlight limitations with non-`Toplevel` views as runnables.

Update `Terminal.sln` to include the new `FluentExample` project with appropriate build configurations.

Improve code readability with verbatim string literals and better alignment/indentation.

* Introduce `RunnableWrapper` for making any View runnable

Added the `RunnableWrapper<TView, TResult>` pattern to enable any
`View` to be run as a blocking session with typed results, without
requiring inheritance from `Runnable<TResult>` or implementation
of `IRunnable<TResult>`.

- Added `RunnableWrapperExample` project to demonstrate usage.
- Introduced `ApplicationRunnableExtensions` and `ViewRunnableExtensions`
  for clean, type-safe APIs to run views with or without result extraction.
- Updated `CodeSharingStrategy.md` to document reduced duplication
  using `#if POST_4148` directives.
- Added `RunnableWrapper.md` with detailed documentation and examples.
- Created runnable examples in `Program.cs` showcasing various use cases.
- Improved maintainability by reducing code duplication by 86% and
  increasing shared code by 264%.
- Gated all new functionality behind the `POST_4148` feature flag
  for backward compatibility.

* Simplified `#if POST_4148` usage to reduce duplication and improve clarity. Refactored `RunnableWrapper` to use a parameterless constructor with `required` properties, ensuring type safety and better lifecycle management. Updated `AllViewsView` with new commands, improved generic handling, and enhanced logging.

Refactored `ApplicationRunnableExtensions` and `ViewRunnableExtensions` for cleaner initialization and event handling. Enhanced `TestsAllViews` to handle required properties and constraints dynamically. Updated documentation to reflect new designs and provide clearer examples.

Improved overall code readability, consistency, and maintainability while leveraging modern C# features.

* Update docfx documentation for IRunnable architecture

- Updated View.md with comprehensive IRunnable section
  - Interface-based architecture explanation
  - Fluent API patterns and examples
  - Disposal semantics ("whoever creates it, owns it")
  - Result extraction patterns
  - Lifecycle properties and CWP-compliant events
  - Marked legacy Modal Views section for clarity

- Updated application.md with IRunnable deep dive
  - Key features and benefits
  - Fluent API patterns with method chaining
  - Disposal semantics table
  - Creating runnable views with examples
  - Lifecycle properties and events
  - RunnableSessionStack management
  - Updated IApplication interface documentation

- Updated runnable-architecture-proposal.md
  - Marked Phase 1 as COMPLETE 
  - Updated status to "Phase 1 Complete - Phase 2 In Progress"
  - Documented all implemented features
  - Added bonus features (fluent API, automatic disposal)
  - Included migration examples

All documentation is now clear, concise, and complete relative to Phase 1 implementation.

Co-authored-by: tig <585482+tig@users.noreply.github.com>

---------

Co-authored-by: Tig <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>
2025-11-21 16:01:16 -07:00

363 lines
8.6 KiB
C#

#nullable enable
namespace UnitTests.ApplicationTests;
public class ApplicationPopoverTests
{
[Fact]
public void Application_Init_Initializes_PopoverManager ()
{
try
{
// Arrange
Application.Init ("fake");
// Act
Assert.NotNull (Application.Popover);
}
finally
{
Application.ResetState (true);
}
}
[Fact]
public void Application_Shutdown_Resets_PopoverManager ()
{
try
{
// Arrange
Application.Init ("fake");
// Act
Assert.NotNull (Application.Popover);
Application.Shutdown ();
// Test
}
finally
{
Application.ResetState (true);
}
}
[Fact]
public void Application_End_Does_Not_Reset_PopoverManager ()
{
Toplevel? top = null;
try
{
// Arrange
Application.Init ("fake");
Assert.NotNull (Application.Popover);
Application.StopAfterFirstIteration = true;
top = new ();
SessionToken rs = Application.Begin (top);
// Act
Application.End (rs);
// Test
Assert.NotNull (Application.Popover);
}
finally
{
top?.Dispose ();
Application.ResetState (true);
}
}
[Fact]
public void Application_End_Hides_Active ()
{
Toplevel? top = null;
try
{
// Arrange
Application.Init ("fake");
Application.StopAfterFirstIteration = true;
top = new ();
SessionToken rs = Application.Begin (top);
PopoverTestClass? popover = new ();
Application.Popover?.Register (popover);
Application.Popover?.Show (popover);
Assert.True (popover.Visible);
// Act
Application.End (rs);
// Test
Assert.False (popover.Visible);
Assert.NotNull (Application.Popover);
popover.Dispose ();
Assert.Equal (1, popover.DisposedCount);
}
finally
{
top?.Dispose ();
Application.ResetState (true);
}
}
[Fact]
public void Application_Shutdown_Disposes_Registered_Popovers ()
{
try
{
// Arrange
Application.Init ("fake");
PopoverTestClass? popover = new ();
// Act
Application.Popover?.Register (popover);
Application.Shutdown ();
// Test
Assert.Equal (1, popover.DisposedCount);
}
finally
{
Application.ResetState (true);
}
}
[Fact]
public void Application_Shutdown_Does_Not_Dispose_DeRegistered_Popovers ()
{
try
{
// Arrange
Application.Init ("fake");
PopoverTestClass? popover = new ();
Application.Popover?.Register (popover);
// Act
Application.Popover?.DeRegister (popover);
Application.Shutdown ();
// Test
Assert.Equal (0, popover.DisposedCount);
popover.Dispose ();
Assert.Equal (1, popover.DisposedCount);
}
finally
{
Application.ResetState (true);
}
}
[Fact]
public void Application_Shutdown_Does_Not_Dispose_ActiveNotRegistered_Popover ()
{
try
{
// Arrange
Application.Init ("fake");
PopoverTestClass? popover = new ();
Application.Popover?.Register (popover);
Application.Popover?.Show (popover);
Application.Popover?.DeRegister (popover);
// Act
Application.Shutdown ();
// Test
Assert.Equal (0, popover.DisposedCount);
popover.Dispose ();
Assert.Equal (1, popover.DisposedCount);
}
finally
{
Application.ResetState (true);
}
}
[Fact]
public void Register_SetsTopLevel ()
{
try
{
// Arrange
Application.Init ("fake");
Application.TopRunnable = new ();
PopoverTestClass? popover = new ();
// Act
Application.Popover?.Register (popover);
// Assert
Assert.Equal (Application.TopRunnable, popover.Current);
}
finally
{
Application.ResetState (true);
}
}
[Fact]
public void Keyboard_Events_Go_Only_To_Popover_Associated_With_Toplevel ()
{
try
{
// Arrange
Application.Init ("fake");
Application.TopRunnable = new () { Id = "initialTop" };
PopoverTestClass? popover = new ();
var keyDownEvents = 0;
popover.KeyDown += (s, e) =>
{
keyDownEvents++;
e.Handled = true;
}; // Ensure it handles the key
Application.Popover?.Register (popover);
// Act
Application.RaiseKeyDownEvent (Key.A); // Goes to initialTop
Application.TopRunnable = new () { Id = "secondaryTop" };
Application.RaiseKeyDownEvent (Key.A); // Goes to secondaryTop
// Test
Assert.Equal (1, keyDownEvents);
popover.Dispose ();
Assert.Equal (1, popover.DisposedCount);
}
finally
{
Application.ResetState (true);
}
}
// See: https://github.com/gui-cs/Terminal.Gui/issues/4122
[Theory]
[InlineData (0, 0, new [] { "top" })]
[InlineData (10, 10, new string [] { })]
[InlineData (1, 1, new [] { "top", "view" })]
[InlineData (5, 5, new [] { "top" })]
[InlineData (6, 6, new [] { "popoverSubView" })]
[InlineData (7, 7, new [] { "top" })]
[InlineData (3, 3, new [] { "top" })]
public void GetViewsUnderMouse_Supports_ActivePopover (int mouseX, int mouseY, string [] viewIdStrings)
{
PopoverTestClass? popover = null;
try
{
// Arrange
Application.Init ("fake");
Application.TopRunnable = new ()
{
Frame = new (0, 0, 10, 10),
Id = "top"
};
View? view = new ()
{
Id = "view",
X = 1,
Y = 1,
Width = 2,
Height = 2
};
Application.TopRunnable.Add (view);
popover = new ()
{
Id = "popover",
X = 5,
Y = 5,
Width = 3,
Height = 3
}; // at 5,5 to 8,8 (screen)
View? popoverSubView = new ()
{
Id = "popoverSubView",
X = 1,
Y = 1,
Width = 1,
Height = 1
};
popover.Add (popoverSubView);
Application.Popover?.Register (popover);
Application.Popover?.Show (popover);
List<View?> found = view.GetViewsUnderLocation (new (mouseX, mouseY), ViewportSettingsFlags.TransparentMouse);
string [] foundIds = found.Select (v => v!.Id).ToArray ();
Assert.Equal (viewIdStrings, foundIds);
}
finally
{
popover?.Dispose ();
Application.TopRunnable?.Dispose ();
Application.ResetState (true);
}
}
public class PopoverTestClass : PopoverBaseImpl
{
public List<Key> HandledKeys { get; } = [];
public int NewCommandInvokeCount { get; private set; }
// NOTE: Hides the base DisposedCount property
public new int DisposedCount { get; private set; }
public PopoverTestClass ()
{
CanFocus = true;
AddCommand (Command.New, NewCommandHandler!);
HotKeyBindings.Add (Key.N.WithCtrl, Command.New);
return;
bool? NewCommandHandler (ICommandContext ctx)
{
NewCommandInvokeCount++;
return false;
}
}
protected override bool OnKeyDown (Key key)
{
HandledKeys.Add (key);
return false;
}
/// <inheritdoc/>
protected override void Dispose (bool disposing)
{
base.Dispose (disposing);
DisposedCount++;
}
}
}