Files
Terminal.Gui/Terminal.Gui/MainLoop.cs
Tig dcb3b359ad Fixes #2926 - Refactor KeyEvent and KeyEventEventArgs to simplify (#2927)
* Adds basic MainLoop unit tests

* Remove WinChange action from Curses

* Remove WinChange action from Curses

* Remove ProcessInput action from Windows MainLoop

* Simplified MainLoop/ConsoleDriver by making MainLoop internal and moving impt fns to Application

* Modernized Terminal resize events

* Modernized Terminal resize events

* Removed un used property

* for _isWindowsTerminal devenv->wininit; not sure what changed

* Modernized mouse/keyboard events (Action->EventHandler)

* Updated OnMouseEvent API docs

* Using WT_SESSION to detect WT

* removes hacky GetParentProcess

* Updates to fix #2634 (clear last line)

* removes hacky GetParentProcess2

* Addressed mac resize issue

* Addressed mac resize issue

* Removes ConsoleDriver.PrepareToRun, has Init return MainLoop

* Removes unneeded Attribute methods

* Removed GetProcesssName

* Removed GetProcesssName

* Refactored KeyEvent and KeyEventEventArgs into a single class

* Revert "Refactored KeyEvent and KeyEventEventArgs into a single class"

This reverts commit 88a00658db.

* Fixed key repeat issue; reverted stupidity on 1049/1047 confusion

* Updated CSI API Docs

* merge

* Rearranged Event.cs to Keyboard.cs and Mouse.cs

* Renamed KeyEventEventArgs KeyEventArgs

* temp renamed KeyEvent OldKeyEvent

* Merged KeyEvent into KeyEventArgs

* Renamed Application.ProcessKey members

* Renamed Application.ProcessKey members

* Renamed Application.ProcessKey members

* Added Responder.KeyPressed

* Removed unused references

* Fixed arg naming

* InvokeKeybindings->InvokeKeyBindings

* InvokeKeybindings->InvokeKeyBindings

* Fixed unit tests fail

* More progress on refactoring key input; still broken and probably wrong

* Moved OnKeyPressed out of Responder and made ProcessKeyPrssed non-virtual

* Updated API docs

* Moved key handling from Responder to View

* Updated API docs

* Updated HotKey API docs

* Updated shortcut API docs

* Fixed responder unit tests

* Removed Shortcut from View as it is not used

* Removed unneeded OnHotKey override from Button

* Fixed BackTab logic

* Button now uses Key Bindings exclusively

* Button now uses Key Bindings exclusively

* Updated keyboard.md docs

* Fixed unit tests to account for Toplevel handling default button

* Added View.InvokeCommand API

* Modernized RadioGroup

* Removed ColdKey

* Modernized (partially) StatusBar

* Worked around FileDialog issue with Ctrl-F

* Fixed driver unit test; view must be focused to reciev key pressed

* Application code cleanup

* Start on updaing menu

* Menu now mostly works

* Menu Select refinement

* Fixed known menu bugs!

* Enabled HotKey to cause focus- experimental

* Fixes #3022 & adds unit test to prove it

* Actually Fixes #3022 & adds unit test to prove it

* Working through hotkey issues

* Misc fixes

* removed hot/cold key stuff from Keys scenario

* Fixed scenarios

* Simplified shortcut string handling

* Modernized Checkbox

* Modernized TileView

* Updated API docs

* Updated API docs

* attempting to publish v2 docs

* Revert "attempting to publish v2 docs"

This reverts commit 59dcec111b.

* Playing with api docs

* Removed Key.BackTab

* Removed Caps/Scroll/Numlock

* Partial removal of keymodifiers - unit tests pass

* Partial removal of keymodifiers - broke netdriver somewhere

* WindowsDriver & added KeyEventArgsTests

* Fixing menu shortcut/hotkeys - broke Menu.cs into separate files

* Fixed MenuBar!

* Finished modernizing Menu/MenuBar

* Removed Key.a-z. Broke lots of stuff

* checkout@v4

