Browse Source

Merge pull request #3783 from tig/v2_3777-hexedit

Fixes #3777 - `HexView` Focus Issue - Adds `View.AdvancingFocus` events
Tig 9 months ago
parent
commit
d6a652b159

+ 8 - 8
Terminal.Gui/Application/Application.Run.cs

@@ -80,14 +80,14 @@ public static partial class Application // Run (Begin, Run, End, Stop)
     {
         ArgumentNullException.ThrowIfNull (toplevel);
 
-#if DEBUG_IDISPOSABLE
-        Debug.Assert (!toplevel.WasDisposed);
-
-        if (_cachedRunStateToplevel is { } && _cachedRunStateToplevel != toplevel)
-        {
-            Debug.Assert (_cachedRunStateToplevel.WasDisposed);
-        }
-#endif
+//#if DEBUG_IDISPOSABLE
+//        Debug.Assert (!toplevel.WasDisposed);
+
+//        if (_cachedRunStateToplevel is { } && _cachedRunStateToplevel != toplevel)
+//        {
+//            Debug.Assert (_cachedRunStateToplevel.WasDisposed);
+//        }
+//#endif
 
         // Ensure the mouse is ungrabbed.
         MouseGrabView = null;

+ 14 - 1
Terminal.Gui/Application/ApplicationNavigation.cs

@@ -27,7 +27,19 @@ public class ApplicationNavigation
     /// <summary>
     ///     Gets the most focused <see cref="View"/> in the application, if there is one.
     /// </summary>
-    public View? GetFocused () { return _focused; }
+    public View? GetFocused ()
+    {
+        return _focused;
+
+        if (_focused is { CanFocus: true, HasFocus: true })
+        {
+            return _focused;
+        }
+
+        _focused = null;
+
+        return null;
+    }
 
     /// <summary>
     ///     Gets whether <paramref name="view"/> is in the Subview hierarchy of <paramref name="start"/>.
@@ -77,6 +89,7 @@ public class ApplicationNavigation
         {
             return;
         }
+        Debug.Assert (value is null or { CanFocus: true, HasFocus: true });
 
         _focused = value;
 

+ 3 - 0
Terminal.Gui/Drawing/Glyphs.cs

@@ -97,6 +97,9 @@ public class GlyphDefinitions
     /// <summary>Dot. Default is (U+2219) - ∙.</summary>
     public Rune Dot { get; set; } = (Rune)'∙';
 
+    /// <summary>Dotted Square - ⬚ U+02b1a┝</summary>
+    public Rune DottedSquare { get; set; } = (Rune)'⬚';
+
     /// <summary>Black Circle . Default is (U+025cf) - ●.</summary>
     public Rune BlackCircle { get; set; } = (Rune)'●'; // Black Circle - ● U+025cf
 

+ 5 - 0
Terminal.Gui/Input/Command.cs

@@ -166,6 +166,11 @@ public enum Command
     /// </summary>
     EnableOverwrite,
 
+    /// <summary>
+    ///     Inserts a character.
+    /// </summary>
+    Insert,
+
     /// <summary>Disables overwrite mode (<see cref="EnableOverwrite"/>)</summary>
     DisableOverwrite,
 

+ 1 - 1
Terminal.Gui/View/Adornment/ShadowView.cs

@@ -109,7 +109,7 @@ internal class ShadowView : View
         Rectangle screen = ViewportToScreen (viewport);
 
         // Fill the rest of the rectangle - note we skip the last since vertical will draw it
-        for (int i = screen.X + 1; i < screen.X + screen.Width - 1; i++)
+        for (int i = Math.Max(0, screen.X + 1); i < screen.X + screen.Width - 1; i++)
         {
             Driver.Move (i, screen.Y);
 

+ 11 - 0
Terminal.Gui/View/CancelEventArgs.cs

@@ -27,6 +27,17 @@ public class CancelEventArgs<T> : CancelEventArgs where T : notnull
         NewValue = newValue;
     }
 
+    /// <summary>
+    ///     Initializes a new instance of the <see cref="CancelEventArgs{T}"/> class.
+    /// </summary>
+    /// <param name="currentValue">The current (old) value of the property.</param>
+    /// <param name="newValue">The value the property will be set to if the event is not cancelled.</param>
+    protected CancelEventArgs (T currentValue, T newValue)
+    {
+        CurrentValue = currentValue;
+        NewValue = newValue;
+    }
+
     /// <summary>The current value of the property.</summary>
     public T CurrentValue { get; }
 

+ 18 - 0
Terminal.Gui/View/Navigation/AdvanceFocusEventArgs.cs

@@ -0,0 +1,18 @@
+namespace Terminal.Gui;
+
+/// <summary>The event arguments for <see cref="View.AdvanceFocus"/> events.</summary>
+public class AdvanceFocusEventArgs : CancelEventArgs<bool>
+{
+    /// <summary>Initializes a new instance.</summary>
+    public AdvanceFocusEventArgs (NavigationDirection direction, TabBehavior? behavior) : base (false, false)
+    {
+        Direction = direction;
+        Behavior = behavior;
+    }
+
+    /// <summary>Gets or sets the view that is losing focus.</summary>
+    public NavigationDirection Direction { get; set; }
+
+    /// <summary>Gets or sets the view that is gaining focus.</summary>
+    public TabBehavior? Behavior { get; set; }
+}

+ 1 - 1
Terminal.Gui/View/Navigation/FocusEventArgs.cs

@@ -20,4 +20,4 @@ public class HasFocusEventArgs : CancelEventArgs<bool>
     /// <summary>Gets or sets the view that is gaining focus.</summary>
     public View NewFocused { get; set; }
 
-}
+}

+ 7 - 0
Terminal.Gui/View/View.Hierarchy.cs

@@ -169,6 +169,13 @@ public partial class View // SuperView/SubView hierarchy management (SuperView,
         Debug.Assert (!view.HasFocus);
 
         _subviews.Remove (view);
+
+        // Clean up focus stuff
+        _previouslyFocused = null;
+        if (view._superView is { } && view._superView._previouslyFocused == this)
+        {
+            view._superView._previouslyFocused = null;
+        }
         view._superView = null;
 
         SetNeedsLayout ();

+ 202 - 63
Terminal.Gui/View/View.Navigation.cs

@@ -1,6 +1,5 @@
 #nullable enable
 using System.Diagnostics;
-using System.Reflection.PortableExecutable;
 
 namespace Terminal.Gui;
 
@@ -18,7 +17,8 @@ public partial class View // Focus and cross-view navigation management (TabStop
     ///         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.GuiV2Docs/docs/navigation.html"/>
+    ///         See the View Navigation Deep Dive for more information:
+    ///         <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/navigation.html"/>
     ///     </para>
     /// </remarks>
     /// <param name="direction"></param>
@@ -34,6 +34,11 @@ public partial class View // Focus and cross-view navigation management (TabStop
             return false;
         }
 
+        if (RaiseAdvancingFocus (direction, behavior))
+        {
+            return true;
+        }
+
         View? focused = Focused;
 
         if (focused is { } && focused.AdvanceFocus (direction, behavior))
@@ -128,6 +133,14 @@ public partial class View // Focus and cross-view navigation management (TabStop
         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;
         }
 
@@ -137,10 +150,61 @@ public partial class View // Focus and cross-view navigation management (TabStop
         return focusSet;
     }
 
+    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.GuiV2Docs/docs/navigation.html"/>
+    ///         See the View Navigation Deep Dive for more information:
+    ///         <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/navigation.html"/>
     ///     </para>
     ///     <para>
     ///         <see cref="SuperView"/> must also have <see cref="CanFocus"/> set to <see langword="true"/>.
@@ -180,7 +244,8 @@ public partial class View // Focus and cross-view navigation management (TabStop
             if (!_canFocus && HasFocus)
             {
                 // If CanFocus is set to false and this view has focus, make it leave focus
-                HasFocus = false;
+                // Set transversing down so we don't go back up the hierarchy...
+                SetHasFocusFalse (null, false);
             }
 
             if (_canFocus && !HasFocus && Visible && SuperView is { Focused: null })
@@ -296,7 +361,12 @@ public partial class View // Focus and cross-view navigation management (TabStop
 
         if (Focused is null && _previouslyFocused is { } && indicies.Contains (_previouslyFocused))
         {
-            return _previouslyFocused.SetFocus ();
+            if (_previouslyFocused.SetFocus ())
+            {
+                return true;
+            }
+
+            _previouslyFocused = null;
         }
 
         return false;
