mirror of
https://github.com/gui-cs/Terminal.Gui.git
synced 2025-12-26 15:57:56 +01:00
* WIP: Broken
* Got working. Mostly.
* Parllel tests pass
* More progres
* Fixed app tests.
* Mouse
* more progress.
* working on shortcut
* Shortcut accept on ENTER is broken.
* One left...
* More test progress.
* All unit tests pass. Still some issues though.
* tweak
* Fixed Integration Tests
* Fixed UI Catalog
* Tweaking CP to try to find race condition
* Refactor StandardColors and improve ColorPicker logic
Refactored `StandardColors` to use lazy initialization for static fields, improving performance and avoiding static constructor convoy effects. Introduced `NamesValueFactory` and `MapValueFactory` methods for encapsulated initialization logic.
Simplified `GetColorNames` to directly return `_names.Value`. Improved `TryParseColor` by clarifying default value usage and adopting object initializer syntax. Updated `TryNameColor` to use `_argbNameMap.Value`.
Refactored `GetArgb` for better readability. Replaced `MultiStandardColorNameResolver` with `StandardColorsNameResolver` in `ColorPicker`. Commented out `app.Init("Fake")` in `ColorPickerTests` for testing purposes.
Made minor formatting improvements, including updated comments and XML documentation for consistency.
* revert
* Throttle input loop to prevent CPU spinning
Introduce a 20ms delay in the input loop of `InputImpl<TInputRecord>`
to prevent excessive CPU usage when no input is available. Removed
the `DateTime dt = Now();` line and the `while (Peek())` block, which
previously enqueued input records.
This change improves resource management, especially in scenarios
where multiple `ApplicationImpl` instances are created in parallel
tests without calling `Shutdown()`. It prevents thread pool
exhaustion and ensures better performance in such cases.
* Refactor ApplicationImpl to use IDisposable pattern
Implemented the IDisposable pattern in ApplicationImpl to improve resource management. Added `Dispose` and `DisposeCore` methods, and marked the `Shutdown` method as obsolete, encouraging the use of `Dispose` or `using` statements instead. Updated the `IApplication` interface to inherit from IDisposable and added `GetResult` methods for retrieving run session results.
Refactored unit tests to adopt the new lifecycle management approach, replacing legacy `Shutdown` calls with `Dispose` or `using`. Removed fragile and obsolete tests, and re-enabled previously skipped tests after addressing underlying issues.
Updated `FakeApplicationLifecycle` and `SetupFakeApplicationAttribute` to align with the new disposal pattern. Improved documentation and examples to guide users toward modern usage patterns. Maintained backward compatibility for legacy singleton usage.
* Add IDisposable pattern with input loop throttling
- Add IDisposable to IApplication for proper resource cleanup
- Add 20ms throttle to input loop (prevents CPU spinning)
- Add Lazy<T> to StandardColors (eliminates convoy effect)
- Add MainLoopCoordinatorTests suite (5 new tests)
- Add Dispose() calls to all 16 ColorPickerTests
- Mark Application.Shutdown() as [Obsolete]
IApplication now requires Dispose() for cleanup
Performance: 100x CPU reduction, 15x faster disposal, tests complete in <5s
Fixes: Thread leaks, CPU saturation, test hangs in parallel execution
Docs: Updated application.md and newinv2.md with disposal patterns
* Refactor test for input loop throttling clarity
Updated `InputLoop_Throttle_Limits_Poll_Rate` test to improve clarity, reliability, and efficiency:
- Rewrote summary comment to clarify purpose and emphasize the 20ms throttle's role in preventing CPU spinning.
- Replaced `var` with explicit types for better readability.
- Reduced test duration from 1s to 500ms to improve test speed.
- Revised assertions:
- Replaced range-based assertion with upper-bound check to ensure poll count is below 500, avoiding timing sensitivity issues.
- Added assertion to verify the thread ran and was not immediately canceled.
- Added a 2-second timeout to `inputTask.Wait` and verified task completion.
- Improved comments to explain test behavior and reasoning behind changes.
* tweaks
* Fix nullabiltiy stuff.
* runnable fixes
* more nullabe
* More nullability
* warnings gone
* Fixed fluent test failure.
* Refactor ApplicationImpl and update Runnable layout logic
Refactored `ApplicationImpl.Run.cs` for improved readability and
atomicity:
- Combined `if (wasModal)` with `SessionStack?.TryPop` to streamline
logic.
- Simplified restoration of `previousRunnable` by reducing nesting.
- Updated comments for clarity and retained `SetIsModal` call.
Simplified focus-setting logic in `ApplicationImpl.Run.cs` using
pattern matching for `TopRunnableView`.
In `Runnable<TResult>`, added `SetNeedsLayout` after `IsModalChanged`
to ensure layout updates. Removed an unused empty line for cleanup.
Corrected namespace in `GetViewsUnderLocationForRootTests.cs` to
align with test structure.
* Update layout on modal state change
A call to `SetNeedsLayout()` was added to the `OnIsModalChanged`
method in the `Runnable` class. This ensures that the layout
is updated whenever the modal state changes.
* Increase test timeout for inputTask.Wait to 10 seconds
Extended the timeout duration for the `inputTask.Wait` method
from 4 seconds to 10 seconds in `MainLoopCoordinatorTests`.
This change ensures the test has a longer window to complete
under conditions of increased load or slower execution
environments, reducing the likelihood of false test failures.
* Refactor project files and simplify test logic
Removed `<LangVersion>` and `<ImplicitUsings>` properties from
`UnitTests.csproj` and `UnitTests.Parallelizable.csproj` to rely
on default SDK settings and disable implicit global usings.
Simplified the `SizeChanged_Event_Still_Fires_For_Compatibility`
test in `FakeDriverTests` by removing the `screenChangedFired`
variable, its associated event handler, and related assertions.
Also removed obsolete warning suppression directives as they
are no longer needed.
* Reduce UnitTestsParallelizable iterations from 10 to 3
Reduced the number of iterations for the UnitTestsParallelizable
test suite from 10 to 3 to save time and resources while still
exposing concurrency issues. Updated the loop and log messages
to reflect the new iteration count.
* disabled InputLoop_Throttle_Limits_Poll_Rate
* Refactor app lifecycle and improve Runnable API
Refactored `Program.cs` to simplify application lifecycle:
- Modularized app creation, initialization, and disposal.
- Improved result handling and ensured proper resource cleanup.
Re-implemented `Runnable<TResult>` with a cleaner design:
- Retained functionality while improving readability and structure.
- Added XML documentation and followed the Cancellable Work Pattern.
Re-implemented `RunnableWrapper<TView, TResult>`:
- Enabled wrapping any `View` to make it runnable with typed results.
- Added examples and remarks for better developer guidance.
Re-implemented `ViewRunnableExtensions`:
- Provided fluent API for making views runnable with or without results.
- Enhanced documentation with examples for common use cases.
General improvements:
- Enhanced code readability, maintainability, and error handling.
- Replaced redundant code with cleaner, more maintainable versions.
* Modernize codebase for Terminal.Gui and MVVM updates
Refactored `LoginView` to remove redundant `Application.LayoutAndDraw()`
call. Enhanced `LoginViewModel` with new observable properties for
automatic property change notifications. Updated `Message` class to use
nullable generics for improved type safety.
Replaced legacy `Application.Init()` and `Application.Run()` calls with
the modern `IApplication` API across `Program.cs`, `Example.cs`, and
`ReactiveExample`. Ensured proper disposal of `IApplication` instances
to prevent resource leaks.
Updated `TerminalScheduler` to integrate with `IApplication` for
invoking actions and managing timeouts. Added null checks and improved
timeout disposal logic for robustness.
Refactored `ExampleWindow` for better readability and alignment with
modern `Terminal.Gui` conventions. Cleaned up unused imports and
improved code clarity across the codebase.
Updated README.md to reflect the latest `Terminal.Gui` practices,
including examples of the `IApplication` API and automatic UI refresh
handling. Renamed `LoginAction` to `LoginActions` for consistency.
* Refactor: Transition to IRunnable-based architecture
Replaced `Toplevel` with `Window` as the primary top-level UI element. Introduced the `IRunnable` interface to modernize the architecture, enabling greater flexibility and testability. Deprecated the static `Application` class in favor of the instance-based `IApplication` model, which supports multiple application contexts.
Updated methods like `Application.Run()` and `Application.RequestStop()` to use `IRunnable`. Removed or replaced legacy `Modal` properties with `IsModal`. Enhanced the `IApplication` interface with a fluent API, including methods like `Run<TRunnable>()` and `GetResult<T>()`.
Refactored tests and examples to align with the new architecture. Updated documentation to reflect the instance-based model. Deprecated obsolete members and methods, including `Application.Current` and `Application.TopRunnable`.
Improved event handling by replacing the `Accept` event with `Accepting` and using `e.Handled` for event processing. Updated threading examples to use `App?.Invoke()` or `app.Invoke()` for UI updates. Cleaned up redundant code and redefined modal behavior for better consistency.
These changes modernize the `Terminal.Gui` library, improving clarity, usability, and maintainability while ensuring backward compatibility where possible.
* Refactor: Replace Toplevel with Runnable class
This commit introduces a major architectural update to the `Terminal.Gui` library, replacing the legacy `Toplevel` class with the new `Runnable` class. The changes span the entire codebase, including core functionality, tests, documentation, and configuration files.
- **Core Class Replacement**:
- Replaced `Toplevel` with `Runnable` as the base class for modal views and session management.
- Updated all references to `Toplevel` in the codebase, including constructors, methods, and properties.
- **Configuration Updates**:
- Updated `tui-config-schema.json` to reflect the new `Runnable` scheme.
- **New Classes**:
- Added `UICatalogRunnable` for managing the UI Catalog application.
- Introduced `Runnable<TResult>` as a generic base class for blocking sessions with result handling.
- **Documentation and Tests**:
- Updated documentation to emphasize `Runnable` and mark `Toplevel` as obsolete.
- Refactored test cases to use `Runnable` and ensure compatibility.
- **Behavioral Improvements**:
- Enhanced lifecycle management and alignment with the `IRunnable` interface.
- Improved clarity and consistency in naming conventions.
These changes modernize the library, improve flexibility, and provide a clearer architecture for developers.
* Refactor: Consolidate Runnable classes and decouple View from ApplicationImpl
- Made Runnable<TResult> inherit from Runnable (eliminating ~180 LOC duplication)
- Moved View init/layout/cursor logic from ApplicationImpl to Runnable lifecycle events
- ApplicationImpl.Begin now operates purely on IRunnable interface
Related to #4419
* Simplified the disposal logic in `ApplicationImpl.Run.cs` by replacing
the type-specific check for `View` with a more general check for
`IDisposable`. This ensures proper disposal of any `IDisposable`
object, improving robustness.
Removed the `FrameworkOwnedRunnable` property from the `ApplicationImpl`
class in `ApplicationImpl.cs` and the `IApplication` interface in
`IApplication.cs`. This eliminates the need to manage this property,
reducing complexity and improving maintainability.
Updated `application.md` to reflect the removal of the
`FrameworkOwnedRunnable` property, ensuring the documentation aligns
with the updated codebase.
* Replaces the legacy `Shutdown()` method with `Dispose()` to align
with the `IDisposable` pattern, ensuring proper resource cleanup
and simplifying the API. The `Dispose()` method is now the
recommended way to release resources, with `using` statements
encouraged for automatic disposal.
Key changes:
- Marked `Shutdown()` as obsolete; it now internally calls `Dispose()`.
- Updated the fluent API to remove `Shutdown()` from chaining.
- Enhanced session lifecycle management for thread safety.
- Updated tests to validate proper disposal and state reset.
- Improved `IRunnable` integration with automatic disposal for
framework-created runnables.
- Maintained backward compatibility for the legacy static
`Application` singleton.
- Refactored documentation and examples to reflect modern practices
and emphasize `Dispose()` usage.
These changes modernize the `Terminal.Gui` lifecycle, improve
testability, and encourage alignment with .NET conventions.
* Refactor runnable app context handling in ApplicationImpl
Refactor how the application context is set for `runnable` objects
by introducing a new `SetApp` method in the `IRunnable` interface.
This replaces the previous logic of directly setting the `App`
property for `View` objects, making the process more generic and
encapsulated within `IRunnable` implementations.
Simplify `Mouse.UngrabMouse()` by removing the conditional check
and calling it unconditionally.
Make a minor formatting adjustment in the generic constraint of
`Run<TRunnable>` in `ApplicationImpl`.
Add `SetApp(IApplication app)` to the `IRunnable` interface and
implement it in the `Runnable` class to set the `App` property
to the provided application instance.
* Improve docs, tests, and modularity across the codebase
Reorganized and updated `CONTRIBUTING.md`:
- Added **Key Architecture Concepts** section and reordered the table of contents.
- Updated testing requirements to discourage legacy patterns.
- Added instructions for replicating CI workflows locally.
- Clarified PR guidelines and coding style expectations.
Enhanced `README.md` with detailed CI/CD workflow documentation.
Refactored `ColorPicker.Prompt` to use `IApplication` for improved modularity and testability.
Introduced `IApplicationScreenChangedTests` for comprehensive testing of `ScreenChanged` events and `Screen` property.
Refactored `ApplicationScreenTests` and `TextView.PromptForColors` to align with modern patterns.
Updated `Terminal.sln` to include `.github/workflows/README.md`.
Performed general cleanup:
- Removed outdated documentation links.
- Improved XML documentation and coding consistency.
* readme tweaks
* Improve thread safety, layout, and test coverage
Refactored `OutputBufferImpl.cs` to enhance thread safety by locking shared resources and adding bounds checks for columns and rows. Improved handling of wide characters and removed outdated TODO comments.
Updated `Runnable.cs` to call `SetNeedsDraw()` on modal state changes, ensuring proper layout and drawing updates. Simplified layout handling in `ApplicationImpl.Run.cs` by replacing redundant comments with a `LayoutAndDraw()` call.
Added a check in `AllViewsTester.cs` to skip creating instances of `RunnableWrapper` types with unsatisfiable generic constraints, logging a warning when encountered.
Enhanced `ListViewTests.cs` by adding explicit `app.LayoutAndDraw()` calls to validate visual output and ensure tests reflect the updated application state.
These changes improve robustness, prevent race conditions, and ensure consistent behavior across the application.
* Refactor: Rename Toplevel to Runnable and update logic
Updated the `Border` class to use `Command.Quit` instead of
`Command.QuitToplevel` in the `CloseButton.Accept` handler.
Renamed test methods in `GetViewsAtLocationTests.cs` to replace
"Toplevel" with "Runnable" for consistency. Updated `Runnable<bool>`
instances to use "topRunnable" as the `Id` property.
These changes align the codebase with updated naming conventions
and improve clarity.
* Removed `ToplevelTests` and migrated relevant test cases to
`MouseDragTests` with improved structure and coverage. Updated
tests to use `Application.Create`, `app.Begin`, and `app.End`
for better resource management and lifecycle handling.
Replaced direct event handling with `app.Mouse.RaiseMouseEvent`
to align with the application's event-handling mechanism. Added
`Runnable` objects to ensure views are properly initialized and
disposed of within the application context.
Enhanced tests to include assertions for minimum width and
height constraints during resize operations. Removed redundant
tests and streamlined logic to reduce duplication and improve
maintainability.
* Reorged Unit Test namespaces.
* more
* Refactor tests and update namespaces for consistency
Updated namespaces in `ArrangementTests.cs` and `MouseDragTests.cs` for better organization. Enhanced `ArrangementTests.cs` with additional checks for arrangement flags. Reformatted and re-added `MouseDragTests.cs` and `SchemeTests.cs` with modern C# features like nullable annotations and object initializers. Ensured no functional changes while improving code clarity and consistency.
* Fix nullability warnings in MouseDragTests.cs
Updated `app.End` calls to use the null-forgiving operator (`!`)
on `app.SessionStack` to ensure it is treated as non-null.
This change addresses potential nullability warnings and
improves code safety and clarity. Applied consistently across
all relevant test cases in the `MouseDragTests` class.
1089 lines
38 KiB
C#
1089 lines
38 KiB
C#
using System.Diagnostics;
|
|
|
|
|
|
namespace Terminal.Gui.ViewBase;
|
|
|
|
public partial class View // Focus and cross-view navigation management (TabStop, TabIndex, etc...)
|
|
{
|
|
private bool _canFocus;
|
|
|
|
/// <summary>
|
|
/// Advances the focus to the next or previous view in the focus chain, based on
|
|
/// <paramref name="direction"/>.
|
|
/// itself.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// If there is no next/previous view to advance to, the focus is set to the view itself.
|
|
/// </para>
|
|
/// <para>
|
|
/// See the View Navigation Deep Dive for more information:
|
|
/// <see href="https://gui-cs.github.io/Terminal.Gui/docs/navigation.html"/>
|
|
/// </para>
|
|
/// </remarks>
|
|
/// <param name="direction"></param>
|
|
/// <param name="behavior"></param>
|
|
/// <returns>
|
|
/// <see langword="true"/> if focus was changed to another subview (or stayed on this one), <see langword="false"/>
|
|
/// otherwise.
|
|
/// </returns>
|
|
public bool AdvanceFocus (NavigationDirection direction, TabBehavior? behavior)
|
|
{
|
|
//Logging.Trace ($"{Id} - {direction} {behavior}");
|
|
if (!CanBeVisible (this)) // TODO: is this check needed?
|
|
{
|
|
return false;
|
|
}
|
|
|
|
if (RaiseAdvancingFocus (direction, behavior))
|
|
{
|
|
return true;
|
|
}
|
|
|
|
View? focused = Focused;
|
|
|
|
if (focused is { } && focused.AdvanceFocus (direction, behavior))
|
|
{
|
|
return true;
|
|
}
|
|
|
|
// AdvanceFocus did not advance - do we wrap, or move up to the superview?
|
|
|
|
View [] focusChain = GetFocusChain (direction, behavior);
|
|
|
|
if (focusChain.Length == 0)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
// Special case TabGroup
|
|
if (behavior == TabBehavior.TabGroup)
|
|
{
|
|
if (direction == NavigationDirection.Forward && focused == focusChain [^1] && SuperView is null)
|
|
{
|
|
// We're at the top of the focus chain. Go back down the focus chain and focus the first TabGroup
|
|
if (AdvanceFocusChain ())
|
|
{
|
|
return true;
|
|
}
|
|
}
|
|
|
|
if (direction == NavigationDirection.Backward && focused == focusChain [0] && SuperView is null)
|
|
{
|
|
// We're at the bottom of the focus chain
|
|
if (AdvanceFocusChain ())
|
|
{
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
|
|
int focusedIndex = focusChain.IndexOf (Focused); // Will return -1 if Focused can't be found or is null
|
|
var next = 0; // Assume we wrap to start of the focus chain
|
|
|
|
if (focusedIndex < focusChain.Length - 1)
|
|
{
|
|
// We're moving w/in the subviews
|
|
next = focusedIndex + 1;
|
|
}
|
|
else
|
|
{
|
|
// Determine if focus should remain in this focus chain, or move to the superview's focus chain
|
|
if (SuperView is { })
|
|
{
|
|
// If we are TabStop, and we have at least one other focusable peer, move to the SuperView's chain
|
|
if (TabStop == TabBehavior.TabStop && SuperView is { } && ShouldBubbleUpForWrapping (SuperView, direction, behavior))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
// TabGroup is special-cased.
|
|
if (focused?.TabStop == TabBehavior.TabGroup)
|
|
{
|
|
if (SuperView?.GetFocusChain (direction, TabBehavior.TabGroup)?.Length > 0)
|
|
{
|
|
// Our superview has a TabGroup subview; signal we couldn't move so we nav out to it
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
View view = focusChain [next];
|
|
|
|
if (view.HasFocus)
|
|
{
|
|
// We could not advance
|
|
if (view != this)
|
|
{
|
|
// Tell it to try the other way.
|
|
return view.RaiseAdvancingFocus (
|
|
direction == NavigationDirection.Forward ? NavigationDirection.Backward : NavigationDirection.Forward,
|
|
behavior);
|
|
}
|
|
|
|
return view == this;
|
|
}
|
|
|
|
// The subview does not have focus, but at least one other that can. Can this one be focused?
|
|
(bool focusSet, bool _) = view.SetHasFocusTrue (Focused);
|
|
|
|
return focusSet;
|
|
|
|
bool AdvanceFocusChain ()
|
|
{
|
|
if (focusChain.Length > 0)
|
|
{
|
|
// Get the index of the currently focused view
|
|
int focusedTabGroupIndex = focusChain.IndexOf (Focused); // Will return -1 if Focused can't be found or is null
|
|
|
|
if (focusedTabGroupIndex + 1 > focusChain.Length - 1)
|
|
{
|
|
focusedTabGroupIndex = 0;
|
|
}
|
|
else
|
|
{
|
|
focusedTabGroupIndex++;
|
|
}
|
|
|
|
View [] subViews = focusChain [focusedTabGroupIndex].GetFocusChain (NavigationDirection.Forward, TabBehavior.TabStop);
|
|
|
|
if (subViews.Length > 0)
|
|
{
|
|
if (focusChain [focusedTabGroupIndex]._previouslyFocused is { }
|
|
&& subViews.Any (v => v == focusChain [focusedTabGroupIndex]._previouslyFocused))
|
|
{
|
|
if (focusChain [focusedTabGroupIndex]._previouslyFocused!.SetFocus ())
|
|
{
|
|
return true;
|
|
}
|
|
}
|
|
|
|
// We have a subview that can be focused
|
|
if (subViews [0].SetFocus ())
|
|
{
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Determines if focus should bubble up to a SuperView when wrapping would occur.
|
|
/// Iteratively checks up the SuperView hierarchy to see if there are any focusable peers at any level.
|
|
/// </summary>
|
|
/// <param name="view">The SuperView to check.</param>
|
|
/// <param name="direction">The navigation direction.</param>
|
|
/// <param name="behavior">The tab behavior to filter by.</param>
|
|
/// <returns>
|
|
/// <see langword="true"/> if there are focusable peers at this level or any ancestor level,
|
|
/// <see langword="false"/> otherwise.
|
|
/// </returns>
|
|
private bool ShouldBubbleUpForWrapping (View? view, NavigationDirection direction, TabBehavior? behavior)
|
|
{
|
|
View? currentView = view;
|
|
|
|
while (currentView is { })
|
|
{
|
|
// If this parent has multiple focusable children, we should bubble up
|
|
View [] chain = currentView.GetFocusChain (direction, behavior);
|
|
|
|
if (chain.Length > 1)
|
|
{
|
|
return true;
|
|
}
|
|
|
|
// If parent has only 1 child but parent is also TabStop with a SuperView, continue checking up the hierarchy
|
|
if (currentView.TabStop == TabBehavior.TabStop && currentView.SuperView is { })
|
|
{
|
|
currentView = currentView.SuperView;
|
|
}
|
|
else
|
|
{
|
|
break;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
private bool RaiseAdvancingFocus (NavigationDirection direction, TabBehavior? behavior)
|
|
{
|
|
// Call the virtual method
|
|
if (OnAdvancingFocus (direction, behavior))
|
|
{
|
|
// The event was cancelled
|
|
return true;
|
|
}
|
|
|
|
var args = new AdvanceFocusEventArgs (direction, behavior);
|
|
AdvancingFocus?.Invoke (this, args);
|
|
|
|
if (args.Cancel)
|
|
{
|
|
// The event was cancelled
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Called when <see cref="View.AdvanceFocus"/> is about to advance focus.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// If a view cancels the event and the focus could not otherwise advance, the Navigation direction will be
|
|
/// reversed and the event will be raised again.
|
|
/// </para>
|
|
/// </remarks>
|
|
/// <returns>
|
|
/// <see langword="true"/>, if the focus advance is to be cancelled, <see langword="false"/>
|
|
/// otherwise.
|
|
/// </returns>
|
|
protected virtual bool OnAdvancingFocus (NavigationDirection direction, TabBehavior? behavior) { return false; }
|
|
|
|
/// <summary>
|
|
/// Raised when <see cref="View.AdvanceFocus"/> is about to advance focus.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// Cancel the event to prevent the focus from advancing.
|
|
/// </para>
|
|
/// <para>
|
|
/// If a view cancels the event and the focus could not otherwise advance, the Navigation direction will be
|
|
/// reversed and the event will be raised again.
|
|
/// </para>
|
|
/// </remarks>
|
|
public event EventHandler<AdvanceFocusEventArgs>? AdvancingFocus;
|
|
|
|
/// <summary>Gets or sets a value indicating whether this <see cref="View"/> can be focused.</summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// See the View Navigation Deep Dive for more information:
|
|
/// <see href="https://gui-cs.github.io/Terminal.Gui/docs/navigation.html"/>
|
|
/// </para>
|
|
/// <para>
|
|
/// <see cref="SuperView"/> must also have <see cref="CanFocus"/> set to <see langword="true"/>.
|
|
/// </para>
|
|
/// <para>
|
|
/// When set to <see langword="false"/>, if an attempt is made to make this view focused, the focus will be set to
|
|
/// the next focusable view.
|
|
/// </para>
|
|
/// <para>
|
|
/// When set to <see langword="false"/>, the value of <see cref="CanFocus"/> for all
|
|
/// subviews will be cached so that when <see cref="CanFocus"/> is set back to <see langword="true"/>, the subviews
|
|
/// will be restored to their previous values.
|
|
/// </para>
|
|
/// <para>
|
|
/// Changing this property to <see langword="true"/> will cause <see cref="TabStop"/> to be set to
|
|
/// <see cref="TabBehavior.TabStop"/>" as a convenience. Changing this property to
|
|
/// <see langword="false"/> will have no effect on <see cref="TabStop"/>.
|
|
/// </para>
|
|
/// </remarks>
|
|
public bool CanFocus
|
|
{
|
|
get => _canFocus;
|
|
set
|
|
{
|
|
if (_canFocus == value)
|
|
{
|
|
return;
|
|
}
|
|
|
|
_canFocus = value;
|
|
|
|
if (TabStop is null && _canFocus)
|
|
{
|
|
TabStop = TabBehavior.TabStop;
|
|
}
|
|
|
|
if (!_canFocus && HasFocus)
|
|
{
|
|
// If CanFocus is set to false and this view has focus, make it leave focus
|
|
// Set transversing down so we don't go back up the hierarchy...
|
|
SetHasFocusFalse (null);
|
|
}
|
|
|
|
if (_canFocus && !HasFocus && Visible && SuperView is { Focused: null })
|
|
{
|
|
// If CanFocus is set to true and this view does not have focus, make it enter focus
|
|
SetFocus ();
|
|
}
|
|
|
|
OnCanFocusChanged ();
|
|
}
|
|
}
|
|
|
|
/// <summary>Raised when <see cref="CanFocus"/> has been changed.</summary>
|
|
/// <remarks>
|
|
/// Raised by the <see cref="OnCanFocusChanged"/> virtual method.
|
|
/// </remarks>
|
|
public event EventHandler? CanFocusChanged;
|
|
|
|
/// <summary>
|
|
/// Focuses the deepest focusable SubView if one exists. If there are no focusable SubViews then the focus is set to
|
|
/// the view itself.
|
|
/// </summary>
|
|
/// <param name="direction"></param>
|
|
/// <param name="behavior"></param>
|
|
/// <returns><see langword="true"/> if a subview other than this was focused.</returns>
|
|
public bool FocusDeepest (NavigationDirection direction, TabBehavior? behavior)
|
|
{
|
|
View? deepest = FindDeepestFocusableView (direction, behavior);
|
|
|
|
if (deepest is { })
|
|
{
|
|
return deepest.SetFocus ();
|
|
}
|
|
|
|
return SetFocus ();
|
|
}
|
|
|
|
/// <summary>Gets the currently focused SubView or Adornment of this view, or <see langword="null"/> if nothing is focused.</summary>
|
|
public View? Focused
|
|
{
|
|
get
|
|
{
|
|
View? focused = SubViews.FirstOrDefault (v => v.HasFocus);
|
|
|
|
if (focused is { })
|
|
{
|
|
return focused;
|
|
}
|
|
|
|
// How about in Adornments?
|
|
if (Margin is { HasFocus: true })
|
|
{
|
|
return Margin;
|
|
}
|
|
|
|
if (Border is { HasFocus: true })
|
|
{
|
|
return Border;
|
|
}
|
|
|
|
if (Padding is { HasFocus: true })
|
|
{
|
|
return Padding;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
}
|
|
|
|
internal void RaiseFocusedChanged (View? previousFocused, View? focused)
|
|
{
|
|
//Logging.Trace($"RaiseFocusedChanged: {focused.Title}");
|
|
OnFocusedChanged (previousFocused, focused);
|
|
FocusedChanged?.Invoke (this, new (true, true, previousFocused, focused));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Called when the focused view has changed.
|
|
/// </summary>
|
|
/// <param name="previousFocused"></param>
|
|
/// <param name="focused"></param>
|
|
protected virtual void OnFocusedChanged (View? previousFocused, View? focused) { }
|
|
|
|
/// <summary>
|
|
/// Raised when the focused view has changed.
|
|
/// </summary>
|
|
public event EventHandler<HasFocusEventArgs>? FocusedChanged;
|
|
|
|
/// <summary>Returns a value indicating if this View is currently on Top (Active)</summary>
|
|
public bool IsCurrentTop => App?.TopRunnableView == this;
|
|
|
|
/// <summary>
|
|
/// Returns the most focused SubView down the subview-hierarchy.
|
|
/// </summary>
|
|
/// <value>The most focused SubView, or <see langword="null"/> if no SubView is focused.</value>
|
|
public View? MostFocused
|
|
{
|
|
get
|
|
{
|
|
// TODO: Remove this API. It's duplicative of Application.Navigation.GetFocused.
|
|
if (Focused is null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
View? most = Focused.MostFocused;
|
|
|
|
if (most is { })
|
|
{
|
|
return most;
|
|
}
|
|
|
|
return Focused;
|
|
}
|
|
}
|
|
|
|
/// <summary>Invoked when the <see cref="CanFocus"/> property from a view is changed.</summary>
|
|
/// <remarks>
|
|
/// Raises the <see cref="CanFocusChanged"/> event.
|
|
/// </remarks>
|
|
public virtual void OnCanFocusChanged () { CanFocusChanged?.Invoke (this, EventArgs.Empty); }
|
|
|
|
/// <summary>
|
|
/// INTERNAL API to restore focus to the subview that had focus before this view lost focus.
|
|
/// </summary>
|
|
/// <returns>
|
|
/// Returns true if focus was restored to a subview, false otherwise.
|
|
/// </returns>
|
|
internal bool RestoreFocus ()
|
|
{
|
|
// Ignore TabStop
|
|
View [] indicies = GetFocusChain (NavigationDirection.Forward, null);
|
|
|
|
if (Focused is null && _previouslyFocused is { } && indicies.Contains (_previouslyFocused))
|
|
{
|
|
if (_previouslyFocused.SetFocus ())
|
|
{
|
|
return true;
|
|
}
|
|
|
|
_previouslyFocused = null;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Clears any focus state (e.g. the previously focused subview) from this view.
|
|
/// </summary>
|
|
public void ClearFocus () { _previouslyFocused = null; }
|
|
|
|
private View? FindDeepestFocusableView (NavigationDirection direction, TabBehavior? behavior)
|
|
{
|
|
View [] indicies = GetFocusChain (direction, behavior);
|
|
|
|
foreach (View v in indicies)
|
|
{
|
|
return v.FindDeepestFocusableView (direction, behavior);
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
#region HasFocus
|
|
|
|
// Backs `HasFocus` and is the ultimate source of truth whether a View has focus or not.
|
|
private bool _hasFocus;
|
|
|
|
/// <summary>
|
|
/// Gets or sets whether this view has focus.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// See the View Navigation Deep Dive for more information:
|
|
/// <see href="https://gui-cs.github.io/Terminal.Gui/docs/navigation.html"/>
|
|
/// </para>
|
|
/// <para>
|
|
/// Only Views that are visible, enabled, and have <see cref="CanFocus"/> set to <see langword="true"/> are
|
|
/// focusable. If
|
|
/// these conditions are not met when this property is set to <see langword="true"/> <see cref="HasFocus"/> will
|
|
/// not change.
|
|
/// </para>
|
|
/// <para>
|
|
/// Setting this property causes the <see cref="OnHasFocusChanging"/> and <see cref="OnHasFocusChanged"/> virtual
|
|
/// methods (and <see cref="HasFocusChanging"/> and
|
|
/// <see cref="HasFocusChanged"/> events to be raised). If the event is cancelled, <see cref="HasFocus"/> will not
|
|
/// be changed.
|
|
/// </para>
|
|
/// <para>
|
|
/// Setting this property to <see langword="true"/> will recursively set <see cref="HasFocus"/> to
|
|
/// <see langword="true"/> for all SuperViews up the hierarchy.
|
|
/// </para>
|
|
/// <para>
|
|
/// Setting this property to <see langword="true"/> will cause the subview furthest down the hierarchy that is
|
|
/// focusable to also gain focus (as long as <see cref="TabStop"/>
|
|
/// </para>
|
|
/// <para>
|
|
/// Setting this property to <see langword="false"/> will cause <see cref="AdvanceFocus"/> to set
|
|
/// the focus on the next view to be focused.
|
|
/// </para>
|
|
/// </remarks>
|
|
public bool HasFocus
|
|
{
|
|
set
|
|
{
|
|
if (HasFocus == value)
|
|
{
|
|
return;
|
|
}
|
|
|
|
if (value)
|
|
{
|
|
// NOTE: If Application.Navigation is null, we pass null to FocusChanging. For unit tests.
|
|
(bool focusSet, bool _) = SetHasFocusTrue (App?.Navigation?.GetFocused ());
|
|
|
|
if (focusSet)
|
|
{
|
|
// The change happened
|
|
// HasFocus is now true
|
|
}
|
|
}
|
|
else
|
|
{
|
|
SetHasFocusFalse (null);
|
|
|
|
Debug.Assert (!_hasFocus);
|
|
|
|
if (_hasFocus)
|
|
{
|
|
// force it.
|
|
_hasFocus = false;
|
|
}
|
|
}
|
|
}
|
|
get => _hasFocus;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Causes this view to be focused. Calling this method has the same effect as setting <see cref="HasFocus"/> to
|
|
/// <see langword="true"/> but with the added benefit of returning a value indicating whether the focus was set.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// See the View Navigation Deep Dive for more information:
|
|
/// <see href="https://gui-cs.github.io/Terminal.Gui/docs/navigation.html"/>
|
|
/// </para>
|
|
/// </remarks>
|
|
/// <returns><see langword="true"/> if the focus changed; <see langword="true"/> false otherwise.</returns>
|
|
public bool SetFocus ()
|
|
{
|
|
(bool focusSet, bool _) = SetHasFocusTrue (App?.Navigation?.GetFocused ());
|
|
|
|
return focusSet;
|
|
}
|
|
|
|
/// <summary>
|
|
/// A cache of the subview that was focused when this view last lost focus. This is used by <see cref="RestoreFocus"/>.
|
|
/// </summary>
|
|
private View? _previouslyFocused;
|
|
|
|
/// <summary>
|
|
/// INTERNAL: Called when focus is going to change to this view. This method is called by <see cref="SetFocus"/> and
|
|
/// other methods that
|
|
/// set or remove focus from a view.
|
|
/// </summary>
|
|
/// <param name="currentFocusedView">
|
|
/// The currently focused view. If <see langword="null"/> there is no previously focused
|
|
/// view.
|
|
/// </param>
|
|
/// <param name="traversingUp"></param>
|
|
/// <returns><see langword="true"/> if <see cref="HasFocus"/> was changed to <see langword="true"/>.</returns>
|
|
/// <exception cref="InvalidOperationException"></exception>
|
|
private (bool focusSet, bool cancelled) SetHasFocusTrue (View? currentFocusedView, bool traversingUp = false)
|
|
{
|
|
Debug.Assert (SuperView is null || IsInHierarchy (SuperView, this));
|
|
|
|
//Logging.Trace ($"{Id} - {currentFocusedView?.Id} -> {Id}");
|
|
|
|
// Pre-conditions
|
|
if (_hasFocus)
|
|
{
|
|
//// See https://github.com/gui-cs/Terminal.Gui/pull/4013#issuecomment-2823934197
|
|
//if (Application.Navigation is { } && (Application.Navigation.GetFocused () == this || Application.Navigation.GetFocused () == MostFocused))
|
|
//{
|
|
// throw new InvalidOperationException (@"Do not SetFocus on a view that is already MostFocused.");
|
|
//}
|
|
|
|
return (false, false);
|
|
}
|
|
|
|
if (currentFocusedView is { HasFocus: false })
|
|
{
|
|
throw new ArgumentException ("SetHasFocusTrue: currentFocusedView must HasFocus.");
|
|
}
|
|
|
|
var thisAsAdornment = this as Adornment;
|
|
View? superViewOrParent = thisAsAdornment?.Parent ?? SuperView;
|
|
|
|
if (CanFocus && superViewOrParent is { CanFocus: false })
|
|
{
|
|
Logging.Warning ($@"Attempt to FocusChanging where SuperView.CanFocus == false. {this}");
|
|
|
|
return (false, false);
|
|
}
|
|
|
|
if (!CanBeVisible (this) || !Enabled)
|
|
{
|
|
return (false, false);
|
|
}
|
|
|
|
if (!CanFocus)
|
|
{
|
|
return (false, false);
|
|
}
|
|
|
|
bool previousValue = HasFocus;
|
|
|
|
bool cancelled = RaiseFocusChanging (false, true, currentFocusedView, this);
|
|
|
|
if (cancelled)
|
|
{
|
|
return (false, true);
|
|
}
|
|
|
|
// Make sure superviews up the superview hierarchy have focus.
|
|
// Any of them may cancel gaining focus. In which case we need to back out.
|
|
if (superViewOrParent is { HasFocus: false } sv)
|
|
{
|
|
(bool focusSet, bool svCancelled) = sv.SetHasFocusTrue (currentFocusedView, true);
|
|
|
|
if (!focusSet)
|
|
{
|
|
return (false, svCancelled);
|
|
}
|
|
}
|
|
|
|
if (_hasFocus)
|
|
{
|
|
// Something else beat us to the change (likely a FocusChanged handler).
|
|
return (true, false);
|
|
}
|
|
|
|
// By setting _hasFocus to true we definitively change HasFocus for this view.
|
|
|
|
// Get whatever peer has focus, if any
|
|
View? focusedPeer = superViewOrParent?.Focused;
|
|
|
|
_hasFocus = true;
|
|
|
|
// Ensure that the peer loses focus
|
|
focusedPeer?.SetHasFocusFalse (this, true);
|
|
|
|
if (!traversingUp)
|
|
{
|
|
// Restore focus to the previously focused subview, if any
|
|
if (!RestoreFocus ())
|
|
{
|
|
// Couldn't restore focus, so use Advance to navigate to the next focusable subview, if any
|
|
AdvanceFocus (NavigationDirection.Forward, null);
|
|
}
|
|
}
|
|
|
|
// Now make sure the old focused view loses focus
|
|
if (currentFocusedView is { HasFocus: true } && GetFocusChain (NavigationDirection.Forward, TabStop).Contains (currentFocusedView))
|
|
{
|
|
currentFocusedView.SetHasFocusFalse (this);
|
|
}
|
|
|
|
if (_previouslyFocused is { })
|
|
{
|
|
_previouslyFocused = null;
|
|
}
|
|
|
|
if (Arrangement.HasFlag (ViewArrangement.Overlapped))
|
|
{
|
|
SuperView?.MoveSubViewToEnd (this);
|
|
}
|
|
|
|
// Focus work is done. Notify.
|
|
RaiseFocusChanged (HasFocus, currentFocusedView, this);
|
|
|
|
SetNeedsDraw ();
|
|
|
|
// Post-conditions - prove correctness
|
|
if (HasFocus == previousValue)
|
|
{
|
|
throw new InvalidOperationException ("NotifyFocusChanging was not cancelled and the HasFocus value did not change.");
|
|
}
|
|
|
|
return (true, false);
|
|
}
|
|
|
|
// TODO: CWP: FocusChanging should use an event arg type derived from ResultEventArgs<bool> so that its more obvious
|
|
// TODO: the result can be changed.
|
|
private bool RaiseFocusChanging (bool currentHasFocus, bool newHasFocus, View? currentFocused, View? newFocused)
|
|
{
|
|
Debug.Assert (currentFocused is null || currentFocused is { HasFocus: true });
|
|
Debug.Assert (newFocused is null || newFocused is { CanFocus: true });
|
|
|
|
// Call the virtual method
|
|
if (OnHasFocusChanging (currentHasFocus, newHasFocus, currentFocused, newFocused))
|
|
{
|
|
// The event was cancelled
|
|
return true;
|
|
}
|
|
|
|
var args = new HasFocusEventArgs (currentHasFocus, newHasFocus, currentFocused, newFocused);
|
|
HasFocusChanging?.Invoke (this, args);
|
|
|
|
if (args.Cancel)
|
|
{
|
|
// The event was cancelled
|
|
return true;
|
|
}
|
|
|
|
View? appFocused = App?.Navigation?.GetFocused ();
|
|
|
|
if (appFocused == currentFocused)
|
|
{
|
|
if (newFocused is { HasFocus: true })
|
|
{
|
|
App?.Navigation?.SetFocused (newFocused);
|
|
}
|
|
else
|
|
{
|
|
App?.Navigation?.SetFocused (null);
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Invoked when <see cref="View.HasFocus"/> is about to change. This method is called before the
|
|
/// <see cref="HasFocusChanging"/> event is raised.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// Use <see cref="OnHasFocusChanged"/> to be notified after the focus has changed.
|
|
/// </para>
|
|
/// </remarks>
|
|
/// <param name="currentHasFocus">The current value of <see cref="View.HasFocus"/>.</param>
|
|
/// <param name="newHasFocus">The value <see cref="View.HasFocus"/> will have if the focus change happens.</param>
|
|
/// <param name="currentFocused">The view that is currently Focused. May be <see langword="null"/>.</param>
|
|
/// <param name="newFocused">The view that will be focused. May be <see langword="null"/>.</param>
|
|
/// <returns>
|
|
/// <see langword="true"/>, if the change to <see cref="View.HasFocus"/> is to be cancelled, <see langword="false"/>
|
|
/// otherwise.
|
|
/// </returns>
|
|
protected virtual bool OnHasFocusChanging (bool currentHasFocus, bool newHasFocus, View? currentFocused, View? newFocused) { return false; }
|
|
|
|
/// <summary>
|
|
/// Raised when <see cref="View.HasFocus"/> is about to change.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// Cancel the event to prevent the focus from changing.
|
|
/// </para>
|
|
/// <para>
|
|
/// Use <see cref="HasFocusChanged"/> to be notified after the focus has changed.
|
|
/// </para>
|
|
/// </remarks>
|
|
public event EventHandler<HasFocusEventArgs>? HasFocusChanging;
|
|
|
|
/// <summary>
|
|
/// Called when this view should stop being focused.
|
|
/// </summary>
|
|
/// <param name="newFocusedView">
|
|
/// The new focused view. If <see langword="null"/> it is not known which view will be
|
|
/// focused.
|
|
/// </param>
|
|
/// <param name="traversingDown">
|
|
/// Set to true to traverse down the focus
|
|
/// chain only. If false, the method will attempt to AdvanceFocus on the superview or restorefocus on
|
|
/// Application.Navigation.GetFocused().
|
|
/// </param>
|
|
/// <exception cref="InvalidOperationException"></exception>
|
|
private void SetHasFocusFalse (View? newFocusedView, bool traversingDown = false)
|
|
{
|
|
// Pre-conditions
|
|
if (!_hasFocus)
|
|
{
|
|
throw new InvalidOperationException ("SetHasFocusFalse should not be called if the view does not have focus.");
|
|
}
|
|
|
|
if (newFocusedView is { HasFocus: false })
|
|
{
|
|
throw new InvalidOperationException ("SetHasFocusFalse new focused view does not have focus.");
|
|
}
|
|
|
|
var thisAsAdornment = this as Adornment;
|
|
View? superViewOrParent = thisAsAdornment?.Parent ?? SuperView;
|
|
|
|
// If newFocusedVew is null, we need to find the view that should get focus, and SetFocus on it.
|
|
if (!traversingDown && newFocusedView is null)
|
|
{
|
|
// Restore focus?
|
|
if (superViewOrParent?._previouslyFocused is { CanFocus: true })
|
|
{
|
|
// TODO: Why don't we call RestoreFocus here?
|
|
if (superViewOrParent._previouslyFocused != this && superViewOrParent._previouslyFocused.SetFocus ())
|
|
{
|
|
// The above will cause SetHasFocusFalse, so we can return
|
|
Debug.Assert (!_hasFocus);
|
|
|
|
return;
|
|
}
|
|
}
|
|
|
|
// AdvanceFocus?
|
|
if (superViewOrParent is { CanFocus: true })
|
|
{
|
|
if (superViewOrParent.AdvanceFocus (NavigationDirection.Forward, TabStop))
|
|
{
|
|
// The above might have SetHasFocusFalse, so we can return
|
|
if (!_hasFocus)
|
|
{
|
|
return;
|
|
}
|
|
}
|
|
|
|
if (superViewOrParent is { HasFocus: true, CanFocus: true })
|
|
{
|
|
newFocusedView = superViewOrParent;
|
|
}
|
|
}
|
|
|
|
// Application.Navigation.GetFocused?
|
|
View? applicationFocused = App?.Navigation?.GetFocused ();
|
|
|
|
if (newFocusedView is null && applicationFocused != this && applicationFocused is { CanFocus: true })
|
|
{
|
|
// Temporarily ensure this view can't get focus
|
|
bool prevCanFocus = _canFocus;
|
|
_canFocus = false;
|
|
bool restoredFocus = applicationFocused!.RestoreFocus ();
|
|
_canFocus = prevCanFocus;
|
|
|
|
if (restoredFocus)
|
|
{
|
|
// The above caused SetHasFocusFalse, so we can return
|
|
Debug.Assert (!_hasFocus);
|
|
|
|
return;
|
|
}
|
|
}
|
|
|
|
// Application.TopRunnable?
|
|
if (newFocusedView is null && App?.TopRunnableView is { CanFocus: true, HasFocus: false })
|
|
{
|
|
// Temporarily ensure this view can't get focus
|
|
bool prevCanFocus = _canFocus;
|
|
_canFocus = false;
|
|
bool restoredFocus = App?.TopRunnableView.RestoreFocus () ?? false;
|
|
_canFocus = prevCanFocus;
|
|
|
|
if (App?.TopRunnableView is { CanFocus: true, HasFocus: true })
|
|
{
|
|
newFocusedView = App?.TopRunnableView;
|
|
}
|
|
else if (restoredFocus)
|
|
{
|
|
// The above caused SetHasFocusFalse, so we can return
|
|
Debug.Assert (!_hasFocus);
|
|
|
|
return;
|
|
}
|
|
}
|
|
|
|
// No other focusable view to be found. Just "leave" us...
|
|
}
|
|
|
|
Debug.Assert (_hasFocus);
|
|
|
|
// Before we can leave focus, we need to make sure that all views down the subview-hierarchy have left focus.
|
|
View? mostFocused = MostFocused;
|
|
|
|
if (mostFocused is { } && (newFocusedView is null || mostFocused != newFocusedView))
|
|
{
|
|
// Start at the bottom and work our way up to us
|
|
View? bottom = mostFocused;
|
|
|
|
while (bottom is { } && bottom != this)
|
|
{
|
|
if (bottom.HasFocus)
|
|
{
|
|
bottom.SetHasFocusFalse (newFocusedView, true);
|
|
|
|
Debug.Assert (_hasFocus);
|
|
}
|
|
|
|
bottom = bottom.SuperView;
|
|
}
|
|
|
|
Debug.Assert (_hasFocus);
|
|
}
|
|
|
|
if (superViewOrParent is { })
|
|
{
|
|
superViewOrParent._previouslyFocused = this;
|
|
}
|
|
|
|
bool previousValue = HasFocus;
|
|
|
|
Debug.Assert (_hasFocus);
|
|
|
|
// Note, can't be cancelled.
|
|
RaiseFocusChanging (HasFocus, !HasFocus, this, newFocusedView);
|
|
|
|
// Even though the change can't be cancelled, some listener may have changed the focus to another view.
|
|
if (!_hasFocus)
|
|
{
|
|
// Notify caused HasFocus to change to false.
|
|
return;
|
|
}
|
|
|
|
// Get whatever peer has focus, if any so we can update our superview's _previouslyMostFocused
|
|
View? focusedPeer = superViewOrParent?.Focused;
|
|
|
|
// Set HasFocus false
|
|
_hasFocus = false;
|
|
|
|
RaiseFocusChanged (HasFocus, this, newFocusedView);
|
|
|
|
if (_hasFocus)
|
|
{
|
|
// Notify caused HasFocus to change to true.
|
|
return;
|
|
}
|
|
|
|
// Post-conditions - prove correctness
|
|
if (HasFocus == previousValue)
|
|
{
|
|
throw new InvalidOperationException ("SetHasFocusFalse and the HasFocus value did not change.");
|
|
}
|
|
|
|
SetNeedsDraw ();
|
|
}
|
|
|
|
// TODO: CWP: FocusChanged should not be using event args derived from CancelEventArgs, as it is not cancellable.
|
|
private void RaiseFocusChanged (bool newHasFocus, View? previousFocusedView, View? focusedView)
|
|
{
|
|
// If we are the most focused view, we need to set the focused view in Application.Navigation
|
|
if (newHasFocus && focusedView?.Focused is null)
|
|
{
|
|
App?.Navigation?.SetFocused (focusedView);
|
|
}
|
|
|
|
// Call the virtual method
|
|
OnHasFocusChanged (newHasFocus, previousFocusedView, focusedView);
|
|
|
|
// Raise the event
|
|
var args = new HasFocusEventArgs (newHasFocus, newHasFocus, previousFocusedView, focusedView);
|
|
HasFocusChanged?.Invoke (this, args);
|
|
|
|
if (newHasFocus || focusedView is null)
|
|
{
|
|
SuperView?.RaiseFocusedChanged (previousFocusedView, focusedView);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Invoked after <see cref="HasFocus"/> has changed. This method is called before the <see cref="HasFocusChanged"/>
|
|
/// event is raised.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// This event cannot be cancelled.
|
|
/// </para>
|
|
/// </remarks>
|
|
/// <param name="newHasFocus">The new value of <see cref="View.HasFocus"/>.</param>
|
|
/// <param name="previousFocusedView"></param>
|
|
/// <param name="focusedView">The view that is now focused. May be <see langword="null"/></param>
|
|
protected virtual void OnHasFocusChanged (bool newHasFocus, View? previousFocusedView, View? focusedView) { }
|
|
|
|
/// <summary>Raised after <see cref="HasFocus"/> has changed.</summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// This event cannot be cancelled.
|
|
/// </para>
|
|
/// </remarks>
|
|
public event EventHandler<HasFocusEventArgs>? HasFocusChanged;
|
|
|
|
#endregion HasFocus
|
|
|
|
#region Tab/Focus Handling
|
|
|
|
/// <summary>
|
|
/// Gets the subviews and Adornments of this view that are scoped to the specified behavior and direction. If behavior
|
|
/// is null, all focusable subviews and
|
|
/// Adornments are returned.
|
|
/// </summary>
|
|
/// <param name="direction"></param>
|
|
/// <param name="behavior"></param>
|
|
/// <returns></returns>
|
|
internal View [] GetFocusChain (NavigationDirection direction, TabBehavior? behavior)
|
|
{
|
|
IEnumerable<View>? filteredSubViews;
|
|
|
|
if (behavior.HasValue)
|
|
{
|
|
filteredSubViews = InternalSubViews?.Where (v => v.TabStop == behavior && v is { CanFocus: true, Visible: true, Enabled: true });
|
|
}
|
|
else
|
|
{
|
|
filteredSubViews = InternalSubViews?.Where (v => v is { CanFocus: true, Visible: true, Enabled: true });
|
|
}
|
|
|
|
// How about in Adornments?
|
|
if (Padding is { CanFocus: true, Visible: true, Enabled: true } && Padding.TabStop == behavior)
|
|
{
|
|
filteredSubViews = filteredSubViews?.Append (Padding);
|
|
}
|
|
|
|
if (Border is { CanFocus: true, Visible: true, Enabled: true } && Border.TabStop == behavior)
|
|
{
|
|
filteredSubViews = filteredSubViews?.Append (Border);
|
|
}
|
|
|
|
if (Margin is { CanFocus: true, Visible: true, Enabled: true } && Margin.TabStop == behavior)
|
|
{
|
|
filteredSubViews = filteredSubViews?.Append (Margin);
|
|
}
|
|
|
|
if (direction == NavigationDirection.Backward)
|
|
{
|
|
filteredSubViews = filteredSubViews?.Reverse ();
|
|
}
|
|
|
|
return filteredSubViews?.ToArray () ?? Array.Empty<View> ();
|
|
}
|
|
|
|
private TabBehavior? _tabStop;
|
|
|
|
/// <summary>
|
|
/// Gets or sets the behavior of <see cref="AdvanceFocus"/> for keyboard navigation.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// See the View Navigation Deep Dive for more information:
|
|
/// <see href="https://gui-cs.github.io/Terminal.Gui/docs/navigation.html"/>
|
|
/// </para>
|
|
/// </remarks>
|
|
/// ///
|
|
/// <para>
|
|
/// If <see langword="null"/> the tab stop has not been set and setting <see cref="CanFocus"/> to true will set it
|
|
/// to
|
|
/// <see cref="TabBehavior.TabStop"/>.
|
|
/// </para>
|
|
/// <para>
|
|
/// TabStop is independent of <see cref="CanFocus"/>. If <see cref="CanFocus"/> is <see langword="false"/>, the
|
|
/// view will not gain
|
|
/// focus even if this property is set and vice versa.
|
|
/// </para>
|
|
/// <para>
|
|
/// The default <see cref="TabBehavior.TabStop"/> keys are <see cref="Application.NextTabKey"/> (<c>Key.Tab</c>)
|
|
/// and <see cref="Application.PrevTabKey"/> (<c>Key>Tab.WithShift</c>).
|
|
/// </para>
|
|
/// <para>
|
|
/// The default <see cref="TabBehavior.TabGroup"/> keys are <see cref="Application.NextTabGroupKey"/> (
|
|
/// <c>Key.F6</c>) and <see cref="Application.PrevTabGroupKey"/> (<c>Key>Key.F6.WithShift</c>).
|
|
/// </para>
|
|
/// </remarks>
|
|
public TabBehavior? TabStop
|
|
{
|
|
get => _tabStop;
|
|
set
|
|
{
|
|
if (_tabStop is { } && _tabStop == value)
|
|
{
|
|
return;
|
|
}
|
|
|
|
_tabStop = value;
|
|
}
|
|
}
|
|
|
|
#endregion Tab/Focus Handling
|
|
}
|