* progress on key mapping and formatting

* VK tests are still failing

* Fixed some unit tests

* Added Hotkey and Keybinding unit tests

* fixed unit test

* All unit tests pass again...

* Fixed broken unit tests

* KeyEventArgs.KeyValue -> AsRune

* Fixed bugs. Still some broken

* Added KeyEventArgs.IsAlpha. Added KeyEventArgs.cast ops. Fixed bugs. Unit tests pass

* Fixed WindowsDriver

* Oops.

* Refactoring based on bdisp's help. Not complete!

* removed calling into subviews from OnKeyBindings

* removed calling into subviews from OnKeyBindings

* Improved View KeyEvent unit tests

* More hotkey unit tests

* BIg change - Got rid of KeyPress w/in Application/Drivers

* Unit tests now pass again

* Refreshed API docs

* Better HotKey logic. More progress. Getting close.

* Fixed handling of shifted chars like ö

* Minor code cleanup

* Minor code cleanup2

* Why is build Action failing?

* Why is build Action failing??

* upgraded to .net8 to try to fix weird CI/CD build errors

* upgraded to .net8 to try to fix weird CI/CD build errors2

* Disabling TextViewTests to diagnose build errors

* reenable TextViewTests to diagnose build errors

* Arrrrrrg

* Merged v2_develop

* Fixed uppercase accented keys in WindowsDriver

* Fixed key binding api docs

* Experimental impl of CommandScope.SubViews for MenuBar

* Removed dead code from application.cs

* Removed dead code from application.cs

* Removed dead code from ConsoleDriver.cs

* Cleaned up some key binding stuff

* Disabled Alt to activate menu for now

* Updated label commands

* Fixed menu bugs. Upgraded menu unit tests

* Fixed unit tests

* Working on NetDriver

* fixed netdriver

* Fixed issues called out by @bdisp CR

* fixed CursesDriver

* added todo to netdriver

* Cherry picked treeview test fix 1b415e5

* Fix NetDriver.

* CommandScope->KeyBindingScope

* Address some tznind feedback

* Refactored KeyBindings big time!

* Added key consts to KeyEventArgs and renamed Key to ConsoleDriverKey

* Fixed some API docs

* Moved ConsoleDriverKey to ConsoleDriver.cs

* Renamed Key->ConsoleDriverKey

* Renamed Key->ConsoleDriverKey

* Renamed Key->ConsoleDriverKey

* renamed file I forgot to rename before

* Updated name and API docs of KeyEventArgs.isAlpha

* Fixed issues with OnKeyUp not doing the right thing.

* Fixed MainLoop.Running never being used

* Fixed MainLoop.Running never being used - unit tests

* Claned up BUGBUG comments

* Disabled a unit test to see why ci/cd tests are failing

* Removed defunct commented code

* Removed more defunct commented code

* Re-eanbled unit test; jsut removing one test case...

* Disabled more...

* Renambed Global->Applicaton and updated scope API docs

* Disabled more unit tests...

* Removed dead code

* Disabled more unit tests...2

* Disabled more unit tests...3

* Renambed Global->Applicaton and updated scope API docs 2

* Added more KeyBinding scope tests

* Added more KeyBinding scope tests2

* ConsoleDriverKey too long. Key too ambiguous. Settled on KeyCode. (Partialy because eventually I want to intro a class named Key).

* KeyEventArgs improvements. cast to Rune must be explicit as it's lossy

* Fixed warnings

* Renamed KeyEventArgs to Key... progress on fixing broken stuff that resulted

* Fix ConsoleKeyMapping bugs.

* Fix NetDriver issue from converting a lower case to a upper case.

* Started migration to Key from KeyCode - e.g. made HotKeys all consistent.

* Fixed build warnings

* Added key defns to Key

* KeyBindings now uses Key vs. KeyCode

* Verified by tweaking UICatalog

* Fixed treeview test ... again

* Renamed ProcessKeyDown/Up to NewKeyDown/Up and OnKeyPressed to OnProcessKeyDown to make things more clear