@@ -324,7 +394,8 @@ public partial class View // Focus and cross-view navigation management (TabStop
     /// </summary>
     /// <remarks>
     ///     <para>
-    ///         See the View Navigation Deep Dive for more information: <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/navigation.html"/>
+    ///         See the View Navigation Deep Dive for more information:
+    ///         <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/navigation.html"/>
     ///     </para>
     ///     <para>
     ///         Only Views that are visible, enabled, and have <see cref="CanFocus"/> set to <see langword="true"/> are
@@ -375,6 +446,8 @@ public partial class View // Focus and cross-view navigation management (TabStop
             {
                 SetHasFocusFalse (null);
 
+                Debug.Assert (!_hasFocus);
+
                 if (_hasFocus)
                 {
                     // force it.
@@ -391,7 +464,8 @@ public partial class View // Focus and cross-view navigation management (TabStop
     /// </summary>
     /// <remarks>
     ///     <para>
-    ///         See the View Navigation Deep Dive for more information: <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/navigation.html"/>
+    ///         See the View Navigation Deep Dive for more information:
+    ///         <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/navigation.html"/>
     ///     </para>
     /// </remarks>
     /// <returns><see langword="true"/> if the focus changed; <see langword="true"/> false otherwise.</returns>
@@ -412,14 +486,14 @@ public partial class View // Focus and cross-view navigation management (TabStop
     ///     other methods that
     ///     set or remove focus from a view.
     /// </summary>
-    /// <param name="previousFocusedView">
-    ///     The previously focused view. If <see langword="null"/> there is no previously focused
+    /// <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? previousFocusedView, bool traversingUp = false)
+    private (bool focusSet, bool cancelled) SetHasFocusTrue (View? currentFocusedView, bool traversingUp = false)
     {
         Debug.Assert (SuperView is null || ApplicationNavigation.IsInHierarchy (SuperView, this));
 
@@ -429,6 +503,11 @@ public partial class View // Focus and cross-view navigation management (TabStop
             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;
 
@@ -451,7 +530,7 @@ public partial class View // Focus and cross-view navigation management (TabStop
 
         bool previousValue = HasFocus;
 
-        bool cancelled = NotifyFocusChanging (false, true, previousFocusedView, this);
+        bool cancelled = RaiseFocusChanging (false, true, currentFocusedView, this);
 
         if (cancelled)
         {
@@ -462,7 +541,7 @@ public partial class View // Focus and cross-view navigation management (TabStop
         // 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 (previousFocusedView, true);
+            (bool focusSet, bool svCancelled) = sv.SetHasFocusTrue (currentFocusedView, true);
 
             if (!focusSet)
             {
@@ -488,31 +567,32 @@ public partial class View // Focus and cross-view navigation management (TabStop
 
         if (!traversingUp)
         {
-            // Restore focus to the previously focused subview 
+            // 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 (!AdvanceFocus (NavigationDirection.Forward, null))
-                {
-                    // Couldn't advance, so we're the most focused view in the application
-                    Application.Navigation?.SetFocused (this);
-                }
+                // Couldn't restore focus, so use Advance to navigate to the next focusable subview, if any
+                AdvanceFocus (NavigationDirection.Forward, null);
             }
         }
 
-        if (previousFocusedView is { HasFocus: true } && GetFocusChain (NavigationDirection.Forward, TabStop).Contains (previousFocusedView))
+        // Now make sure the old focused view loses focus
+        if (currentFocusedView is { HasFocus: true } && GetFocusChain (NavigationDirection.Forward, TabStop).Contains (currentFocusedView))
         {
-            previousFocusedView.SetHasFocusFalse (this);
+            currentFocusedView.SetHasFocusFalse (this);
         }
 
-        _previouslyFocused = null;
+        if (_previouslyFocused is { })
+        {
+            _previouslyFocused = null;
+        }
 
         if (Arrangement.HasFlag (ViewArrangement.Overlapped))
         {
             SuperView?.MoveSubviewToEnd (this);
         }
 
-        NotifyFocusChanged (HasFocus, previousFocusedView, this);
+        // Focus work is done. Notify.
+        RaiseFocusChanged (HasFocus, currentFocusedView, this);
 
         SetNeedsDisplay ();
 
@@ -525,8 +605,11 @@ public partial class View // Focus and cross-view navigation management (TabStop
         return (true, false);
     }
 
-    private bool NotifyFocusChanging (bool currentHasFocus, bool newHasFocus, View? currentFocused, View? newFocused)
+    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))
         {
@@ -543,6 +626,20 @@ public partial class View // Focus and cross-view navigation management (TabStop
             return true;
         }
 
+        View? appFocused = Application.Navigation?.GetFocused ();
+
+        if (appFocused == currentFocused)
+        {
+            if (newFocused is { HasFocus: true })
+            {
+                Application.Navigation?.SetFocused (newFocused);
+            }
+            else
+            {
+                Application.Navigation?.SetFocused (null);
+            }
+        }
+
         return false;
     }
 
@@ -586,8 +683,9 @@ public partial class View // Focus and cross-view navigation management (TabStop
     ///     focused.
     /// </param>
     /// <param name="traversingDown">
-    ///     Set to true to indicate method is being called recurively, traversing down the focus
-    ///     chain.
+    ///     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)
@@ -598,45 +696,86 @@ public partial class View // Focus and cross-view navigation management (TabStop
             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)
         {
-            if (superViewOrParent?._previouslyFocused is { })
+            // Restore focus?
+            if (superViewOrParent?._previouslyFocused is { CanFocus: true })
             {
-                if (superViewOrParent._previouslyFocused != this)
+                // TODO: Why don't we call RestoreFocus here?
+                if (superViewOrParent._previouslyFocused != this && superViewOrParent._previouslyFocused.SetFocus ())
                 {
-                    superViewOrParent?._previouslyFocused?.SetFocus ();
-
                     // The above will cause SetHasFocusFalse, so we can return
+                    Debug.Assert (!_hasFocus);
+
                     return;
                 }
             }
 
-            if (superViewOrParent is { })
+            // AdvanceFocus?
+            if (superViewOrParent is { CanFocus: true })
             {
                 if (superViewOrParent.AdvanceFocus (NavigationDirection.Forward, TabStop))
                 {
-                    // The above will cause SetHasFocusFalse, so we can return
-                    return;
+                    // The above might have SetHasFocusFalse, so we can return
+                    if (!_hasFocus)
+                    {
+                        return;
+                    }
                 }
 
-                newFocusedView = superViewOrParent;
+                if (superViewOrParent is { HasFocus: true, CanFocus: true })
+                {
+                    newFocusedView = superViewOrParent;
+                }
             }
 
-            if (Application.Navigation is { } && Application.Top is { })
+            // Application.Navigation.GetFocused?
+            View? applicationFocused = Application.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 = Application.Top!.RestoreFocus ();
+                bool restoredFocus = applicationFocused!.RestoreFocus ();
                 _canFocus = prevCanFocus;
 
                 if (restoredFocus)
                 {
                     // The above caused SetHasFocusFalse, so we can return
+                    Debug.Assert (!_hasFocus);
+
+                    return;
+                }
+            }
+
+            // Application.Top?
+            if (newFocusedView is null && Application.Top is { CanFocus: true, HasFocus: false })
+            {
+                // Temporarily ensure this view can't get focus
+                bool prevCanFocus = _canFocus;
+                _canFocus = false;
+                bool restoredFocus = Application.Top.RestoreFocus ();
+                _canFocus = prevCanFocus;
+
+                if (Application.Top is { CanFocus: true, HasFocus: true })
+                {
+                    newFocusedView = Application.Top;
+                }
+                else if (restoredFocus)
+                {
+                    // The above caused SetHasFocusFalse, so we can return
+                    Debug.Assert (!_hasFocus);
+
                     return;
                 }
             }
@@ -644,6 +783,7 @@ public partial class View // Focus and cross-view navigation management (TabStop
             // 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;
@@ -665,15 +805,7 @@ public partial class View // Focus and cross-view navigation management (TabStop
                 bottom = bottom.SuperView;
             }
 
-            if (bottom == this && bottom.SuperView is Adornment a)
-            {
-                //a.SetHasFocusFalse (newFocusedView, true);
-
-                Debug.Assert (_hasFocus);
-            }
-
             Debug.Assert (_hasFocus);
-
         }
 
         if (superViewOrParent is { })
@@ -683,8 +815,17 @@ public partial class View // Focus and cross-view navigation management (TabStop
 
         bool previousValue = HasFocus;
 
+        Debug.Assert (_hasFocus);
+
         // Note, can't be cancelled.
-        NotifyFocusChanging (HasFocus, !HasFocus, newFocusedView, this);
+        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;
@@ -692,17 +833,7 @@ public partial class View // Focus and cross-view navigation management (TabStop
         // Set HasFocus false
         _hasFocus = false;
 
-        if (Application.Navigation is { })
-        {
-            View? appFocused = Application.Navigation.GetFocused ();
-
-            if (appFocused is { } || appFocused == this)
-            {
-                Application.Navigation.SetFocused (newFocusedView ?? superViewOrParent);
-            }
-        }
-
-        NotifyFocusChanged (HasFocus, this, newFocusedView);
+        RaiseFocusChanged (HasFocus, this, newFocusedView);
 
         if (_hasFocus)
         {
@@ -719,8 +850,13 @@ public partial class View // Focus and cross-view navigation management (TabStop
         SetNeedsDisplay ();
     }
 
-    private void NotifyFocusChanged (bool newHasFocus, View? previousFocusedView, View? focusedVew)
+    private void RaiseFocusChanged (bool newHasFocus, View? previousFocusedView, View? focusedVew)
     {
+        if (newHasFocus && focusedVew?.Focused is null)
+        {
+            Application.Navigation?.SetFocused (focusedVew);
+        }
+
         // Call the virtual method
         OnHasFocusChanged (newHasFocus, previousFocusedView, focusedVew);
 
@@ -756,7 +892,8 @@ public partial class View // Focus and cross-view navigation management (TabStop
     #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
+    ///     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>
@@ -775,7 +912,6 @@ public partial class View // Focus and cross-view navigation management (TabStop
             filteredSubviews = _subviews?.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)
         {
@@ -806,11 +942,14 @@ public partial class View // Focus and cross-view navigation management (TabStop
     ///     Gets or sets the behavior of <see cref="AdvanceFocus"/> for keyboard navigation.
     /// </summary>
     /// <remarks>
-    /// <remarks>
+    ///     <remarks>
+    ///         <para>
+    ///             See the View Navigation Deep Dive for more information:
+    ///             <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/navigation.html"/>
+    ///         </para>
+    ///     </remarks>
+    ///     ///
     ///     <para>
-    ///         See the View Navigation Deep Dive for more information: <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/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"/>.

File diff suppressed because it is too large
+ 392 - 235
Terminal.Gui/Views/HexView.cs


+ 15 - 15
Terminal.Gui/Views/HexViewEventArgs.cs

@@ -12,41 +12,41 @@ namespace Terminal.Gui;
 public class HexViewEventArgs : EventArgs
 {
     /// <summary>Initializes a new instance of <see cref="HexViewEventArgs"/></summary>
-    /// <param name="pos">The character position.</param>
-    /// <param name="cursor">The cursor position.</param>
+    /// <param name="address">The byte position in the steam.</param>
+    /// <param name="position">The edit position.</param>
     /// <param name="lineLength">Line bytes length.</param>
-    public HexViewEventArgs (long pos, Point cursor, int lineLength)
+    public HexViewEventArgs (long address, Point position, int lineLength)
     {
-        Position = pos;
-        CursorPosition = cursor;
+        Address = address;
+        Position = position;
         BytesPerLine = lineLength;
     }
 
     /// <summary>The bytes length per line.</summary>
     public int BytesPerLine { get; private set; }
 
-    /// <summary>Gets the current cursor position starting at one for both, line and column.</summary>
-    public Point CursorPosition { get; private set; }
+    /// <summary>Gets the current edit position.</summary>
+    public Point Position { get; private set; }
 
-    /// <summary>Gets the current character position starting at one, related to the <see cref="Stream"/>.</summary>
-    public long Position { get; private set; }
+    /// <summary>Gets the byte position in the <see cref="Stream"/>.</summary>
+    public long Address { get; private set; }
 }
 
 /// <summary>Defines the event arguments for <see cref="HexView.Edited"/> event.</summary>
 public class HexViewEditEventArgs : EventArgs
 {
     /// <summary>Creates a new instance of the <see cref="HexViewEditEventArgs"/> class.</summary>
-    /// <param name="position"></param>
+    /// <param name="address"></param>
     /// <param name="newValue"></param>
-    public HexViewEditEventArgs (long position, byte newValue)
+    public HexViewEditEventArgs (long address, byte newValue)
     {
-        Position = position;
+        Address = address;
         NewValue = newValue;
     }
 
-    /// <summary>Gets the new value for that <see cref="Position"/>.</summary>
+    /// <summary>Gets the new value for that <see cref="Address"/>.</summary>
     public byte NewValue { get; }
 
-    /// <summary>Gets the location of the edit.</summary>
-    public long Position { get; }
+    /// <summary>Gets the address of the edit in the stream.</summary>
+    public long Address { get; }
 }

+ 1 - 1
Terminal.Gui/Views/Shortcut.cs

@@ -58,7 +58,7 @@ public class Shortcut : View, IOrientation, IDesignable
     ///     </para>
     /// </remarks>
     /// <param name="targetView">
-    ///     The View that <paramref name="command"/> will be invoked when user does something that causes the Shortcut's Accept
+    ///     The View that <paramref name="command"/> will be invoked on when user does something that causes the Shortcut's Accept
     ///     event to be raised.
     /// </param>
     /// <param name="command">

+ 110 - 71
UICatalog/Scenarios/HexEditor.cs

@@ -16,20 +16,23 @@ public class HexEditor : Scenario
     private HexView _hexView;
     private MenuItem _miAllowEdits;
     private bool _saved = true;
-    private Shortcut _siPositionChanged;
+    private Shortcut _scAddress;
+    private Shortcut _scInfo;
+    private Shortcut _scPosition;
     private StatusBar _statusBar;
 
     public override void Main ()
     {
         Application.Init ();
-        Toplevel app = new Toplevel ()
+
+        var app = new Toplevel
         {
             ColorScheme = Colors.ColorSchemes ["Base"]
         };
 
         CreateDemoFile (_fileName);
 
-        _hexView = new HexView (new MemoryStream (Encoding.UTF8.GetBytes ("Demo text.")))
+        _hexView = new (new MemoryStream (Encoding.UTF8.GetBytes ("Demo text.")))
         {
             X = 0,
             Y = 1,
@@ -46,71 +49,97 @@ public class HexEditor : Scenario
         {
             Menus =
             [
-                new MenuBarItem (
-                                 "_File",
-                                 new MenuItem []
-                                 {
-                                     new ("_New", "", () => New ()),
-                                     new ("_Open", "", () => Open ()),
-                                     new ("_Save", "", () => Save ()),
-                                     null,
-                                     new ("_Quit", "", () => Quit ())
-                                 }
-                                ),
-                new MenuBarItem (
-                                 "_Edit",
-                                 new MenuItem []
-                                 {
-                                     new ("_Copy", "", () => Copy ()),
-                                     new ("C_ut", "", () => Cut ()),
-                                     new ("_Paste", "", () => Paste ())
-                                 }
-                                ),
-                new MenuBarItem (
-                                 "_Options",
-                                 new []
-                                 {
-                                     _miAllowEdits = new MenuItem (
-                                                                   "_AllowEdits",
-                                                                   "",
-                                                                   () => ToggleAllowEdits ()
-                                                                  )
-                                     {
-                                         Checked = _hexView.AllowEdits,
-                                         CheckType = MenuItemCheckStyle
-                                             .Checked
-                                     }
-                                 }
-                                )
+                new (
+                     "_File",
+                     new MenuItem []
+                     {
+                         new ("_New", "", () => New ()),
+                         new ("_Open", "", () => Open ()),
+                         new ("_Save", "", () => Save ()),
+                         null,
+                         new ("_Quit", "", () => Quit ())
+                     }
+                    ),
+                new (
+                     "_Edit",
+                     new MenuItem []
+                     {
+                         new ("_Copy", "", () => Copy ()),
+                         new ("C_ut", "", () => Cut ()),
+                         new ("_Paste", "", () => Paste ())
+                     }
+                    ),
+                new (
+                     "_Options",
+                     new []
+                     {
+                         _miAllowEdits = new (
+                                              "_AllowEdits",
+                                              "",
+                                              () => ToggleAllowEdits ()
+                                             )
+                         {
+                             Checked = _hexView.AllowEdits,
+                             CheckType = MenuItemCheckStyle
+                                 .Checked
+                         }
+                     }
+                    )
             ]
         };
         app.Add (menu);
 
-        _statusBar = new StatusBar (
-                                    new []
-                                    {
-                                        new (Key.F2, "Open", () => Open ()),
-                                        new (Key.F3, "Save", () => Save ()),
-                                        new (
-                                             Application.QuitKey,
-                                             $"Quit",
-                                             () => Quit ()
-                                            ),
-                                        _siPositionChanged = new Shortcut (
-                                                                             Key.Empty,
-                                                                             $"Position: {
-                                                                                 _hexView.Position
-                                                                             } Line: {
-                                                                                 _hexView.CursorPosition.Y
-                                                                             } Col: {
-                                                                                 _hexView.CursorPosition.X
-                                                                             } Line length: {
-                                                                                 _hexView.BytesPerLine
-                                                                             }",
-                                                                             () => { }
-                                                                            )
-                                    }
-                                   )
+        var addressWidthUpDown = new NumericUpDown
+        {
+            Value = _hexView.AddressWidth
+        };
+
+        NumericUpDown<long> addressUpDown = new NumericUpDown<long>
+        {
+            Value = _hexView.Address,
+            Format = $"0x{{0:X{_hexView.AddressWidth}}}"
+        };
+
+        addressWidthUpDown.ValueChanging += (sender, args) =>
+                                            {
+                                                args.Cancel = args.NewValue is < 0 or > 8;
+
+                                                if (!args.Cancel)
+                                                {
+                                                    _hexView.AddressWidth = args.NewValue;
+
+                                                    // ReSharper disable once AccessToDisposedClosure
+                                                    addressUpDown.Format = $"0x{{0:X{_hexView.AddressWidth}}}";
+                                                }
+                                            };
+
+        addressUpDown.ValueChanging += (sender, args) =>
+                                       {
+                                           args.Cancel = args.NewValue is < 0;
+
+                                           if (!args.Cancel)
+                                           {
+                                               _hexView.Address = args.NewValue;
+                                           }
+                                       };
+
+        _statusBar = new (
+                          [
+                              new (Key.F2, "Open", Open),
+                              new (Key.F3, "Save", Save),
+                              new ()
+                              {
+                                  CommandView = addressWidthUpDown,
+                                  HelpText = "Address Width"
+                              },
+                              _scAddress = new ()
+                              {
+                                  CommandView = addressUpDown,
+                                  HelpText = "Address:"
+                              },
+                              _scInfo = new (Key.Empty, string.Empty, () => { }),
+                              _scPosition = new (Key.Empty, string.Empty, () => { })
+                          ])
         {
             AlignmentModes = AlignmentModes.IgnoreFirstOrLast
         };
@@ -119,6 +148,8 @@ public class HexEditor : Scenario
         _hexView.Source = LoadFile ();
 
         Application.Run (app);
+        addressUpDown.Dispose ();
+        addressWidthUpDown.Dispose ();
         app.Dispose ();
         Application.Shutdown ();
     }
@@ -127,8 +158,15 @@ public class HexEditor : Scenario
 
     private void _hexView_PositionChanged (object sender, HexViewEventArgs obj)
     {
-        _siPositionChanged.Title =
-            $"Position: {obj.Position} Line: {obj.CursorPosition.Y} Col: {obj.CursorPosition.X} Line length: {obj.BytesPerLine}";
+        _scInfo.Title =
+            $"Bytes: {_hexView.Source!.Length}";
+        _scPosition.Title =
+            $"L: {obj.Position.Y} C: {obj.Position.X} Per Line: {obj.BytesPerLine}";
+
+        if (_scAddress.CommandView is NumericUpDown<long> addrNumericUpDown)
+        {
+            addrNumericUpDown.Value = obj.Address;
+        }
     }
 
     private void Copy () { MessageBox.ErrorQuery ("Not Implemented", "Functionality not yet implemented.", "Ok"); }
@@ -147,7 +185,7 @@ public class HexEditor : Scenario
     private void CreateUnicodeDemoFile (string fileName)
     {
         var sb = new StringBuilder ();
-        sb.Append ("Hello world.\n");
+        sb.Append ("Hello world with wide codepoints: 𝔹Aℝ𝔽.\n");
         sb.Append ("This is a test of the Emergency Broadcast System.\n");
 
         byte [] buffer = Encoding.Unicode.GetBytes (sb.ToString ());
@@ -169,8 +207,8 @@ public class HexEditor : Scenario
             if (MessageBox.ErrorQuery (
                                        "Save",
                                        "The changes were not saved. Want to open without saving?",
-                                       "Yes",
-                                       "No"
+                                       "_Yes",
+                                       "_No"
                                       )
                 == 1)
             {
@@ -190,7 +228,7 @@ public class HexEditor : Scenario
         }
         else
         {
-            _hexView.Title = (_fileName ?? "Untitled");
+            _hexView.Title = _fileName ?? "Untitled";
         }
 
         return stream;
@@ -213,10 +251,11 @@ public class HexEditor : Scenario
             _hexView.Source = LoadFile ();
             _hexView.DisplayStart = 0;
         }
+
         d.Dispose ();
     }
 