* Added test AllViews_KeyDown_All_EventsFire unit tests and fixed a few Views that were wrong

* fixed stupid KeyUp event bug

* If key not handled, return false for datefield

* dotnet test --no-restore --verbosity diag

* dotnet test --blame

* run tests on windows

* Fix TestVKPacket unit test and move it to ConsoleKeyMappingTests.cs file.

* Remove unnecessary commented code.

* Tweaked unit tests and removed Key.BareKey

* Fixed little details and updated api docs

* updated api docs

* AddKeyBindingsForHotKey: KeyCode->Key

* Cleaned up more old KeyCode usages. Added TODOs

---------

Co-authored-by: BDisp <bd.bdisp@gmail.com>
2023-12-16 12:04:23 -07:00

382 lines
11 KiB
C#

//
// MainLoop.cs: IMainLoopDriver and MainLoop for Terminal.Gui
//
// Authors:
// Miguel de Icaza (miguel@gnome.org)
//
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Terminal.Gui {
/// <summary>
/// Interface to create a platform specific <see cref="MainLoop"/> driver.
/// </summary>
internal interface IMainLoopDriver {
/// <summary>
/// Initializes the <see cref="MainLoop"/>, gets the calling main loop for the initialization.
/// </summary>
/// <remarks>
/// Call <see cref="TearDown"/> to release resources.
/// </remarks>
/// <param name="mainLoop">Main loop.</param>
void Setup (MainLoop mainLoop);
/// <summary>
/// Wakes up the <see cref="MainLoop"/> that might be waiting on input, must be thread safe.
/// </summary>
void Wakeup ();
/// <summary>
/// Must report whether there are any events pending, or even block waiting for events.
/// </summary>
/// <returns><c>true</c>, if there were pending events, <c>false</c> otherwise.</returns>
bool EventsPending ();
/// <summary>
/// The iteration function.
/// </summary>
void Iteration ();
/// <summary>
/// Tears down the <see cref="MainLoop"/> driver. Releases resources created in <see cref="Setup"/>.
/// </summary>
void TearDown ();
}
/// <summary>
/// The MainLoop monitors timers and idle handlers.
/// </summary>
/// <remarks>
/// Monitoring of file descriptors is only available on Unix, there
/// does not seem to be a way of supporting this on Windows.
/// </remarks>
internal class MainLoop : IDisposable {
internal SortedList<long, Timeout> _timeouts = new SortedList<long, Timeout> ();
readonly object _timeoutsLockToken = new object ();
/// <summary>
/// The idle handlers and lock that must be held while manipulating them
/// </summary>
readonly object _idleHandlersLock = new object ();
internal List<Func<bool>> _idleHandlers = new List<Func<bool>> ();
/// <summary>
/// Gets the list of all timeouts sorted by the <see cref="TimeSpan"/> time ticks.
/// A shorter limit time can be added at the end, but it will be called before an
/// earlier addition that has a longer limit time.
/// </summary>
internal SortedList<long, Timeout> Timeouts => _timeouts;
/// <summary>
/// Gets a copy of the list of all idle handlers.
/// </summary>
internal ReadOnlyCollection<Func<bool>> IdleHandlers {
get {
lock (_idleHandlersLock) {
return new List<Func<bool>> (_idleHandlers).AsReadOnly ();
}
}
}
/// <summary>
/// The current <see cref="IMainLoopDriver"/> in use.
/// </summary>
/// <value>The main loop driver.</value>
internal IMainLoopDriver MainLoopDriver { get; private set; }
/// <summary>
/// Invoked when a new timeout is added. To be used in the case
/// when <see cref="Application.EndAfterFirstIteration"/> is <see langword="true"/>.
/// </summary>
internal event EventHandler<TimeoutEventArgs> TimeoutAdded;
/// <summary>
/// Creates a new MainLoop.
/// </summary>
/// <remarks>
/// Use <see cref="Dispose"/> to release resources.
/// </remarks>
/// <param name="driver">The <see cref="ConsoleDriver"/> instance
/// (one of the implementations FakeMainLoop, UnixMainLoop, NetMainLoop or WindowsMainLoop).</param>
internal MainLoop (IMainLoopDriver driver)
{
MainLoopDriver = driver;
driver.Setup (this);
}
/// <summary>
/// Adds specified idle handler function to <see cref="MainLoop"/> processing.
/// The handler function will be called once per iteration of the main loop after other events have been handled.
/// </summary>
/// <remarks>
/// <para>
/// Remove an idle handler by calling <see cref="RemoveIdle(Func{bool})"/> with the token this method returns.
/// </para>
/// <para>
/// If the <paramref name="idleHandler"/> returns <see langword="false"/> it will be removed and not called subsequently.
/// </para>
/// </remarks>
/// <param name="idleHandler">Token that can be used to remove the idle handler with <see cref="RemoveIdle(Func{bool})"/> .</param>
internal Func<bool> AddIdle (Func<bool> idleHandler)
{
lock (_idleHandlersLock) {
_idleHandlers.Add (idleHandler);
}
MainLoopDriver.Wakeup ();
return idleHandler;
}
/// <summary>
/// Removes an idle handler added with <see cref="AddIdle(Func{bool})"/> from processing.
/// </summary>
/// <param name="token">A token returned by <see cref="AddIdle(Func{bool})"/></param>
/// Returns <c>true</c>if the idle handler is successfully removed; otherwise, <c>false</c>.
/// This method also returns <c>false</c> if the idle handler is not found.
internal bool RemoveIdle (Func<bool> token)
{
lock (_idleHandlersLock) {
return _idleHandlers.Remove (token);
}
}
void AddTimeout (TimeSpan time, Timeout timeout)
{
lock (_timeoutsLockToken) {
var k = (DateTime.UtcNow + time).Ticks;
_timeouts.Add (NudgeToUniqueKey (k), timeout);
TimeoutAdded?.Invoke (this, new TimeoutEventArgs (timeout, k));
}
}
/// <summary>
/// Adds a timeout to the <see cref="MainLoop"/>.
/// </summary>
/// <remarks>
/// When time specified passes, the callback will be invoked.
/// If the callback returns true, the timeout will be reset, repeating
/// the invocation. If it returns false, the timeout will stop and be removed.
///
/// The returned value is a token that can be used to stop the timeout
/// by calling <see cref="RemoveTimeout(object)"/>.
/// </remarks>
internal object AddTimeout (TimeSpan time, Func<bool> callback)
{
if (callback == null) {
throw new ArgumentNullException (nameof (callback));
}
var timeout = new Timeout () {
Span = time,
Callback = callback
};
AddTimeout (time, timeout);
return timeout;
}
/// <summary>
/// Removes a previously scheduled timeout
/// </summary>
/// <remarks>
/// The token parameter is the value returned by AddTimeout.
/// </remarks>
/// Returns <c>true</c>if the timeout is successfully removed; otherwise, <c>false</c>.
/// This method also returns <c>false</c> if the timeout is not found.
internal bool RemoveTimeout (object token)
{
lock (_timeoutsLockToken) {
var idx = _timeouts.IndexOfValue (token as Timeout);
if (idx == -1) {
return false;
}
_timeouts.RemoveAt (idx);
}
return true;
}
void RunTimers ()
{
var now = DateTime.UtcNow.Ticks;
SortedList<long, Timeout> copy;
// lock prevents new timeouts being added
// after we have taken the copy but before
// we have allocated a new list (which would
// result in lost timeouts or errors during enumeration)
lock (_timeoutsLockToken) {
copy = _timeouts;
_timeouts = new SortedList<long, Timeout> ();
}
foreach ((var k, var timeout) in copy) {
if (k < now) {
if (timeout.Callback ()) {
AddTimeout (timeout.Span, timeout);
}
} else {
lock (_timeoutsLockToken) {
_timeouts.Add (NudgeToUniqueKey (k), timeout);
}
}
}
}
/// <summary>
/// Called from <see cref="IMainLoopDriver.EventsPending"/> to check if there are any outstanding timers or idle handlers.
/// </summary>
/// <param name="waitTimeout">Returns the number of milliseconds remaining in the current timer (if any). Will be -1 if
/// there are no active timers.</param>
/// <returns><see langword="true"/> if there is a timer or idle handler active.</returns>
internal bool CheckTimersAndIdleHandlers (out int waitTimeout)
{
var now = DateTime.UtcNow.Ticks;
waitTimeout = 0;
lock (_timeouts) {
if (_timeouts.Count > 0) {
waitTimeout = (int)((_timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
if (waitTimeout < 0) {
// This avoids 'poll' waiting infinitely if 'waitTimeout < 0' until some action is detected
// This can occur after IMainLoopDriver.Wakeup is executed where the pollTimeout is less than 0
// and no event occurred in elapsed time when the 'poll' is start running again.
waitTimeout = 0;
}
return true;
}
// ManualResetEventSlim.Wait, which is called by IMainLoopDriver.EventsPending, will wait indefinitely if
// the timeout is -1.
waitTimeout = -1;
}
// There are no timers set, check if there are any idle handlers
lock (_idleHandlers) {
return _idleHandlers.Count > 0;
}
}
/// <summary>
/// Finds the closest number to <paramref name="k"/> that is not
/// present in <see cref="_timeouts"/> (incrementally).
/// </summary>
/// <param name="k"></param>
/// <returns></returns>
long NudgeToUniqueKey (long k)
{
lock (_timeoutsLockToken) {
while (_timeouts.ContainsKey (k)) {
k++;
}
}
return k;
}
void RunIdle ()
{
List<Func<bool>> iterate;
lock (_idleHandlersLock) {
iterate = _idleHandlers;
_idleHandlers = new List<Func<bool>> ();
}
foreach (var idle in iterate) {
if (idle ()) {
lock (_idleHandlersLock) {
_idleHandlers.Add (idle);
}
}
}
}
/// <summary>
/// Used for unit tests.
/// </summary>
internal bool Running { get; set; }
/// <summary>
/// Determines whether there are pending events to be processed.
/// </summary>
/// <remarks>
/// You can use this method if you want to probe if events are pending.
/// Typically used if you need to flush the input queue while still
/// running some of your own code in your main thread.
/// </remarks>
internal bool EventsPending ()
{
return MainLoopDriver.EventsPending ();
}
/// <summary>
/// Runs one iteration of timers and file watches
/// </summary>
/// <remarks>
/// Use this to process all pending events (timers, idle handlers and file watches).
///
/// <code>
/// while (main.EventsPending ()) RunIteration ();
/// </code>
/// </remarks>
internal void RunIteration ()
{
lock (_timeouts) {
if (_timeouts.Count > 0) {
RunTimers ();
}
}
MainLoopDriver.Iteration ();
var runIdle = false;
lock (_idleHandlersLock) {
runIdle = _idleHandlers.Count > 0;
}
if (runIdle) {
RunIdle ();
}
}
/// <summary>
/// Runs the <see cref="MainLoop"/>. Used only for unit tests.
/// </summary>
internal void Run ()
{
var prev = Running;
Running = true;
while (Running) {
EventsPending ();
RunIteration ();
}
Running = prev;
}
/// <summary>
/// Wakes up the <see cref="MainLoop"/> that might be waiting on input.
/// </summary>
internal void Wakeup () => MainLoopDriver?.Wakeup ();
/// <summary>
/// Stops the main loop driver and calls <see cref="IMainLoopDriver.Wakeup"/>. Used only for unit tests.
/// </summary>
internal void Stop ()
{
Running = false;
Wakeup ();
}
/// <inheritdoc/>
public void Dispose ()
{
GC.SuppressFinalize (this);
Stop ();
Running = false;
MainLoopDriver?.TearDown ();
MainLoopDriver = null;
}
}
}