-    private void Paste () { MessageBox.ErrorQuery ("Not Implemented", "Functionality not yet implemented.", "Ok"); }
+    private void Paste () { MessageBox.ErrorQuery ("Not Implemented", "Functionality not yet implemented.", "_Ok"); }
     private void Quit () { Application.RequestStop (); }
 
     private void Save ()

+ 1 - 1
UICatalog/Scenarios/Text.cs

@@ -177,7 +177,7 @@ public class Text : Scenario
                          new MemoryStream (Encoding.UTF8.GetBytes ("HexEditor Unicode that shouldn't 𝔹Aℝ𝔽!"))
                         )
             {
-                X = Pos.Right (label) + 1, Y = Pos.Bottom (chxMultiline) + 1, Width = Dim.Percent (50) - 1, Height = Dim.Percent (30)
+                X = Pos.Right (label) + 1, Y = Pos.Bottom (chxMultiline) + 1, Width = Dim.Percent (50) - 1, Height = Dim.Percent (30),
             };
         win.Add (hexEditor);
 

+ 1 - 0
UICatalog/UICatalog.cs

@@ -387,6 +387,7 @@ public class UICatalogApp
         // 'app' closed cleanly.
         foreach (Responder? inst in Responder.Instances)
         {
+            
             Debug.Assert (inst.WasDisposed);
         }
 

+ 3 - 3
UnitTests/Application/Application.NavigationTests.cs

@@ -68,7 +68,7 @@ public class ApplicationNavigationTests (ITestOutputHelper output)
 
         Application.Navigation.FocusedChanged += ApplicationNavigationOnFocusedChanged;
 
-        Application.Navigation.SetFocused (new ());
+        Application.Navigation.SetFocused (new () { CanFocus = true, HasFocus = true });
 
         Assert.True (raised);
 
@@ -89,7 +89,7 @@ public class ApplicationNavigationTests (ITestOutputHelper output)
     {
         Application.Navigation = new ();
 
-        Application.Top = new()
+        Application.Top = new ()
         {
             Id = "top",
             CanFocus = true
@@ -125,7 +125,7 @@ public class ApplicationNavigationTests (ITestOutputHelper output)
     {
         Application.Navigation = new ();
 
-        Application.Top = new()
+        Application.Top = new ()
         {
             Id = "top",
             CanFocus = true

+ 4 - 4
UnitTests/Application/ApplicationTests.cs

@@ -939,10 +939,10 @@ public class ApplicationTests
         w.Dispose ();
         Assert.True (w.WasDisposed);
 
-        exception = Record.Exception (
-                                      () => Application.Run (
-                                                             w)); // Invalid - w has been disposed. Run it in debug mode will throw, otherwise the user may want to run it again
-        Assert.NotNull (exception);
+        //exception = Record.Exception (
+        //                              () => Application.Run (
+        //                                                     w)); // Invalid - w has been disposed. Run it in debug mode will throw, otherwise the user may want to run it again
+        //Assert.NotNull (exception);
 
         exception = Record.Exception (() => Assert.Equal (string.Empty, w.Title)); // Invalid - w has been disposed and cannot be accessed
         Assert.NotNull (exception);

+ 4 - 6
UnitTests/View/Navigation/NavigationTests.cs

@@ -66,7 +66,6 @@ public class NavigationTests (ITestOutputHelper _output) : TestsAllViews
                         // Try once more (HexView)
                         Application.RaiseKeyDownEvent (key);
                     }
-
                     break;
                 default:
                     Application.RaiseKeyDownEvent (Key.Tab);
@@ -78,12 +77,11 @@ public class NavigationTests (ITestOutputHelper _output) : TestsAllViews
             {
                 left = true;
                 _output.WriteLine ($"{view.GetType ().Name} - {key} Left.");
-                view.SetFocus ();
-            }
-            else
-            {
-                _output.WriteLine ($"{view.GetType ().Name} - {key} did not Leave.");
+
+                break;
             }
+
+            _output.WriteLine ($"{view.GetType ().Name} - {key} did not Leave.");
         }
 
         top.Dispose ();

+ 209 - 209
UnitTests/Views/HexViewTests.cs

@@ -1,36 +1,65 @@
-using System.Text;
+#nullable enable
+using System.Text;
+using JetBrains.Annotations;
 
 namespace Terminal.Gui.ViewsTests;
 
 public class HexViewTests
 {
+    [Theory]
+    [InlineData (0, 4)]
+    [InlineData (4, 4)]
+    [InlineData (8, 4)]
+    [InlineData (35, 4)]
+    [InlineData (36, 8)]
+    [InlineData (37, 8)]
+    [InlineData (41, 8)]
+    [InlineData (54, 12)]
+    [InlineData (55, 12)]
+    [InlineData (71, 12)]
+    [InlineData (72, 16)]
+    [InlineData (73, 16)]
+    public void BytesPerLine_Calculates_Correctly (int width, int expectedBpl)
+    {
+        var hv = new HexView (LoadStream (null, out long _)) { Width = width, Height = 10, AddressWidth = 0 };
+        hv.LayoutSubviews ();
+
+        Assert.Equal (expectedBpl, hv.BytesPerLine);
+    }
+
     [Fact]
     public void AllowEdits_Edits_ApplyEdits ()
     {
-        var hv = new HexView (LoadStream (true)) { Width = 20, Height = 20 };
+        var hv = new HexView (LoadStream (null, out _, true)) { Width = 20, Height = 20 };
+        Application.Navigation = new ApplicationNavigation ();
+        Application.Top = new Toplevel ();
+        Application.Top.Add (hv);
+        Application.Top.SetFocus ();
 
         // Needed because HexView relies on LayoutComplete to calc sizes
         hv.LayoutSubviews ();
 
+        Assert.True (Application.RaiseKeyDownEvent (Key.Tab)); // Move to left side
+
         Assert.Empty (hv.Edits);
         hv.AllowEdits = false;
-        Assert.True (hv.NewKeyDownEvent (Key.Home));
-        Assert.False (hv.NewKeyDownEvent (Key.A));
+        Assert.True (Application.RaiseKeyDownEvent (Key.Home));
+        Assert.False (Application.RaiseKeyDownEvent (Key.A));
         Assert.Empty (hv.Edits);
-        Assert.Equal (126, hv.Source.Length);
+        Assert.Equal (126, hv.Source!.Length);
 
         hv.AllowEdits = true;
-        Assert.True (hv.NewKeyDownEvent (Key.D4));
-        Assert.True (hv.NewKeyDownEvent (Key.D1));
+        Assert.True (Application.RaiseKeyDownEvent (Key.D4));
+        Assert.True (Application.RaiseKeyDownEvent (Key.D1));
         Assert.Single (hv.Edits);
         Assert.Equal (65, hv.Edits.ToList () [0].Value);
         Assert.Equal ('A', (char)hv.Edits.ToList () [0].Value);
         Assert.Equal (126, hv.Source.Length);
 
         // Appends byte
-        Assert.True (hv.NewKeyDownEvent (Key.End));
-        Assert.True (hv.NewKeyDownEvent (Key.D4));
-        Assert.True (hv.NewKeyDownEvent (Key.D2));
+        Assert.True (Application.RaiseKeyDownEvent (Key.End));
+        Assert.True (Application.RaiseKeyDownEvent (Key.D4));
+        Assert.True (Application.RaiseKeyDownEvent (Key.D2));
         Assert.Equal (2, hv.Edits.Count);
         Assert.Equal (66, hv.Edits.ToList () [1].Value);
         Assert.Equal ('B', (char)hv.Edits.ToList () [1].Value);
@@ -39,11 +68,18 @@ public class HexViewTests
         hv.ApplyEdits ();
         Assert.Empty (hv.Edits);
         Assert.Equal (127, hv.Source.Length);
+
+        Application.Top.Dispose ();
+        Application.ResetState (true);
+
     }
 
     [Fact]
     public void ApplyEdits_With_Argument ()
     {
+        Application.Navigation = new ApplicationNavigation ();
+        Application.Top = new Toplevel ();
+
         byte [] buffer = Encoding.Default.GetBytes ("Fest");
         var original = new MemoryStream ();
         original.Write (buffer, 0, buffer.Length);
@@ -53,28 +89,40 @@ public class HexViewTests
         original.CopyTo (copy);
         copy.Flush ();
         var hv = new HexView (copy) { Width = Dim.Fill (), Height = Dim.Fill () };
+        Application.Top.Add (hv);
+        Application.Top.SetFocus ();
 
         // Needed because HexView relies on LayoutComplete to calc sizes
         hv.LayoutSubviews ();
 
-        var readBuffer = new byte [hv.Source.Length];
+        var readBuffer = new byte [hv.Source!.Length];
         hv.Source.Position = 0;
         hv.Source.Read (readBuffer);
         Assert.Equal ("Fest", Encoding.Default.GetString (readBuffer));
 
-        Assert.True (hv.NewKeyDownEvent (Key.D5));
-        Assert.True (hv.NewKeyDownEvent (Key.D4));
+        Assert.True (Application.RaiseKeyDownEvent (Key.Tab)); // Move to left side
+        Assert.True (Application.RaiseKeyDownEvent (Key.D5));
+        Assert.True (Application.RaiseKeyDownEvent (Key.D4));
         readBuffer [hv.Edits.ToList () [0].Key] = hv.Edits.ToList () [0].Value;
         Assert.Equal ("Test", Encoding.Default.GetString (readBuffer));
 
+        Assert.True (Application.RaiseKeyDownEvent (Key.Tab)); // Move to right side
+        Assert.True (Application.RaiseKeyDownEvent (Key.CursorLeft)); 
+        Assert.True (Application.RaiseKeyDownEvent (Key.Z.WithShift));
+        readBuffer [hv.Edits.ToList () [0].Key] = hv.Edits.ToList () [0].Value;
+        Assert.Equal ("Zest", Encoding.Default.GetString (readBuffer));
+
         hv.ApplyEdits (original);
         original.Position = 0;
         original.Read (buffer);
         copy.Position = 0;
         copy.Read (readBuffer);
-        Assert.Equal ("Test", Encoding.Default.GetString (buffer));
-        Assert.Equal ("Test", Encoding.Default.GetString (readBuffer));
+        Assert.Equal ("Zest", Encoding.Default.GetString (buffer));
+        Assert.Equal ("Zest", Encoding.Default.GetString (readBuffer));
         Assert.Equal (Encoding.Default.GetString (buffer), Encoding.Default.GetString (readBuffer));
+
+        Application.Top.Dispose ();
+        Application.ResetState (true);
     }
 
     [Fact]
@@ -94,69 +142,84 @@ public class HexViewTests
     }
 
     [Fact]
-    [AutoInitShutdown]
-    public void CursorPosition_Encoding_Default ()
+    public void Position_Encoding_Default ()
     {
-        var hv = new HexView (LoadStream ()) { Width = Dim.Fill (), Height = Dim.Fill () };
-        var top = new Toplevel ();
-        top.Add (hv);
-        Application.Begin (top);
+        Application.Navigation = new ApplicationNavigation ();
 
-        Assert.Equal (new (1, 1), hv.CursorPosition);
+        var hv = new HexView (LoadStream (null, out _)) { Width = 100, Height = 100 };
+        Application.Top = new Toplevel ();
+        Application.Top.Add (hv);
 
-        Assert.True (hv.NewKeyDownEvent (Key.Tab));
-        Assert.True (hv.NewKeyDownEvent (Key.CursorRight.WithCtrl));
-        Assert.Equal (hv.CursorPosition.X, hv.BytesPerLine);
-        Assert.True (hv.NewKeyDownEvent (Key.Home));
+        Application.Top.LayoutSubviews ();
 
-        Assert.True (hv.NewKeyDownEvent (Key.CursorRight));
-        Assert.Equal (new (2, 1), hv.CursorPosition);
+        Assert.Equal (63, hv.Source!.Length);
+        Assert.Equal (20, hv.BytesPerLine);
 
-        Assert.True (hv.NewKeyDownEvent (Key.CursorDown));
-        Assert.Equal (new (2, 2), hv.CursorPosition);
+        Assert.Equal (new (0, 0), hv.Position);
 
-        Assert.True (hv.NewKeyDownEvent (Key.End));
-        int col = hv.CursorPosition.X;
-        int line = hv.CursorPosition.Y;
-        int offset = (line - 1) * (hv.BytesPerLine - col);
-        Assert.Equal (hv.Position, col * line + offset);
-        top.Dispose ();
+        Assert.True (Application.RaiseKeyDownEvent (Key.Tab));
+        Assert.Equal (new (0, 0), hv.Position);
+
+        Assert.True (Application.RaiseKeyDownEvent (Key.CursorRight.WithCtrl));
+        Assert.Equal (hv.BytesPerLine - 1, hv.Position.X);
+
+        Assert.True (Application.RaiseKeyDownEvent (Key.Home));
+
+        Assert.True (Application.RaiseKeyDownEvent (Key.CursorRight));
+        Assert.Equal (new (1, 0), hv.Position);
+
+        Assert.True (Application.RaiseKeyDownEvent (Key.CursorDown));
+        Assert.Equal (new (1, 1), hv.Position);
+
+        Assert.True (Application.RaiseKeyDownEvent (Key.End));
+        Assert.Equal (new (3, 3), hv.Position);
+
+        Assert.Equal (hv.Source!.Length, hv.Address);
+        Application.Top.Dispose ();
+        Application.ResetState (true);
     }
 
     [Fact]
-    [AutoInitShutdown]
-    public void CursorPosition_Encoding_Unicode ()
+    public void Position_Encoding_Unicode ()
     {
-        var hv = new HexView (LoadStream (true)) { Width = Dim.Fill (), Height = Dim.Fill () };
-        var top = new Toplevel ();
-        top.Add (hv);
-        Application.Begin (top);
+        Application.Navigation = new ApplicationNavigation ();
 
-        Assert.Equal (new (1, 1), hv.CursorPosition);
+        var hv = new HexView (LoadStream (null, out _, unicode: true)) { Width = 100, Height = 100 };
+        Application.Top = new Toplevel ();
+        Application.Top.Add (hv);
 
-        Assert.True (hv.NewKeyDownEvent (Key.Tab));
-        Assert.True (hv.NewKeyDownEvent (Key.CursorRight.WithCtrl));
-        Assert.Equal (hv.CursorPosition.X, hv.BytesPerLine);
-        Assert.True (hv.NewKeyDownEvent (Key.Home));
+        hv.LayoutSubviews ();
 
-        Assert.True (hv.NewKeyDownEvent (Key.CursorRight));
-        Assert.Equal (new (2, 1), hv.CursorPosition);
+        Assert.Equal (126, hv.Source!.Length);
+        Assert.Equal (20, hv.BytesPerLine);
 
-        Assert.True (hv.NewKeyDownEvent (Key.CursorDown));
-        Assert.Equal (new (2, 2), hv.CursorPosition);
+        Assert.Equal (new (0, 0), hv.Position);
 
-        Assert.True (hv.NewKeyDownEvent (Key.End));
-        int col = hv.CursorPosition.X;
-        int line = hv.CursorPosition.Y;
-        int offset = (line - 1) * (hv.BytesPerLine - col);
-        Assert.Equal (hv.Position, col * line + offset);
-        top.Dispose ();
+        Assert.True (Application.RaiseKeyDownEvent (Key.Tab));
+
+        Assert.True (Application.RaiseKeyDownEvent (Key.CursorRight.WithCtrl));
+        Assert.Equal (hv.BytesPerLine - 1, hv.Position.X);
+
+        Assert.True (Application.RaiseKeyDownEvent (Key.Home));
+
+        Assert.True (Application.RaiseKeyDownEvent (Key.CursorRight));
+        Assert.Equal (new (1, 0), hv.Position);
+
+        Assert.True (Application.RaiseKeyDownEvent (Key.CursorDown));
+        Assert.Equal (new (1, 1), hv.Position);
+
+        Assert.True (Application.RaiseKeyDownEvent (Key.End));
+        Assert.Equal (new (6, 6), hv.Position);
+
+        Assert.Equal (hv.Source!.Length, hv.Address);
+        Application.Top.Dispose ();
+        Application.ResetState (true);
     }
 
     [Fact]
     public void DiscardEdits_Method ()
     {
-        var hv = new HexView (LoadStream (true)) { Width = 20, Height = 20 };
+        var hv = new HexView (LoadStream (null, out _, true)) { Width = 20, Height = 20 };
 
         // Needed because HexView relies on LayoutComplete to calc sizes
         hv.LayoutSubviews ();
@@ -166,7 +229,7 @@ public class HexViewTests
         Assert.Single (hv.Edits);
         Assert.Equal (65, hv.Edits.ToList () [0].Value);
         Assert.Equal ('A', (char)hv.Edits.ToList () [0].Value);
-        Assert.Equal (126, hv.Source.Length);
+        Assert.Equal (126, hv.Source!.Length);
 
         hv.DiscardEdits ();
         Assert.Empty (hv.Edits);
@@ -175,7 +238,7 @@ public class HexViewTests
     [Fact]
     public void DisplayStart_Source ()
     {
-        var hv = new HexView (LoadStream (true)) { Width = 20, Height = 20 };
+        var hv = new HexView (LoadStream (null, out _, true)) { Width = 20, Height = 20 };
 
         // Needed because HexView relies on LayoutComplete to calc sizes
         hv.LayoutSubviews ();
@@ -184,7 +247,7 @@ public class HexViewTests
 
         Assert.True (hv.NewKeyDownEvent (Key.PageDown));
         Assert.Equal (4 * hv.Frame.Height, hv.DisplayStart);
-        Assert.Equal (hv.Source.Length, hv.Source.Position);
+        Assert.Equal (hv.Source!.Length, hv.Source.Position);
 
         Assert.True (hv.NewKeyDownEvent (Key.End));
 
@@ -196,13 +259,13 @@ public class HexViewTests
     [Fact]
     public void Edited_Event ()
     {
-        var hv = new HexView (LoadStream (true)) { Width = 20, Height = 20 };
+        var hv = new HexView (LoadStream (null, out _, true)) { Width = 20, Height = 20 };
 
         // Needed because HexView relies on LayoutComplete to calc sizes
         hv.LayoutSubviews ();
 
         KeyValuePair<long, byte> keyValuePair = default;
-        hv.Edited += (s, e) => keyValuePair = new (e.Position, e.NewValue);
+        hv.Edited += (s, e) => keyValuePair = new (e.Address, e.NewValue);
 
         Assert.True (hv.NewKeyDownEvent (Key.D4));
         Assert.True (hv.NewKeyDownEvent (Key.D6));
@@ -220,231 +283,168 @@ public class HexViewTests
     }
 
     [Fact]
-    [AutoInitShutdown]
-    public void KeyBindings_Command ()
+    public void KeyBindings_Test_Movement_LeftSide ()
     {
-        var hv = new HexView (LoadStream ()) { Width = 20, Height = 10 };
-        var top = new Toplevel ();
-        top.Add (hv);
-        Application.Begin (top);
+        Application.Navigation = new ApplicationNavigation ();
+        Application.Top = new Toplevel ();
+        var hv = new HexView (LoadStream (null, out _)) { Width = 20, Height = 10 };
+        Application.Top.Add (hv);
 
-        Assert.Equal (63, hv.Source.Length);
-        Assert.Equal (1, hv.Position);
-        Assert.Equal (4, hv.BytesPerLine);
-
-        // right side only needed to press one time
-        Assert.True (hv.NewKeyDownEvent (Key.Tab));
+        hv.LayoutSubviews ();
 
-        Assert.True (hv.NewKeyDownEvent (Key.CursorRight));
-        Assert.Equal (2, hv.Position);
+        Assert.Equal (MEM_STRING_LENGTH, hv.Source!.Length);
+        Assert.Equal (0, hv.Address);
+        Assert.Equal (4, hv.BytesPerLine);
 
-        Assert.True (hv.NewKeyDownEvent (Key.CursorLeft));
-        Assert.Equal (1, hv.Position);
+        // Default internal focus is on right side. Move back to left.
+        Assert.True (Application.RaiseKeyDownEvent (Key.Tab.WithShift));
 
-        Assert.True (hv.NewKeyDownEvent (Key.CursorDown));
-        Assert.Equal (5, hv.Position);
+        Assert.True (Application.RaiseKeyDownEvent (Key.CursorRight));
+        Assert.Equal (1, hv.Address);
 
-        Assert.True (hv.NewKeyDownEvent (Key.CursorUp));
-        Assert.Equal (1, hv.Position);
+        Assert.True (Application.RaiseKeyDownEvent (Key.CursorLeft));
+        Assert.Equal (0, hv.Address);
 
-        Assert.True (hv.NewKeyDownEvent (Key.V.WithCtrl));
-        Assert.Equal (41, hv.Position);
+        Assert.True (Application.RaiseKeyDownEvent (Key.CursorDown));
+        Assert.Equal (4, hv.Address);
 
-        Assert.True (hv.NewKeyDownEvent (new (Key.V.WithAlt)));
-        Assert.Equal (1, hv.Position);
+        Assert.True (Application.RaiseKeyDownEvent (Key.CursorUp));
+        Assert.Equal (0, hv.Address);
 
-        Assert.True (hv.NewKeyDownEvent (Key.PageDown));
-        Assert.Equal (41, hv.Position);
+        Assert.True (Application.RaiseKeyDownEvent (Key.PageDown));
+        Assert.Equal (40, hv.Address);
 
-        Assert.True (hv.NewKeyDownEvent (Key.PageUp));
-        Assert.Equal (1, hv.Position);
+        Assert.True (Application.RaiseKeyDownEvent (Key.PageUp));
+        Assert.Equal (0, hv.Address);
 
-        Assert.True (hv.NewKeyDownEvent (Key.End));
-        Assert.Equal (64, hv.Position);
+        Assert.True (Application.RaiseKeyDownEvent (Key.End));
+        Assert.Equal (MEM_STRING_LENGTH, hv.Address);
 
-        Assert.True (hv.NewKeyDownEvent (Key.Home));
-        Assert.Equal (1, hv.Position);
+        Assert.True (Application.RaiseKeyDownEvent (Key.Home));
+        Assert.Equal (0, hv.Address);
 
-        Assert.True (hv.NewKeyDownEvent (Key.CursorRight.WithCtrl));
-        Assert.Equal (4, hv.Position);
+        Assert.True (Application.RaiseKeyDownEvent (Key.CursorRight.WithCtrl));
+        Assert.Equal (3, hv.Address);
 
-        Assert.True (hv.NewKeyDownEvent (Key.CursorLeft.WithCtrl));
-        Assert.Equal (1, hv.Position);
+        Assert.True (Application.RaiseKeyDownEvent (Key.CursorLeft.WithCtrl));
+        Assert.Equal (0, hv.Address);
 
-        Assert.True (hv.NewKeyDownEvent (Key.CursorDown.WithCtrl));
-        Assert.Equal (37, hv.Position);
+        Assert.True (Application.RaiseKeyDownEvent (Key.CursorDown.WithCtrl));
+        Assert.Equal (36, hv.Address);
 
-        Assert.True (hv.NewKeyDownEvent (Key.CursorUp.WithCtrl));
-        Assert.Equal (1, hv.Position);
-        top.Dispose ();
+        Assert.True (Application.RaiseKeyDownEvent (Key.CursorUp.WithCtrl));
+        Assert.Equal (0, hv.Address);
+        Application.Top.Dispose ();
+        Application.ResetState (true);
     }
 
     [Fact]
-    public void Position_Using_Encoding_Default ()
+    public void PositionChanged_Event ()
     {
-        var hv = new HexView (LoadStream ()) { Width = 20, Height = 20 };
-
-        // Needed because HexView relies on LayoutComplete to calc sizes
-        hv.LayoutSubviews ();
-        Assert.Equal (63, hv.Source.Length);
-        Assert.Equal (63, hv.Source.Position);
-        Assert.Equal (1, hv.Position);
-
-        // left side needed to press twice
-        Assert.True (hv.NewKeyDownEvent (Key.CursorRight));
-        Assert.Equal (63, hv.Source.Position);
-        Assert.Equal (1, hv.Position);
-        Assert.True (hv.NewKeyDownEvent (Key.CursorRight));
-        Assert.Equal (63, hv.Source.Position);
-        Assert.Equal (2, hv.Position);
-
-        // right side only needed to press one time
-        Assert.True (hv.NewKeyDownEvent (Key.Tab));
-        Assert.Equal (63, hv.Source.Position);
-        Assert.Equal (2, hv.Position);
-        Assert.True (hv.NewKeyDownEvent (Key.CursorLeft));
-        Assert.Equal (63, hv.Source.Position);
-        Assert.Equal (1, hv.Position);
-
-        // last position is equal to the source length
-        Assert.True (hv.NewKeyDownEvent (Key.End));
-        Assert.Equal (63, hv.Source.Position);
-        Assert.Equal (64, hv.Position);
-        Assert.Equal (hv.Position - 1, hv.Source.Length);
-    }
+        var hv = new HexView (LoadStream (null, out _)) { Width = 20, Height = 10 };
+        Application.Top = new Toplevel ();
+        Application.Top.Add (hv);
 
-    [Fact]
-    public void Position_Using_Encoding_Unicode ()
-    {
-        var hv = new HexView (LoadStream (true)) { Width = 20, Height = 20 };
+        Application.Top.LayoutSubviews ();
 
-        // Needed because HexView relies on LayoutComplete to calc sizes
-        hv.LayoutSubviews ();
-        Assert.Equal (126, hv.Source.Length);
-        Assert.Equal (126, hv.Source.Position);
-        Assert.Equal (1, hv.Position);
-
-        // left side needed to press twice
-        Assert.True (hv.NewKeyDownEvent (Key.CursorRight));
-        Assert.Equal (126, hv.Source.Position);
-        Assert.Equal (1, hv.Position);
-        Assert.True (hv.NewKeyDownEvent (Key.CursorRight));
-        Assert.Equal (126, hv.Source.Position);
-        Assert.Equal (2, hv.Position);
-
-        // right side only needed to press one time
-        Assert.True (hv.NewKeyDownEvent (Key.Tab));
-        Assert.Equal (126, hv.Source.Position);
-        Assert.Equal (2, hv.Position);
-        Assert.True (hv.NewKeyDownEvent (Key.CursorLeft));
-        Assert.Equal (126, hv.Source.Position);
-        Assert.Equal (1, hv.Position);
-
-        // last position is equal to the source length
-        Assert.True (hv.NewKeyDownEvent (Key.End));
-        Assert.Equal (126, hv.Source.Position);
-        Assert.Equal (127, hv.Position);
-        Assert.Equal (hv.Position - 1, hv.Source.Length);
-    }
-
-    [Fact]
-    [AutoInitShutdown]
-    public void PositionChanged_Event ()
-    {
-        var hv = new HexView (LoadStream ()) { Width = Dim.Fill (), Height = Dim.Fill () };
-        HexViewEventArgs hexViewEventArgs = null;
+        HexViewEventArgs hexViewEventArgs = null!;
         hv.PositionChanged += (s, e) => hexViewEventArgs = e;
-        var top = new Toplevel ();
-        top.Add (hv);
-        Application.Begin (top);
+
+        Assert.Equal (4, hv.BytesPerLine);
 
         Assert.True (hv.NewKeyDownEvent (Key.CursorRight)); // left side must press twice
         Assert.True (hv.NewKeyDownEvent (Key.CursorRight));
         Assert.True (hv.NewKeyDownEvent (Key.CursorDown));
 
-        Assert.Equal (12, hexViewEventArgs.BytesPerLine);
-        Assert.Equal (new (2, 2), hexViewEventArgs.CursorPosition);
-        Assert.Equal (14, hexViewEventArgs.Position);
-        top.Dispose ();
+        Assert.Equal (4, hexViewEventArgs.BytesPerLine);
+        Assert.Equal (new (1, 1), hexViewEventArgs.Position);
+        Assert.Equal (5, hexViewEventArgs.Address);
+        Application.Top.Dispose ();
+        Application.ResetState (true);
     }
 
     [Fact]
-    [AutoInitShutdown]
     public void Source_Sets_DisplayStart_And_Position_To_Zero_If_Greater_Than_Source_Length ()
     {
-        var hv = new HexView (LoadStream ()) { Width = 10, Height = 5 };
-        var top = new Toplevel ();
-        top.Add (hv);
-        Application.Begin (top);
+        var hv = new HexView (LoadStream (null, out _)) { Width = 10, Height = 5 };
+        Application.Top = new Toplevel ();
+        Application.Top.Add (hv);
+
+        hv.LayoutSubviews ();
 
         Assert.True (hv.NewKeyDownEvent (Key.End));
-        Assert.Equal (62, hv.DisplayStart);
-        Assert.Equal (64, hv.Position);
+        Assert.Equal (MEM_STRING_LENGTH - 1, hv.DisplayStart);
+        Assert.Equal (MEM_STRING_LENGTH, hv.Address);
 
         hv.Source = new MemoryStream ();
         Assert.Equal (0, hv.DisplayStart);
-        Assert.Equal (0, hv.Position - 1);
+        Assert.Equal (0, hv.Address);
 
-        hv.Source = LoadStream ();
+        hv.Source = LoadStream (null, out _);
         hv.Width = Dim.Fill ();
         hv.Height = Dim.Fill ();
-        top.LayoutSubviews ();
+        Application.Top.LayoutSubviews ();
         Assert.Equal (0, hv.DisplayStart);
-        Assert.Equal (0, hv.Position - 1);
+        Assert.Equal (0, hv.Address);
 
         Assert.True (hv.NewKeyDownEvent (Key.End));
         Assert.Equal (0, hv.DisplayStart);
-        Assert.Equal (64, hv.Position);
+        Assert.Equal (MEM_STRING_LENGTH, hv.Address);
 
         hv.Source = new MemoryStream ();
         Assert.Equal (0, hv.DisplayStart);
-        Assert.Equal (0, hv.Position - 1);
-        top.Dispose ();
+        Assert.Equal (0, hv.Address);
+        Application.Top.Dispose ();
+        Application.ResetState (true);
     }
 
-    private Stream LoadStream (bool unicode = false)
+    private const string MEM_STRING = "Hello world.\nThis is a test of the Emergency Broadcast System.\n";
+    private const int MEM_STRING_LENGTH = 63;
+
+    private Stream LoadStream (string? memString, out long numBytesInMemString, bool unicode = false)
     {
         var stream = new MemoryStream ();
         byte [] bArray;
-        var memString = "Hello world.\nThis is a test of the Emergency Broadcast System.\n";
 
-        Assert.Equal (63, memString.Length);
+        Assert.Equal (MEM_STRING_LENGTH, MEM_STRING.Length);
+
+        if (memString is null)
+        {
+            memString = MEM_STRING;
+        }
 
         if (unicode)
         {
             bArray = Encoding.Unicode.GetBytes (memString);
-            Assert.Equal (126, bArray.Length);
         }
         else
         {
             bArray = Encoding.Default.GetBytes (memString);
-            Assert.Equal (63, bArray.Length);
         }
+        numBytesInMemString = bArray.Length;
 
         stream.Write (bArray);
 
         return stream;
     }
 
-    private class NonSeekableStream : Stream
+    private class NonSeekableStream (Stream baseStream) : Stream
     {
-        private readonly Stream m_stream;
-        public NonSeekableStream (Stream baseStream) { m_stream = baseStream; }
-        public override bool CanRead => m_stream.CanRead;
+        public override bool CanRead => baseStream.CanRead;
         public override bool CanSeek => false;
-        public override bool CanWrite => m_stream.CanWrite;
+        public override bool CanWrite => baseStream.CanWrite;
         public override long Length => throw new NotSupportedException ();
 
         public override long Position
         {
-            get => m_stream.Position;
+            get => baseStream.Position;
             set => throw new NotSupportedException ();
         }
 
-        public override void Flush () { m_stream.Flush (); }
-        public override int Read (byte [] buffer, int offset, int count) { return m_stream.Read (buffer, offset, count); }
+        public override void Flush () { baseStream.Flush (); }
+        public override int Read (byte [] buffer, int offset, int count) { return baseStream.Read (buffer, offset, count); }
         public override long Seek (long offset, SeekOrigin origin) { throw new NotImplementedException (); }
         public override void SetLength (long value) { throw new NotSupportedException (); }
-        public override void Write (byte [] buffer, int offset, int count) { m_stream.Write (buffer, offset, count); }
+        public override void Write (byte [] buffer, int offset, int count) { baseStream.Write (buffer, offset, count); }
     }
 }

+ 2 - 1
UnitTests/Views/ScrollViewTests.cs

@@ -874,7 +874,8 @@ public class ScrollViewTests (ITestOutputHelper output)
             X = 3,
             Y = 3,
             Width = 10,
-            Height = 10
+            Height = 10,
+            TabStop = TabBehavior.TabStop
         };
         sv.SetContentSize (new (50, 50));
 

+ 4 - 4
docfx/docs/cursor.md

@@ -4,19 +4,19 @@ See end for list of issues this design addresses.
 
 ## Tenets for Cursor Support (Unless you know better ones...)
 
-1. **More GUI than Command Line**. The concept of a cursor on the command line of a terminal is intrinsically tied to enabling the user to know where keybaord import is going to impact text editing. TUI apps have many more modalities than text editing where the keyboard is used (e.g. scrolling through a `ColorPicker`). Terminal.Gui's cursor system is biased towards the broader TUI experiences.
+1. **More GUI than Command Line**. The concept of a cursor on the command line of a terminal is intrinsically tied to enabling the user to know where keyboard import is going to impact text editing. TUI apps have many more modalities than text editing where the keyboard is used (e.g. scrolling through a `ColorPicker`). Terminal.Gui's cursor system is biased towards the broader TUI experiences.
 
 2. **Be Consistent With the User's Platform** - Users get to choose the platform they run *Terminal.Gui* apps on and the cursor should behave in a way consistent with the terminal.
 
 ## Lexicon & Taxonomy
 
 - Navigation - Refers to the user-experience for moving Focus between views in the application view-hierarchy. See [Navigation](navigation.md) for a deep-dive.
-- Focus - Indicates which View in the view-hierarchy is currently the one receiving keyboard input. Only one view-heirachy in an applicstion can have focus (`view.HasFocus == true`), and there is only one View in a focused heirarchy that is the most-focused; the one recieving keyboard input. See [Navigation](navigation.md) for a deep-dive.
-- Cursor - A visual indicator to the user where keyboard input will have an impact. There is one Cursor per terminal sesssion.
+- Focus - Indicates which View in the view-hierarchy is currently the one receiving keyboard input. Only one view-hexarchy in an application can have focus (`view.HasFocus == true`), and there is only one View in a focused hierarchy that is the most-focused; the one receiving keyboard input. See [Navigation](navigation.md) for a deep-dive.
+- Cursor - A visual indicator to the user where keyboard input will have an impact. There is one Cursor per terminal session.
 - Cursor Location - The top-left corner of the Cursor. In text entry scenarios, new text will be inserted to the left/top of the Cursor Location. 
 - Cursor Size - The width and height of the cursor. Currently the size is limited to 1x1.
 - Cursor Style - How the cursor renders. Some terminals support various cursor styles such as Block and Underline.
-- Cursor Visibilty - Whether the cursor is visible to the user or not. NOTE: Some ConsoleDrivers overload Cursor Style and Cursor Visibility, making "invisible" a style. Terminal.Gui HIDES this from developers and changing the visibilty of the cursor does NOT change the style.
+- Cursor Visibility - Whether the cursor is visible to the user or not. NOTE: Some ConsoleDrivers overload Cursor Style and Cursor Visibility, making "invisible" a style. Terminal.Gui HIDES this from developers and changing the visibility of the cursor does NOT change the style.
 - Caret - Visual indicator that  where text entry will occur. 
 - Selection - A visual indicator to the user that something is selected. It is common for the Selection and Cursor to be the same. It is also common for the Selection and Cursor to be distinct. In a `ListView` the Cursor and Selection (`SelectedItem`) are the same, but the `Cursor` is not visible. In a `TextView` with text selected, the `Cursor` is at either the start or end of the `Selection`. A `TableView' supports mutliple things being selected at once.
 

Some files were not shown because too many files changed in this diff