Tig 1 month ago
parent
commit
6a9dfb1f34
42 changed files with 2858 additions and 1953 deletions
  1. 4 2
      .github/copilot-instructions.md
  2. 4 1
      Examples/UICatalog/Scenarios/AnimationScenario/AnimationScenario.cs
  3. 0 1
      Examples/UICatalog/Scenarios/Arrangement.cs
  4. 0 1
      Examples/UICatalog/Scenarios/Clipping.cs
  5. 0 2
      Examples/UICatalog/Scenarios/ProgressBarStyles.cs
  6. 0 1
      Examples/UICatalog/Scenarios/Shortcuts.cs
  7. 1 1
      Terminal.Gui/App/Application.Lifecycle.cs
  8. 0 20
      Terminal.Gui/App/Application.Run.cs
  9. 0 3
      Terminal.Gui/App/Application.cs
  10. 0 24
      Terminal.Gui/App/MainLoop/IMainLoopDriver.cs
  11. 0 122
      Terminal.Gui/App/MainLoop/LegacyMainLoopDriver.cs
  12. 2 17
      Terminal.Gui/App/MainLoop/MainLoopSyncContext.cs
  13. 56 2
      Terminal.Gui/Drivers/AnsiHandling/EscSeqUtils/EscSeqUtils.cs
  14. 345 0
      Terminal.Gui/Drivers/AnsiHandling/Osc8UrlLinker.cs
  15. 1 2
      Terminal.Gui/Drivers/ConsoleDriver.cs
  16. 1 1
      Terminal.Gui/Drivers/ConsoleDriverFacade.cs
  17. 1 27
      Terminal.Gui/Drivers/FakeDriver/FakeDriver.cs
  18. 0 38
      Terminal.Gui/Drivers/FakeDriver/FakeMainLoop.cs
  19. 1 2
      Terminal.Gui/Drivers/IConsoleDriver.cs
  20. 48 53
      Terminal.Gui/Drivers/OutputBase.cs
  21. 2 1
      Terminal.sln.ToDo.DotSettings
  22. 0 17
      Tests/UnitTests/Application/ApplicationTests.cs
  23. 0 940
      Tests/UnitTests/Application/MainLoopTests.cs
  24. 0 1
      Tests/UnitTests/Application/RunStateTests.cs
  25. 2 2
      Tests/UnitTests/ConsoleDrivers/ConsoleDriverTests.cs
  26. 0 1
      Tests/UnitTests/View/Draw/AllViewsDrawTests.cs
  27. 0 1
      Tests/UnitTests/View/Layout/LayoutTests.cs
  28. 0 1
      Tests/UnitTests/Views/AllViewsTests.cs
  29. 0 2
      Tests/UnitTests/Views/Menuv1/MenuBarv1Tests.cs
  30. 0 300
      Tests/UnitTestsParallelizable/ConsoleDrivers/MainLoopDriverTests.cs
  31. 170 0
      Tests/UnitTestsParallelizable/ConsoleDrivers/UrlHyperlinkerTests.cs
  32. 1 1
      Tests/UnitTestsParallelizable/MockConsoleDriver.cs
  33. 0 1
      Tests/UnitTestsParallelizable/TestSetup.cs
  34. 632 57
      docfx/docs/View.md
  35. 684 51
      docfx/docs/arrangement.md
  36. 807 217
      docfx/docs/config.md
  37. 2 0
      docfx/docs/drivers.md
  38. 16 7
      docfx/docs/migratingfromv1.md
  39. 72 27
      docfx/docs/newinv2.md
  40. 6 6
      docfx/includes/arrangement-lexicon.md
  41. BIN
      local_packages/Terminal.Gui.2.0.0.nupkg
  42. BIN
      local_packages/Terminal.Gui.2.0.0.snupkg

+ 4 - 2
.github/copilot-instructions.md

@@ -1,5 +1,7 @@
 # Terminal.Gui - CoPilot AI Rules
 
-> **📘 Source of Truth: [CONTRIBUTING.md](CONTRIBUTING.md)**
+> **📘 Source of Truth: [../CONTRIBUTING.md](../CONTRIBUTING.md)**
 
-This project uses [CONTRIBUTING.md](CONTRIBUTING.md) as the single source of truth for contribution guidelines. AI agents, including CoPilot and Cursor **MUST** follow the guidelines in [CONTRIBUTING.md](CONTRIBUTING.md)/
+This project uses [../CONTRIBUTING.md](../CONTRIBUTING.md) as the single source of truth for contribution guidelines. AI agents, including CoPilot and Cursor **MUST** follow the guidelines in [../CONTRIBUTING.md](CONTRIBUTING.md)/
+
+**CRITICAL** - CoPilot you MUST internalize [../CONTRIBUTING.md](../CONTRIBUTING.md) and follow the guidance for any work you do on Terminal.Gui. This includes Github Copilot in Agent mode. 

+ 4 - 1
Examples/UICatalog/Scenarios/AnimationScenario/AnimationScenario.cs

@@ -40,7 +40,10 @@ public class AnimationScenario : Scenario
 
         var lbl2 = new Label
         {
-            X = Pos.AnchorEnd (), Y = Pos.AnchorEnd (), Text = "https://commons.wikimedia.org/wiki/File:Spinning_globe.gif"
+            // This ensures the URL that has an underscore is drawn correctly
+            HotKeySpecifier = new Rune ('\xFFFF'),
+            X = Pos.AnchorEnd (), Y = Pos.AnchorEnd (), 
+            Text = "https://commons.wikimedia.org/wiki/File:Spinning_globe.gif"
         };
         win.Add (lbl2);
 

+ 0 - 1
Examples/UICatalog/Scenarios/Arrangement.cs

@@ -99,7 +99,6 @@ public class Arrangement : Scenario
 
                              progressBar.Fraction += 0.01f;
 
-                             Application.Wakeup ();
 
                              progressBar.SetNeedsDraw ();
                          };

+ 0 - 1
Examples/UICatalog/Scenarios/Clipping.cs

@@ -100,7 +100,6 @@ public class Clipping : Scenario
                                  {
                                      tiledProgressBar1.Pulse ();
                                      tiledProgressBar2.Pulse ();
-                                     Application.Wakeup ();
                                  };
 
         progressTimer.Start ();

+ 0 - 2
Examples/UICatalog/Scenarios/ProgressBarStyles.cs

@@ -198,7 +198,6 @@ public class ProgressBarStyles : Scenario
                                                                       button.Enabled = true;
                                                                   }
 
-                                                                  Application.Wakeup ();
                                                               },
                                                               null,
                                                               0,
@@ -282,7 +281,6 @@ public class ProgressBarStyles : Scenario
                                      marqueesBlocksPB.Text = marqueesContinuousPB.Text = DateTime.Now.TimeOfDay.ToString ();
                                      marqueesBlocksPB.Pulse ();
                                      marqueesContinuousPB.Pulse ();
-                                     Application.Wakeup ();
                                  },
                                  null,
                                  0,

+ 0 - 1
Examples/UICatalog/Scenarios/Shortcuts.cs

@@ -384,7 +384,6 @@ public class Shortcuts : Scenario
 
                                  pb.Fraction += 0.01f;
 
-                                 Application.Wakeup ();
 
                                  pb.SetNeedsDraw ();
                              }

+ 1 - 1
Terminal.Gui/App/Application.Lifecycle.cs

@@ -131,7 +131,7 @@ public static partial class Application // Lifecycle (Init/Shutdown)
 
         try
         {
-            MainLoop = Driver!.Init ();
+            Driver!.Init ();
             SubscribeDriverEvents ();
         }
         catch (InvalidOperationException ex)

+ 0 - 20
Terminal.Gui/App/Application.Run.cs

@@ -372,12 +372,6 @@ public static partial class Application // Run (Begin -> Run -> Layout/Draw -> E
     /// <param name="action">the action to be invoked on the main processing thread.</param>
     public static void Invoke (Action action) { ApplicationImpl.Instance.Invoke (action); }
 
-    // TODO: Determine if this is really needed. The only code that calls WakeUp I can find
-    // is ProgressBarStyles, and it's not clear it needs to.
-
-    /// <summary>Wakes up the running application that might be waiting on input.</summary>
-    public static void Wakeup () { MainLoop?.Wakeup (); }
-
     /// <summary>
     ///     Causes any Toplevels that need layout to be laid out. Then draws any Toplevels that need display. Only Views that
     ///     need to be laid out (see <see cref="View.NeedsLayout"/>) will be laid out.
@@ -396,10 +390,6 @@ public static partial class Application // Run (Begin -> Run -> Layout/Draw -> E
     /// <remarks>See also <see cref="Timeout"/></remarks>
     public static event EventHandler<IterationEventArgs>? Iteration;
 
-    /// <summary>The <see cref="MainLoop"/> driver for the application</summary>
-    /// <value>The main loop.</value>
-    internal static MainLoop? MainLoop { get; set; }
-
     /// <summary>
     ///     Set to true to cause <see cref="End"/> to be called after the first iteration. Set to false (the default) to
     ///     cause the application to continue running until Application.RequestStop () is called.
@@ -417,11 +407,6 @@ public static partial class Application // Run (Begin -> Run -> Layout/Draw -> E
 
         for (state.Toplevel.Running = true; state.Toplevel?.Running == true;)
         {
-            if (MainLoop is { })
-            {
-                MainLoop.Running = true;
-            }
-
             if (EndAfterFirstIteration && !firstIteration)
             {
                 return;
@@ -430,11 +415,6 @@ public static partial class Application // Run (Begin -> Run -> Layout/Draw -> E
             firstIteration = RunIteration (ref state, firstIteration);
         }
 
-        if (MainLoop is { })
-        {
-            MainLoop.Running = false;
-        }
-
         // Run one last iteration to consume any outstanding input events from Driver
         // This is important for remaining OnKeyUp events.
         RunIteration (ref state, firstIteration);

+ 0 - 3
Terminal.Gui/App/Application.cs

@@ -216,9 +216,6 @@ public static partial class Application
         Top = null;
         _cachedRunStateToplevel = null;
 
-        // MainLoop stuff
-        MainLoop?.Dispose ();
-        MainLoop = null;
         MainThreadId = -1;
         Iteration = null;
         EndAfterFirstIteration = false;

+ 0 - 24
Terminal.Gui/App/MainLoop/IMainLoopDriver.cs

@@ -1,24 +0,0 @@
-#nullable enable
-namespace Terminal.Gui.App;
-
-/// <summary>Interface to create a platform specific <see cref="MainLoop"/> driver.</summary>
-internal interface IMainLoopDriver
-{
-    /// <summary>Must report whether there are any events pending, or even block waiting for events.</summary>
-    /// <returns><see langword="true"/>, if there were pending events, <see langword="false"/> otherwise.</returns>
-    bool EventsPending ();
-
-    /// <summary>The iteration function.</summary>
-    void Iteration ();
-
-    /// <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>Tears down the <see cref="MainLoop"/> driver. Releases resources created in <see cref="Setup"/>.</summary>
-    void TearDown ();
-
-    /// <summary>Wakes up the <see cref="MainLoop"/> that might be waiting on input, must be thread safe.</summary>
-    void Wakeup ();
-}

+ 0 - 122
Terminal.Gui/App/MainLoop/LegacyMainLoopDriver.cs

@@ -1,122 +0,0 @@
-#nullable enable
-//
-// LegacyMainLoopDriver.cs: IMainLoopDriver and MainLoop for legacy v1 driver based applications
-//
-// Authors:
-//   Miguel de Icaza ([email protected])
-//
-
-using System.Collections.ObjectModel;
-
-namespace Terminal.Gui.App;
-
-/// <summary>
-///     The main event loop of legacy v1 driver based applications.
-/// </summary>
-/// <remarks>
-///     <para>
-///         This class is provided for backward compatibility with the legacy FakeDriver implementation.
-///         New code should use the modern <see cref="ApplicationMainLoop{T}"/> architecture instead.
-///     </para>
-///     <para>
-///         Monitoring of file descriptors is only available on Unix, there does not seem to be a way of supporting this
-///         on Windows.
-///     </para>
-/// </remarks>
-[Obsolete ("This class is for legacy FakeDriver compatibility only. Use ApplicationMainLoop<T> for new code.")]
-public class MainLoop : IDisposable
-{
-    /// <summary>
-    /// Gets the class responsible for handling timeouts
-    /// </summary>
-    public ITimedEvents TimedEvents { get; } = new TimedEvents();
-
-    /// <summary>Creates a new MainLoop.</summary>
-    /// <remarks>Use <see cref="Dispose"/> to release resources.</remarks>
-    /// <param name="driver">
-    ///     The <see cref="IConsoleDriver"/> instance (one of the implementations FakeMainLoop, UnixMainLoop,
-    ///     NetMainLoop or WindowsMainLoop).
-    /// </param>
-    internal MainLoop (IMainLoopDriver driver)
-    {
-        MainLoopDriver = driver;
-        driver.Setup (this);
-    }
-
-
-    /// <summary>The current <see cref="IMainLoopDriver"/> in use.</summary>
-    /// <value>The main loop driver.</value>
-    internal IMainLoopDriver? MainLoopDriver { get; private set; }
-
-    /// <summary>Used for unit tests.</summary>
-    internal bool Running { get; set; }
-
-
-    /// <inheritdoc/>
-    public void Dispose ()
-    {
-        GC.SuppressFinalize (this);
-        Stop ();
-        Running = false;
-        MainLoopDriver?.TearDown ();
-        MainLoopDriver = null;
-    }
-
-
-    /// <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 the <see cref="MainLoop"/>. Used only for unit tests.</summary>
-    internal void Run ()
-    {
-        bool prev = Running;
-        Running = true;
-
-        while (Running)
-        {
-            EventsPending ();
-            RunIteration ();
-        }
-
-        Running = prev;
-    }
-
-    /// <summary>Runs one iteration of timers and file watches</summary>
-    /// <remarks>
-    ///     Use this to process all pending events (timers handlers and file watches).
-    ///     <code>
-    ///     while (main.EventsPending ()) RunIteration ();
-    ///   </code>
-    /// </remarks>
-    internal void RunIteration ()
-    {
-        RunAnsiScheduler ();
-
-        MainLoopDriver?.Iteration ();
-
-        TimedEvents.RunTimers ();
-    }
-
-    private void RunAnsiScheduler ()
-    {
-        Application.Driver?.GetRequestScheduler ().RunSchedule ();
-    }
-
-    /// <summary>Stops the main loop driver and calls <see cref="IMainLoopDriver.Wakeup"/>. Used only for unit tests.</summary>
-    internal void Stop ()
-    {
-        Running = false;
-        Wakeup ();
-    }
-
-
-    /// <summary>Wakes up the <see cref="MainLoop"/> that might be waiting on input.</summary>
-    internal void Wakeup () { MainLoopDriver?.Wakeup (); }
-
-
-}

+ 2 - 17
Terminal.Gui/App/MainLoop/MainLoopSyncContext.cs

@@ -10,23 +10,8 @@ internal sealed class MainLoopSyncContext : SynchronizationContext
 
     public override void Post (SendOrPostCallback d, object state)
     {
-        // Queue the task
-        if (ApplicationImpl.Instance.IsLegacy)
-        {
-            Application.MainLoop?.TimedEvents.Add (TimeSpan.Zero,
-                                                   () =>
-                                                   {
-                                                       d (state);
-
-                                                       return false;
-                                                   }
-                                                  );
-            Application.MainLoop?.Wakeup ();
-        }
-        else
-        {
-            ApplicationImpl.Instance.Invoke (() => { d (state); });
-        }
+        // Queue the task using the modern architecture
+        ApplicationImpl.Instance.Invoke (() => { d (state); });
     }
 
     //_mainLoop.Driver.Wakeup ();

+ 56 - 2
Terminal.Gui/Drivers/AnsiHandling/EscSeqUtils/EscSeqUtils.cs

@@ -931,7 +931,7 @@ public static class EscSeqUtils
             _isButtonClicked = false;
             _isButtonDoubleClicked = true;
 
-            Application.MainLoop?.TimedEvents.Add (TimeSpan.Zero,
+            ApplicationImpl.Instance.TimedEvents?.Add (TimeSpan.Zero,
                                           () =>
                                           {
                                               Task.Run (async () => await ProcessButtonDoubleClickedAsync ());
@@ -970,7 +970,7 @@ public static class EscSeqUtils
                 mouseFlags.Add (GetButtonClicked (buttonState));
                 _isButtonClicked = true;
 
-                Application.MainLoop?.TimedEvents.Add (TimeSpan.Zero,
+                ApplicationImpl.Instance.TimedEvents?.Add (TimeSpan.Zero,
                                               () =>
                                               {
                                                   Task.Run (async () => await ProcessButtonClickedAsync ());
@@ -2076,4 +2076,58 @@ public static class EscSeqUtils
     public const string CSI_ReportTerminalSizeInChars_ResponseValue = "8";
 
     #endregion
+
+    #region OSC 8 Hyperlinks
+
+    /// <summary>
+    ///     OSC (Operating System Command) escape sequence prefix.
+    /// </summary>
+    /// <remarks>
+    ///     OSC sequences are used for operating system-specific commands like setting window title,
+    ///     hyperlinks (OSC 8), and other terminal emulator features.
+    /// </remarks>
+    public const string OSC = "\u001B]";
+
+    /// <summary>
+    ///     String Terminator (ST) - terminates OSC sequences.
+    /// </summary>
+    /// <remarks>
+    ///     Can also be represented as BEL (0x07) in some terminals, but ST is more modern.
+    /// </remarks>
+    public const string ST = "\u001B\\";
+
+    /// <summary>
+    ///     Starts a hyperlink using OSC 8 escape sequence.
+    /// </summary>
+    /// <param name="url">The URL to link to (e.g., "https://github.com").</param>
+    /// <param name="id">Optional hyperlink ID for matching start/end pairs. Use null for automatic matching.</param>
+    /// <returns>The OSC 8 start sequence.</returns>
+    /// <remarks>
+    ///     OSC 8 format: ESC ] 8 ; params ; URL ST
+    ///     Supported in Windows Terminal, iTerm2, and other modern terminals.
+    ///     Must be followed by visible text, then terminated with <see cref="OSC_EndHyperlink"/>.
+    /// </remarks>
+    public static string OSC_StartHyperlink (string url, string? id = null)
+    {
+        // Format: ESC ] 8 ; params ; URL ST
+        // params can include "id=value" for matching start/end
+        string parameters = string.IsNullOrEmpty (id) ? "" : $"id={id}";
+        return $"{OSC}8;{parameters};{url}{ST}";
+    }
+
+    /// <summary>
+    ///     Ends a hyperlink using OSC 8 escape sequence.
+    /// </summary>
+    /// <returns>The OSC 8 end sequence.</returns>
+    /// <remarks>
+    ///     This terminates the hyperlink started by <see cref="OSC_StartHyperlink"/>.
+    ///     Format: ESC ] 8 ; ; ST (empty URL ends the hyperlink).
+    /// </remarks>
+    public static string OSC_EndHyperlink ()
+    {
+        // Format: ESC ] 8 ; ; ST (empty URL ends hyperlink)
+        return $"{OSC}8;;{ST}";
+    }
+
+    #endregion
 }

+ 345 - 0
Terminal.Gui/Drivers/AnsiHandling/Osc8UrlLinker.cs

@@ -0,0 +1,345 @@
+#nullable enable
+
+namespace Terminal.Gui.Drivers;
+
+internal static class Osc8UrlLinker
+{
+    internal readonly struct Options
+    {
+        internal readonly string [] _allowedSchemes;
+        internal readonly bool _validateWithUri;
+
+        private Options (string [] allowedSchemes, bool validateWithUri)
+        {
+            _allowedSchemes = allowedSchemes;
+            _validateWithUri = validateWithUri;
+        }
+
+        public static Options CreateDefault ()
+        {
+            return new Options (
+                allowedSchemes: ["http", "https", "ftp", "ftps"],
+                validateWithUri: true
+            );
+        }
+    }
+
+    private static readonly Options _defaultOptions = Options.CreateDefault ();
+
+    internal static StringBuilder WrapOsc8 (StringBuilder input)
+    {
+        return WrapOsc8 (input, _defaultOptions);
+    }
+
+    internal static StringBuilder WrapOsc8 (StringBuilder input, Options options)
+    {
+        if (input is null || input.Length == 0)
+        {
+            return input;
+        }
+
+        string text = input.ToString ();
+        int len = text.Length;
+
+        StringBuilder? result = null;
+        int copyFrom = 0;
+
+        int i = 0;
+        while (i < len)
+        {
+            if (text [i] == '\x1B')
+            {
+                int escEnd = ParseEscapeSequence (text, i, len);
+                if (result != null)
+                {
+                    if (i > copyFrom)
+                    {
+                        result.Append (text, copyFrom, i - copyFrom);
+                    }
+
+                    result.Append (text, i, escEnd - i);
+                    copyFrom = escEnd;
+                }
+
+                i = escEnd;
+                continue;
+            }
+
+            int segStart = i;
+            int nextEsc = text.IndexOf ('\x1B', segStart);
+            if (nextEsc < 0)
+            {
+                nextEsc = len;
+            }
+
+            bool changed;
+            string processed = WrapPlainText (text, segStart, nextEsc, options, out changed);
+
+            if (changed)
+            {
+                result ??= new StringBuilder (text.Length + 100);
+
+                if (segStart > copyFrom)
+                {
+                    result.Append (text, copyFrom, segStart - copyFrom);
+                }
+
+                result.Append (processed);
+                copyFrom = nextEsc;
+            }
+
+            i = nextEsc;
+        }
+
+        if (result is null)
+        {
+            return input;
+        }
+
+        if (copyFrom < len)
+        {
+            result.Append (text, copyFrom, len - copyFrom);
+        }
+
+        return result;
+    }
+
+    private static int ParseEscapeSequence (string text, int start, int len)
+    {
+        int i = start;
+        if (i + 1 >= len)
+        {
+            return len;
+        }
+
+        char c1 = text [i + 1];
+
+        if (c1 == '[')
+        {
+            int j = i + 2;
+            while (j < len)
+            {
+                char ch = text [j++];
+                if (ch >= '@' && ch <= '~')
+                {
+                    break;
+                }
+            }
+
+            return j;
+        }
+
+        if (c1 == ']')
+        {
+            int j = i + 2;
+            while (j < len)
+            {
+                char ch = text [j++];
+                if (ch == '\x07')
+                {
+                    break;
+                }
+
+                if (ch == '\x1B')
+                {
+                    if (j < len && text [j] == '\\')
+                    {
+                        j++;
+                        break;
+                    }
+                }
+            }
+
+            return j;
+        }
+
+        return Math.Min (i + 2, len);
+    }
+
+    private static string WrapPlainText (string full, int start, int endExclusive, Options options, out bool changed)
+    {
+        ReadOnlySpan<char> span = full.AsSpan (start, endExclusive - start);
+        ReadOnlySpan<char> delimiter = "://".AsSpan ();
+        int i = 0;
+        int copyFrom = 0;
+        StringBuilder? sb = null;
+
+        while (i < span.Length)
+        {
+            int rel = span.Slice (i).IndexOf (delimiter, StringComparison.Ordinal);
+            if (rel < 0)
+            {
+                break;
+            }
+
+            int delimAt = i + rel;
+            int schemeEnd = delimAt;
+            int schemeStart = schemeEnd - 1;
+
+            while (schemeStart >= 0 && char.IsLetter (span [schemeStart]))
+            {
+                schemeStart--;
+            }
+
+            schemeStart++;
+
+            if (schemeStart < 0 || schemeStart >= schemeEnd)
+            {
+                i = delimAt + delimiter.Length;
+                continue;
+            }
+
+            ReadOnlySpan<char> scheme = span.Slice (schemeStart, schemeEnd - schemeStart);
+            if (!IsAllowedScheme (scheme, options))
+            {
+                i = delimAt + delimiter.Length;
+                continue;
+            }
+
+            int urlStart = schemeStart;
+            int j = delimAt + delimiter.Length;
+
+            while (j < span.Length && !IsUrlTerminator (span [j]))
+            {
+                j++;
+            }
+
+            // Trim punctuation from the end of the URL, but remember it so we can re-append it after the hyperlink
+            int urlEnd = TrimTrailingPunctuation (span, urlStart, j);
+            ReadOnlySpan<char> trailing = span.Slice (urlEnd, j - urlEnd);
+
+            if (urlEnd <= (delimAt + delimiter.Length))
+            {
+                i = j;
+                continue;
+            }
+
+            string candidate = span.Slice (urlStart, urlEnd - urlStart).ToString ();
+
+            Uri? _;
+            if (options._validateWithUri && !IsValidUrl (candidate, options, out _))
+            {
+                i = j;
+                continue;
+            }
+
+            sb ??= new StringBuilder (span.Length + 64);
+
+            if (urlStart > copyFrom)
+            {
+                sb.Append (span.Slice (copyFrom, urlStart - copyFrom));
+            }
+
+            // Preserve original candidate for link target and display
+            string linkTarget = candidate;
+
+            sb.Append (EscSeqUtils.OSC_StartHyperlink (linkTarget));
+            sb.Append (candidate);
+            sb.Append (EscSeqUtils.OSC_EndHyperlink ());
+
+            // Re-append the trimmed punctuation/suffix (e.g., "!", ",", ")")
+            if (!trailing.IsEmpty)
+            {
+                sb.Append (trailing);
+            }
+
+            copyFrom = j;
+            i = j;
+        }
+
+        if (sb is null)
+        {
+            changed = false;
+            return span.ToString ();
+        }
+
+        if (copyFrom < span.Length)
+        {
+            sb.Append (span.Slice (copyFrom));
+        }
+
+        changed = true;
+        return sb.ToString ();
+    }
+
+    private static bool IsAllowedScheme (ReadOnlySpan<char> scheme, Options options)
+    {
+        for (int i = 0; i < options._allowedSchemes.Length; i++)
+        {
+            string s = options._allowedSchemes [i];
+            if (scheme.Equals (s, StringComparison.OrdinalIgnoreCase))
+            {
+                return true;
+            }
+        }
+
+        return false;
+    }
+
+    private static bool IsUrlTerminator (char c)
+    {
+        return char.IsWhiteSpace (c) || c == '<' || c == '>' || c == '"' || c == '\'' || c == '\x1B';
+    }
+
+    private static int TrimTrailingPunctuation (ReadOnlySpan<char> span, int start, int end)
+    {
+        int e = end;
+
+        while (e > start)
+        {
+            char c = span [e - 1];
+            if (c is '.' or ',' or '!' or '?' or ';' or ':' or ']' or '}' or '"')
+            {
+                e--;
+            }
+            else
+            {
+                break;
+            }
+        }
+
+        if (e > start && span [e - 1] == ')')
+        {
+            int opens = 0;
+            int closes = 0;
+
+            for (int k = start; k < e; k++)
+            {
+                if (span [k] == '(')
+                {
+                    opens++;
+                }
+                else if (span [k] == ')')
+                {
+                    closes++;
+                }
+            }
+
+            while (e > start && closes > opens && span [e - 1] == ')')
+            {
+                e--;
+                closes--;
+            }
+        }
+
+        return e;
+    }
+
+    private static bool IsValidUrl (string candidate, Options options, out Uri? uri)
+    {
+        if (Uri.TryCreate (candidate, UriKind.Absolute, out uri))
+        {
+            for (int i = 0; i < options._allowedSchemes.Length; i++)
+            {
+                string s = options._allowedSchemes [i];
+                if (uri.Scheme.Equals (s, StringComparison.OrdinalIgnoreCase))
+                {
+                    return true;
+                }
+            }
+        }
+
+        uri = null;
+        return false;
+    }
+}

+ 1 - 2
Terminal.Gui/Drivers/ConsoleDriver.cs

@@ -550,8 +550,7 @@ public abstract class ConsoleDriver : IConsoleDriver
     #region Setup & Teardown
 
     /// <summary>Initializes the driver</summary>
-    /// <returns>Returns an instance of <see cref="MainLoop"/> using the <see cref="IMainLoopDriver"/> for the driver.</returns>
-    public abstract MainLoop Init ();
+    public abstract void Init ();
 
     /// <summary>Ends the execution of the console driver.</summary>
     public abstract void End ();

+ 1 - 1
Terminal.Gui/Drivers/ConsoleDriverFacade.cs

@@ -365,7 +365,7 @@ internal class ConsoleDriverFacade<T> : IConsoleDriver, IConsoleDriverFacade
 
     /// <summary>Initializes the driver</summary>
     /// <returns>Returns an instance of <see cref="MainLoop"/> using the <see cref="IMainLoopDriver"/> for the driver.</returns>
-    public MainLoop Init () { throw new NotSupportedException (); }
+    public void Init () { throw new NotSupportedException (); }
 
     /// <summary>Ends the execution of the console driver.</summary>
     public void End ()

+ 1 - 27
Terminal.Gui/Drivers/FakeDriver/FakeDriver.cs

@@ -91,9 +91,7 @@ public class FakeDriver : ConsoleDriver
         FakeConsole.Clear ();
     }
 
-    private FakeMainLoop? _mainLoopDriver;
-
-    public override MainLoop Init ()
+    public override void Init ()
     {
         FakeConsole.MockKeyPresses.Clear ();
 
@@ -102,12 +100,6 @@ public class FakeDriver : ConsoleDriver
         FakeConsole.Clear ();
         ResizeScreen ();
         CurrentAttribute = new Attribute (Color.White, Color.Black);
-        //ClearContents ();
-
-        _mainLoopDriver = new FakeMainLoop (this);
-        _mainLoopDriver.MockKeyPressed = MockKeyPressedHandler;
-
-        return new MainLoop (_mainLoopDriver);
     }
 
     public override bool UpdateScreen ()
@@ -346,24 +338,6 @@ public class FakeDriver : ConsoleDriver
 
     private CursorVisibility _savedCursorVisibility;
 
-    private void MockKeyPressedHandler (ConsoleKeyInfo consoleKeyInfo)
-    {
-        if (consoleKeyInfo.Key == ConsoleKey.Packet)
-        {
-            consoleKeyInfo = ConsoleKeyMapping.DecodeVKPacketToKConsoleKeyInfo (consoleKeyInfo);
-        }
-
-        KeyCode map = MapKey (consoleKeyInfo);
-
-        if (IsValidInput (map, out map))
-        {
-            OnKeyDown (new (map));
-            OnKeyUp (new (map));
-        }
-
-        //OnKeyPressed (new KeyEventArgs (map));
-    }
-
     /// <inheritdoc/>
     public override bool GetCursorVisibility (out CursorVisibility visibility)
     {

+ 0 - 38
Terminal.Gui/Drivers/FakeDriver/FakeMainLoop.cs

@@ -1,38 +0,0 @@
-
-namespace Terminal.Gui.Drivers;
-
-internal class FakeMainLoop : IMainLoopDriver
-{
-    public Action<ConsoleKeyInfo> MockKeyPressed;
-
-    public FakeMainLoop (IConsoleDriver consoleDriver = null)
-    {
-        // No implementation needed for FakeMainLoop
-    }
-
-    public void Setup (MainLoop mainLoop)
-    {
-        // No implementation needed for FakeMainLoop
-    }
-
-    public void Wakeup ()
-    {
-        // No implementation needed for FakeMainLoop
-    }
-
-    public bool EventsPending ()
-    {
-        // Always return true for FakeMainLoop
-        return true;
-    }
-
-    public void Iteration ()
-    {
-        if (FakeConsole.MockKeyPresses.Count > 0)
-        {
-            MockKeyPressed?.Invoke (FakeConsole.MockKeyPresses.Pop ());
-        }
-    }
-
-    public void TearDown () { }
-}

+ 1 - 2
Terminal.Gui/Drivers/IConsoleDriver.cs

@@ -214,8 +214,7 @@ public interface IConsoleDriver
     void UpdateCursor ();
 
     /// <summary>Initializes the driver</summary>
-    /// <returns>Returns an instance of <see cref="MainLoop"/> using the <see cref="IMainLoopDriver"/> for the driver.</returns>
-    MainLoop Init ();
+    void Init ();
 
     /// <summary>Ends the execution of the console driver.</summary>
     void End ();

+ 48 - 53
Terminal.Gui/Drivers/OutputBase.cs

@@ -1,13 +1,8 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
+#nullable enable
 namespace Terminal.Gui.Drivers;
 
 /// <summary>
-/// Abstract base class to assist with implementing <see cref="IConsoleOutput"/>.
+///     Abstract base class to assist with implementing <see cref="IConsoleOutput"/>.
 /// </summary>
 public abstract class OutputBase
 {
@@ -16,6 +11,13 @@ public abstract class OutputBase
     // Last text style used, for updating style with EscSeqUtils.CSI_AppendTextStyleChange().
     private TextStyle _redrawTextStyle = TextStyle.None;
 
+    /// <summary>
+    ///     Changes the visibility of the cursor in the terminal to the specified <paramref name="visibility"/> e.g.
+    ///     the flashing indicator, invisible, box indicator etc.
+    /// </summary>
+    /// <param name="visibility"></param>
+    public abstract void SetCursorVisibility (CursorVisibility visibility);
+
     /// <inheritdoc cref="IConsoleOutput.Write(IOutputBuffer)"/>
     public virtual void Write (IOutputBuffer buffer)
     {
@@ -24,13 +26,6 @@ public abstract class OutputBase
             return;
         }
 
-        //if (Console.WindowHeight < 1
-        //    || buffer.Contents.Length != buffer.Rows * buffer.Cols
-        //    || buffer.Rows != Console.WindowHeight)
-        //{
-        //    //     return;
-        //}
-
         var top = 0;
         var left = 0;
         int rows = buffer.Rows;
@@ -42,16 +37,11 @@ public abstract class OutputBase
         CursorVisibility? savedVisibility = _cachedCursorVisibility;
         SetCursorVisibility (CursorVisibility.Invisible);
 
-        const int maxCharsPerRune = 2;
-        Span<char> runeBuffer = stackalloc char [maxCharsPerRune];
+        const int MAX_CHARS_PER_RUNE = 2;
+        Span<char> runeBuffer = stackalloc char [MAX_CHARS_PER_RUNE];
 
         for (int row = top; row < rows; row++)
         {
-            //if (Console.WindowHeight < 1)
-            //{
-            //    return;
-            //}
-
             if (!SetCursorPositionImpl (0, row))
             {
                 return;
@@ -90,16 +80,21 @@ public abstract class OutputBase
                         lastCol = col;
                     }
 
-                    Attribute attr = buffer.Contents [row, col].Attribute.Value;
+                    Attribute? attribute = buffer.Contents [row, col].Attribute;
 
-                    // Performance: Only send the escape sequence if the attribute has changed.
-                    if (attr != redrawAttr)
+                    if (attribute is { })
                     {
-                        redrawAttr = attr;
+                        Attribute attr = attribute.Value;
+
+                        // Performance: Only send the escape sequence if the attribute has changed.
+                        if (attr != redrawAttr)
+                        {
+                            redrawAttr = attr;
 
-                        AppendOrWriteAttribute (output, attr, _redrawTextStyle);
+                            AppendOrWriteAttribute (output, attr, _redrawTextStyle);
 
-                        _redrawTextStyle = attr.Style;
+                            _redrawTextStyle = attr.Style;
+                        }
                     }
 
                     outputWidth++;
@@ -120,8 +115,6 @@ public abstract class OutputBase
                         // For now, we just ignore the list of CMs.
                         //foreach (var combMark in Contents [row, col].CombiningMarks) {
                         //	output.Append (combMark);
-                        //}
-                        // WriteToConsole (output, ref lastCol, row, ref outputWidth);
                     }
                     else if (rune.IsSurrogatePair () && rune.GetColumns () < 2)
                     {
@@ -136,7 +129,10 @@ public abstract class OutputBase
             if (output.Length > 0)
             {
                 SetCursorPositionImpl (lastCol, row);
-                Write (output);
+
+                // Wrap URLs with OSC 8 hyperlink sequences using the new Osc8UrlLinker
+                StringBuilder processed = Osc8UrlLinker.WrapOsc8 (output);
+                Write (processed);
             }
         }
 
@@ -154,32 +150,19 @@ public abstract class OutputBase
     }
 
     /// <summary>
-    /// Changes the color and text style of the console to the given <paramref name="attr"/> and <paramref name="redrawTextStyle"/>.
-    /// If command can be buffered in line with other output (e.g. CSI sequence) then it should be appended to <paramref name="output"/>
-    /// otherwise the relevant output state should be flushed directly (e.g. by calling relevant win 32 API method)
+    ///     Changes the color and text style of the console to the given <paramref name="attr"/> and
+    ///     <paramref name="redrawTextStyle"/>.
+    ///     If command can be buffered in line with other output (e.g. CSI sequence) then it should be appended to
+    ///     <paramref name="output"/>
+    ///     otherwise the relevant output state should be flushed directly (e.g. by calling relevant win 32 API method)
     /// </summary>
     /// <param name="output"></param>
     /// <param name="attr"></param>
     /// <param name="redrawTextStyle"></param>
     protected abstract void AppendOrWriteAttribute (StringBuilder output, Attribute attr, TextStyle redrawTextStyle);
 
-    private void WriteToConsole (StringBuilder output, ref int lastCol, int row, ref int outputWidth)
-    {
-        SetCursorPositionImpl (lastCol, row);
-        Write (output);
-        output.Clear ();
-        lastCol += outputWidth;
-        outputWidth = 0;
-    }
-
     /// <summary>
-    /// Output the contents of the <paramref name="output"/> to the console.
-    /// </summary>
-    /// <param name="output"></param>
-    protected abstract void Write (StringBuilder output);
-
-    /// <summary>
-    /// When overriden in derived class, positions the terminal output cursor to the specified point on the screen.
+    ///     When overriden in derived class, positions the terminal output cursor to the specified point on the screen.
     /// </summary>
     /// <param name="screenPositionX">Column to move cursor to</param>
     /// <param name="screenPositionY">Row to move cursor to</param>
@@ -187,9 +170,21 @@ public abstract class OutputBase
     protected abstract bool SetCursorPositionImpl (int screenPositionX, int screenPositionY);
 
     /// <summary>
-    /// Changes the visibility of the cursor in the terminal to the specified <paramref name="visibility"/> e.g.
-    /// the flashing indicator, invisible, box indicator etc.
+    ///     Output the contents of the <paramref name="output"/> to the console.
     /// </summary>
-    /// <param name="visibility"></param>
-    public abstract void SetCursorVisibility (CursorVisibility visibility);
+    /// <param name="output"></param>
+    protected abstract void Write (StringBuilder output);
+
+    private void WriteToConsole (StringBuilder output, ref int lastCol, int row, ref int outputWidth)
+    {
+        SetCursorPositionImpl (lastCol, row);
+
+        // Wrap URLs with OSC 8 hyperlink sequences using the new Osc8UrlLinker
+        StringBuilder processed = Osc8UrlLinker.WrapOsc8 (output);
+        Write (processed);
+
+        output.Clear ();
+        lastCol += outputWidth;
+        outputWidth = 0;
+    }
 }

+ 2 - 1
Terminal.sln.ToDo.DotSettings

@@ -1,4 +1,5 @@
-<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
+<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
+	<s:Boolean x:Key="/Default/CodeEditing/StackTraceExplorer/AutoOpen/@EntryValue">False</s:Boolean>
 	<s:String x:Key="/Default/PatternsAndTemplates/Todo/TodoPatterns/=4386F01B791C56499C7EA059B55FFB54/Name/@EntryValue">Bug</s:String>
 	<s:String x:Key="/Default/PatternsAndTemplates/Todo/TodoPatterns/=4386F01B791C56499C7EA059B55FFB54/Pattern/@EntryValue">(?&lt;=\W|^)(?&lt;TAG&gt;BUGBUG|BUG|PROBLEM): *(?&lt;Message&gt;[\S].*)$</s:String>
 	<s:String x:Key="/Default/PatternsAndTemplates/Todo/TodoPatterns/=4386F01B791C56499C7EA059B55FFB54/TodoIconStyle/@EntryValue">Warning</s:String>

+ 0 - 17
Tests/UnitTests/Application/ApplicationTests.cs

@@ -159,7 +159,6 @@ public class ApplicationTests
         Application.Shutdown ();
 
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 
@@ -316,7 +315,6 @@ public class ApplicationTests
             // Don't check Application.Force16Colors
             //Assert.False (Application.Force16Colors);
             Assert.Null (Application.Driver);
-            Assert.Null (Application.MainLoop);
             Assert.False (Application.EndAfterFirstIteration);
 
             // Commented out because if CM changed the defaults, those changes should
@@ -472,7 +470,6 @@ public class ApplicationTests
         Application.Shutdown ();
 
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 
@@ -486,7 +483,6 @@ public class ApplicationTests
         Application.Shutdown ();
 
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 
@@ -522,14 +518,12 @@ public class ApplicationTests
         Application.End (runstate);
 
         Assert.NotNull (Application.Top);
-        Assert.NotNull (Application.MainLoop);
         Assert.NotNull (Application.Driver);
 
         topLevel.Dispose ();
         Application.Shutdown ();
 
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 
@@ -676,7 +670,6 @@ public class ApplicationTests
         Application.Shutdown ();
 
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 
@@ -700,7 +693,6 @@ public class ApplicationTests
         Application.Shutdown ();
 
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 
@@ -734,7 +726,6 @@ public class ApplicationTests
         Application.Shutdown ();
 
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 
@@ -752,7 +743,6 @@ public class ApplicationTests
         Application.Shutdown ();
 
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 
@@ -774,7 +764,6 @@ public class ApplicationTests
         Application.Shutdown ();
 
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
 
         a.After (null);
@@ -793,7 +782,6 @@ public class ApplicationTests
         Application.Shutdown ();
 
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 
@@ -812,7 +800,6 @@ public class ApplicationTests
         Application.Shutdown ();
 
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 
@@ -829,7 +816,6 @@ public class ApplicationTests
         Application.Shutdown ();
 
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 
@@ -849,7 +835,6 @@ public class ApplicationTests
         top.Dispose ();
         Application.Shutdown ();
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 
@@ -872,7 +857,6 @@ public class ApplicationTests
         top.Dispose ();
         Application.Shutdown ();
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 
@@ -892,7 +876,6 @@ public class ApplicationTests
         top.Dispose ();
         Application.Shutdown ();
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 

+ 0 - 940
Tests/UnitTests/Application/MainLoopTests.cs

@@ -1,940 +0,0 @@
-using System.Diagnostics;
-using Xunit.Abstractions;
-
-// Alias Console to MockConsole so we don't accidentally use Console
-
-namespace UnitTests.ApplicationTests;
-
-/// <summary>Tests MainLoop using the FakeMainLoop.</summary>
-public class MainLoopTests
-{
-    private readonly ITestOutputHelper _output;
-
-    public MainLoopTests (ITestOutputHelper output)
-    {
-        _output = output;
-        ConsoleDriver.RunningUnitTests = true;
-    }
-
-    private static Button btn;
-    private static string cancel;
-    private static string clickMe;
-    private static int four;
-    private static int one;
-    private static string pewPew;
-    private static bool taskCompleted;
-
-    // TODO: EventsPending tests
-    // - wait = true
-    // - wait = false
-
-    // TODO: Add IMainLoop tests
-    private static int three;
-    private static int total;
-    private static int two;
-    private static int zero;
-
-    // See Also ConsoleDRivers/MainLoopDriverTests.cs for tests of the MainLoopDriver
-
-    // Idle Handler tests
-    [Fact]
-    public void AddTimeout_Adds_And_Removes ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-
-        Func<bool> fnTrue = () => true;
-        Func<bool> fnFalse = () => false;
-
-        var a = ml.TimedEvents.Add (TimeSpan.Zero, fnTrue);
-        var b = ml.TimedEvents.Add (TimeSpan.Zero, fnFalse);
-
-        Assert.Equal (2, ml.TimedEvents.Timeouts.Count);
-        Assert.Equal (fnTrue, ml.TimedEvents.Timeouts.ElementAt (0).Value.Callback);
-        Assert.NotEqual (fnFalse, ml.TimedEvents.Timeouts.ElementAt (0).Value.Callback);
-
-        Assert.True (ml.TimedEvents.Remove (a));
-        Assert.Single (ml.TimedEvents.Timeouts);
-
-        // BUGBUG: This doesn't throw or indicate an error. Ideally RemoveIdle would either 
-        // throw an exception in this case, or return an error.
-        // No. Only need to return a boolean.
-        Assert.False (ml.TimedEvents.Remove (a));
-
-        Assert.True (ml.TimedEvents.Remove (b));
-
-        // BUGBUG: This doesn't throw an exception or indicate an error. Ideally RemoveIdle would either 
-        // throw an exception in this case, or return an error.
-        // No. Only need to return a boolean.
-        Assert.False (ml.TimedEvents.Remove(b));
-    }
-
-    [Fact]
-    public void AddTimeout_Function_GetsCalled_OnIteration ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-
-        var functionCalled = 0;
-
-        Func<bool> fn = () =>
-                        {
-                            functionCalled++;
-
-                            return true;
-                        };
-
-        ml.TimedEvents.Add (TimeSpan.Zero, fn);
-        ml.RunIteration ();
-        Assert.Equal (1, functionCalled);
-    }
-
-    [Fact]
-    public void AddTimeout_Twice_Returns_False_Called_Twice ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-
-        var functionCalled = 0;
-
-        Func<bool> fn1 = () =>
-                         {
-                             functionCalled++;
-
-                             return false;
-                         };
-
-        // Force stop if 10 iterations
-        var stopCount = 0;
-
-        Func<bool> fnStop = () =>
-                            {
-                                stopCount++;
-
-                                if (stopCount == 10)
-                                {
-                                    ml.Stop ();
-                                }
-
-                                return true;
-                            };
-
-        var a = ml.TimedEvents.Add (TimeSpan.Zero, fnStop);
-        var b = ml.TimedEvents.Add (TimeSpan.Zero, fn1);
-        ml.Run ();
-
-        Assert.True (ml.TimedEvents.Remove(a));
-        Assert.False (ml.TimedEvents.Remove (a));
-
-        // Cannot remove b because it returned false i.e. auto removes itself
-        Assert.False (ml.TimedEvents.Remove (b));
-
-        Assert.Equal (1, functionCalled);
-    }
-
-    [Fact]
-    public void AddTimeoutTwice_Function_CalledTwice ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-
-        var functionCalled = 0;
-
-        Func<bool> fn = () =>
-                        {
-                            functionCalled++;
-
-                            return true;
-                        };
-
-        var a = ml.TimedEvents.Add (TimeSpan.Zero, fn);
-        var b = ml.TimedEvents.Add (TimeSpan.Zero, fn);
-        ml.RunIteration ();
-        Assert.Equal (2, functionCalled);
-        Assert.Equal (2, ml.TimedEvents.Timeouts.Count);
-
-        functionCalled = 0;
-        Assert.True (ml.TimedEvents.Remove (a));
-        Assert.Single (ml.TimedEvents.Timeouts);
-        ml.RunIteration ();
-        Assert.Equal (1, functionCalled);
-
-        functionCalled = 0;
-        Assert.True (ml.TimedEvents.Remove (b));
-        Assert.Empty (ml.TimedEvents.Timeouts);
-        ml.RunIteration ();
-        Assert.Equal (0, functionCalled);
-        Assert.False (ml.TimedEvents.Remove (b));
-    }
-
-    [Fact]
-    public void AddThenRemoveIdle_Function_NotCalled ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-
-        var functionCalled = 0;
-
-        Func<bool> fn = () =>
-                        {
-                            functionCalled++;
-
-                            return true;
-                        };
-
-        var a = ml.TimedEvents.Add (TimeSpan.Zero, fn);
-        Assert.True (ml.TimedEvents.Remove (a));
-        ml.RunIteration ();
-        Assert.Equal (0, functionCalled);
-    }
-
-    // Timeout Handler Tests
-    [Fact]
-    public void AddTimer_Adds_Removes_NoFaults ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-        var ms = 100;
-
-        var callbackCount = 0;
-
-        Func<bool> callback = () =>
-                              {
-                                  callbackCount++;
-
-                                  return true;
-                              };
-
-        object token = ml.TimedEvents.Add (TimeSpan.FromMilliseconds (ms), callback);
-
-        Assert.True (ml.TimedEvents.Remove (token));
-
-        // BUGBUG: This should probably fault?
-        // Must return a boolean.
-        Assert.False (ml.TimedEvents.Remove (token));
-    }
-
-    [Fact]
-    public async Task AddTimer_Duplicate_Keys_Not_Allowed ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-        const int ms = 100;
-        object token1 = null, token2 = null;
-
-        var callbackCount = 0;
-
-        Func<bool> callback = () =>
-                              {
-                                  callbackCount++;
-
-                                  if (callbackCount == 2)
-                                  {
-                                      ml.Stop ();
-                                  }
-
-                                  return true;
-                              };
-
-        var task1 = new Task (() => token1 = ml.TimedEvents.Add (TimeSpan.FromMilliseconds (ms), callback));
-        var task2 = new Task (() => token2 = ml.TimedEvents.Add (TimeSpan.FromMilliseconds (ms), callback));
-        Assert.Null (token1);
-        Assert.Null (token2);
-        task1.Start ();
-        task2.Start ();
-        ml.Run ();
-        Assert.NotNull (token1);
-        Assert.NotNull (token2);
-        await Task.WhenAll (task1, task2);
-        Assert.True (ml.TimedEvents.Remove (token1));
-        Assert.True (ml.TimedEvents.Remove (token2));
-
-        Assert.Equal (2, callbackCount);
-    }
-
-    // Timeout Handler Tests
-    [Fact]
-    public void AddTimer_EventFired ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-        var ms = 100;
-
-        // Use Stopwatch ticks since TimedEvents now uses Stopwatch.GetTimestamp internally
-        long originTicks = Stopwatch.GetTimestamp () * TimeSpan.TicksPerSecond / Stopwatch.Frequency;
-
-        var callbackCount = 0;
-
-        Func<bool> callback = () =>
-                              {
-                                  callbackCount++;
-
-                                  return true;
-                              };
-
-        object sender = null;
-        TimeoutEventArgs args = null;
-
-        ml.TimedEvents.Added += (s, e) =>
-                                       {
-                                           sender = s;
-                                           args = e;
-                                       };
-
-        object token = ml.TimedEvents.Add (TimeSpan.FromMilliseconds (ms), callback);
-
-        Assert.Same (ml.TimedEvents, sender);
-        Assert.NotNull (args.Timeout);
-        Assert.True (args.Ticks - originTicks >= 100 * TimeSpan.TicksPerMillisecond);
-    }
-
-    [Fact]
-    public void AddTimer_In_Parallel_Wont_Throw ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-        const int ms = 100;
-        object token1 = null, token2 = null;
-
-        var callbackCount = 0;
-
-        Func<bool> callback = () =>
-                              {
-                                  callbackCount++;
-
-                                  if (callbackCount == 2)
-                                  {
-                                      ml.Stop ();
-                                  }
-
-                                  return true;
-                              };
-
-        Parallel.Invoke (
-                         () => token1 = ml.TimedEvents.Add (TimeSpan.FromMilliseconds (ms), callback),
-                         () => token2 = ml.TimedEvents.Add (TimeSpan.FromMilliseconds (ms), callback)
-                        );
-        ml.Run ();
-        Assert.NotNull (token1);
-        Assert.NotNull (token2);
-        Assert.True (ml.TimedEvents.Remove (token1));
-        Assert.True (ml.TimedEvents.Remove (token2));
-
-        Assert.Equal (2, callbackCount);
-    }
-
-    [Fact]
-    public void AddTimer_Remove_NotCalled ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-        TimeSpan ms = TimeSpan.FromMilliseconds (50);
-
-        // Force stop if 10 iterations
-        var stopCount = 0;
-
-        Func<bool> fnStop = () =>
-                            {
-                                stopCount++;
-
-                                if (stopCount == 10)
-                                {
-                                    ml.Stop ();
-                                }
-
-                                return true;
-                            };
-        ml.TimedEvents.Add (TimeSpan.Zero, fnStop);
-
-        var callbackCount = 0;
-
-        Func<bool> callback = () =>
-                              {
-                                  callbackCount++;
-
-                                  return true;
-                              };
-
-        object token = ml.TimedEvents.Add (ms, callback);
-        Assert.True (ml.TimedEvents.Remove (token));
-        ml.Run ();
-        Assert.Equal (0, callbackCount);
-    }
-
-    [Fact]
-    public void AddTimer_ReturnFalse_StopsBeingCalled ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-        TimeSpan ms = TimeSpan.FromMilliseconds (50);
-
-        // Force stop if 10 iterations
-        var stopCount = 0;
-
-        Func<bool> fnStop = () =>
-                            {
-                                Thread.Sleep (10); // Sleep to enable timer to fire
-                                stopCount++;
-
-                                if (stopCount == 10)
-                                {
-                                    ml.Stop ();
-                                }
-
-                                return true;
-                            };
-        ml.TimedEvents.Add (TimeSpan.Zero, fnStop);
-
-        var callbackCount = 0;
-
-        Func<bool> callback = () =>
-                              {
-                                  callbackCount++;
-
-                                  return false;
-                              };
-
-        object token = ml.TimedEvents.Add (ms, callback);
-        ml.Run ();
-        Assert.Equal (1, callbackCount);
-        Assert.Equal (10, stopCount);
-        Assert.False (ml.TimedEvents.Remove (token));
-    }
-
-    [Fact]
-    public void AddTimer_Run_Called ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-        var ms = 100;
-
-        var callbackCount = 0;
-
-        Func<bool> callback = () =>
-                              {
-                                  callbackCount++;
-                                  ml.Stop ();
-
-                                  return true;
-                              };
-
-        object token = ml.TimedEvents.Add (TimeSpan.FromMilliseconds (ms), callback);
-        ml.Run ();
-        Assert.True (ml.TimedEvents.Remove (token));
-
-        Assert.Equal (1, callbackCount);
-    }
-
-    [Fact]
-    public void AddTimer_Run_CalledAtApproximatelyRightTime ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-        TimeSpan ms = TimeSpan.FromMilliseconds (50);
-        var watch = new Stopwatch ();
-
-        var callbackCount = 0;
-
-        Func<bool> callback = () =>
-                              {
-                                  watch.Stop ();
-                                  callbackCount++;
-                                  ml.Stop ();
-
-                                  return true;
-                              };
-
-        object token = ml.TimedEvents.Add (ms, callback);
-        watch.Start ();
-        ml.Run ();
-
-        // +/- 100ms should be good enuf
-        // https://github.com/xunit/assert.xunit/pull/25
-        Assert.Equal (ms * callbackCount, watch.Elapsed, new MillisecondTolerance (100));
-
-        Assert.True (ml.TimedEvents.Remove (token));
-        Assert.Equal (1, callbackCount);
-    }
-
-    [Fact]
-    public void AddTimer_Run_CalledTwiceApproximatelyRightTime ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-        TimeSpan ms = TimeSpan.FromMilliseconds (50);
-        var watch = new Stopwatch ();
-
-        var callbackCount = 0;
-
-        Func<bool> callback = () =>
-                              {
-                                  callbackCount++;
-
-                                  if (callbackCount == 2)
-                                  {
-                                      watch.Stop ();
-                                      ml.Stop ();
-                                  }
-
-                                  return true;
-                              };
-
-        object token = ml.TimedEvents.Add (ms, callback);
-        watch.Start ();
-        ml.Run ();
-
-        // +/- 100ms should be good enuf
-        // https://github.com/xunit/assert.xunit/pull/25
-        Assert.Equal (ms * callbackCount, watch.Elapsed, new MillisecondTolerance (100));
-
-        Assert.True (ml.TimedEvents.Remove (token));
-        Assert.Equal (2, callbackCount);
-    }
-
-    [Fact]
-    public void CheckTimersAndIdleHandlers_NoTimers_Returns_False ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-        bool retVal = ml.TimedEvents.CheckTimers(out int waitTimeOut);
-        Assert.False (retVal);
-        Assert.Equal (-1, waitTimeOut);
-    }
-
-    [Fact]
-    public void CheckTimersAndIdleHandlers_NoTimers_WithIdle_Returns_True ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-        Func<bool> fnTrue = () => true;
-
-        ml.TimedEvents.Add (TimeSpan.Zero, fnTrue);
-        bool retVal = ml.TimedEvents.CheckTimers(out int waitTimeOut);
-        Assert.True (retVal);
-        Assert.Equal (0, waitTimeOut);
-    }
-
-    [Fact]
-    public void CheckTimersAndIdleHandlers_With1Timer_Returns_Timer ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-        TimeSpan ms = TimeSpan.FromMilliseconds (50);
-
-        static bool Callback () { return false; }
-
-        _ = ml.TimedEvents.Add (ms, Callback);
-        bool retVal = ml.TimedEvents.CheckTimers (out int waitTimeOut);
-
-        Assert.True (retVal);
-
-        // It should take < 10ms to execute to here
-        Assert.True (ms.TotalMilliseconds <= waitTimeOut + 10);
-    }
-
-    [Fact]
-    public void CheckTimersAndIdleHandlers_With2Timers_Returns_Timer ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-        TimeSpan ms = TimeSpan.FromMilliseconds (50);
-
-        static bool Callback () { return false; }
-
-        _ = ml.TimedEvents.Add (ms, Callback);
-        _ = ml.TimedEvents.Add (ms, Callback);
-        bool retVal = ml.TimedEvents.CheckTimers (out int waitTimeOut);
-
-        Assert.True (retVal);
-
-        // It should take < 10ms to execute to here
-        Assert.True (ms.TotalMilliseconds <= waitTimeOut + 10);
-    }
-
-    [Fact]
-    public void False_Idle_Stops_It_Being_Called_Again ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-
-        var functionCalled = 0;
-
-        Func<bool> fn1 = () =>
-                         {
-                             functionCalled++;
-
-                             if (functionCalled == 10)
-                             {
-                                 return false;
-                             }
-
-                             return true;
-                         };
-
-        // Force stop if 20 iterations
-        var stopCount = 0;
-
-        Func<bool> fnStop = () =>
-                            {
-                                stopCount++;
-
-                                if (stopCount == 20)
-                                {
-                                    ml.Stop ();
-                                }
-
-                                return true;
-                            };
-
-        var a = ml.TimedEvents.Add (TimeSpan.Zero, fnStop);
-        var b = ml.TimedEvents.Add (TimeSpan.Zero, fn1);
-        ml.Run ();
-        Assert.True (ml.TimedEvents.Remove (a));
-        Assert.False (ml.TimedEvents.Remove (a));
-
-        Assert.Equal (10, functionCalled);
-        Assert.Equal (20, stopCount);
-    }
-
-    [Fact]
-    public void Internal_Tests ()
-    {
-        var testMainloop = new TestMainloop ();
-        var mainloop = new MainLoop (testMainloop);
-        Assert.Empty (mainloop.TimedEvents.Timeouts);
-
-        Assert.NotNull (
-                        new Terminal.Gui.App.Timeout { Span = new (), Callback = () => true }
-                       );
-    }
-
-    [Theory]
-    [MemberData (nameof (TestAddTimeout))]
-    public void Mainloop_Invoke_Or_AddTimeout_Can_Be_Used_For_Events_Or_Actions (
-        Action action,
-        string pclickMe,
-        string pcancel,
-        string ppewPew,
-        int pzero,
-        int pone,
-        int ptwo,
-        int pthree,
-        int pfour
-    )
-    {
-        // TODO: Expand this test to test all drivers
-        Application.Init (null, "fakedriver");
-
-        total = 0;
-        btn = null;
-        clickMe = pclickMe;
-        cancel = pcancel;
-        pewPew = ppewPew;
-        zero = pzero;
-        one = pone;
-        two = ptwo;
-        three = pthree;
-        four = pfour;
-        taskCompleted = false;
-
-        var btnLaunch = new Button { Text = "Open Window" };
-
-        btnLaunch.Accepting += (s, e) => action ();
-
-        var top = new Toplevel ();
-        top.Add (btnLaunch);
-
-        int iterations = -1;
-
-        Application.Iteration += (s, a) =>
-                                 {
-                                     iterations++;
-
-                                     if (iterations == 0)
-                                     {
-                                         Assert.Null (btn);
-                                         Assert.Equal (zero, total);
-                                         Assert.False (btnLaunch.NewKeyDownEvent (Key.Space));
-
-                                         if (btn == null)
-                                         {
-                                             Assert.Null (btn);
-                                             Assert.Equal (zero, total);
-                                         }
-                                         else
-                                         {
-                                             Assert.Equal (clickMe, btn.Text);
-                                             Assert.Equal (four, total);
-                                         }
-                                     }
-                                     else if (iterations == 1)
-                                     {
-                                         Assert.Equal (clickMe, btn.Text);
-                                         Assert.Equal (zero, total);
-                                         Assert.False (btn.NewKeyDownEvent (Key.Space));
-                                         Assert.Equal (cancel, btn.Text);
-                                         Assert.Equal (one, total);
-                                     }
-                                     else if (taskCompleted)
-                                     {
-                                         Application.RequestStop ();
-                                     }
-                                 };
-
-        Application.Run (top);
-        top.Dispose ();
-
-        Assert.True (taskCompleted);
-        Assert.Equal (clickMe, btn.Text);
-        Assert.Equal (four, total);
-
-        Application.Shutdown ();
-    }
-    
-    [Fact]
-    public void RemoveIdle_Function_NotCalled ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-
-        var functionCalled = 0;
-
-        Func<bool> fn = () =>
-                        {
-                            functionCalled++;
-
-                            return true;
-                        };
-
-        Assert.False (ml.TimedEvents.Remove ("flibble"));
-        ml.RunIteration ();
-        Assert.Equal (0, functionCalled);
-    }
-
-    [Fact]
-    public void Run_Runs_Idle_Stop_Stops_Idle ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-
-        var functionCalled = 0;
-
-        Func<bool> fn = () =>
-                        {
-                            functionCalled++;
-
-                            if (functionCalled == 10)
-                            {
-                                ml.Stop ();
-                            }
-
-                            return true;
-                        };
-
-        var a = ml.TimedEvents.Add (TimeSpan.Zero, fn);
-        ml.Run ();
-        Assert.True (ml.TimedEvents.Remove (a));
-
-        Assert.Equal (10, functionCalled);
-    }
-
-    [Theory]
-    [InlineData ("fake")]
-    [InlineData ("windows")]
-    [InlineData ("dotnet")]
-    [InlineData ("unix")]
-    public void Application_Invoke_Run_TimedEvents (string driverName)
-    {
-        // Arrange
-        Application.Init (driverName: driverName);
-        var functionCalled = 0;
-        var stopwatch = new Stopwatch ();
-
-        // Act
-        Application.Invoke (() =>
-                            {
-                                // Stop the stopwatch *after* the function is called.
-                                functionCalled++;
-                                stopwatch.Stop ();
-                                Application.RequestStop ();
-                            });
-
-        // Start timing just before running the application loop.
-        stopwatch.Start ();
-        Application.Run ();
-
-        // Assert
-        Assert.NotNull (Application.Top);
-        Application.Top.Dispose ();
-        Application.Shutdown ();
-        Assert.Equal (1, functionCalled);
-
-        // Output the elapsed time for this test case.
-        // ReSharper disable once Xunit.XunitTestWithConsoleOutput
-        // ReSharper disable once LocalizableElement
-        Console.WriteLine ($"[{driverName}] Duration: {stopwatch.Elapsed.TotalMilliseconds:F2} ms");
-
-        // Output elapsed duration to xUnit's test output
-        _output.WriteLine ($"[{driverName}] Duration: {stopwatch.Elapsed.TotalMilliseconds:F2} ms");
-    }
-
-    [Theory]
-    [InlineData ("fake")]
-    [InlineData ("windows")]
-    [InlineData ("dotnet")]
-    [InlineData ("unix")]
-    public void Application_AddTimeout_Run_TimedEvents (string driverName)
-    {
-        // Arrange
-        Application.Init (driverName: driverName);
-        var functionCalled = 0;
-        var stopwatch = new Stopwatch ();
-
-        // Act
-        bool Function ()
-        {
-            functionCalled++;
-
-            if (functionCalled == 10 && Application.Top is { Running: true })
-            {
-                stopwatch.Stop ();
-                Application.RequestStop ();
-
-                return false;
-            }
-
-            return true;
-        }
-
-        Application.AddTimeout (TimeSpan.FromMilliseconds (1), Function);
-
-        // Start timing just before running the application loop.
-        stopwatch.Start ();
-        Application.Run ();
-
-        // Assert
-        Assert.NotNull (Application.Top);
-        Application.Top.Dispose ();
-        Application.Shutdown ();
-        Assert.Equal (10, functionCalled);
-
-        // Output the elapsed time for this test case.
-        // ReSharper disable once Xunit.XunitTestWithConsoleOutput
-        // ReSharper disable once LocalizableElement
-        Console.WriteLine ($"[{driverName}] Duration: {stopwatch.Elapsed.TotalMilliseconds:F2} ms");
-
-        // Output elapsed duration to xUnit's test output
-        _output.WriteLine ($"[{driverName}] Duration: {stopwatch.Elapsed.TotalMilliseconds:F2} ms");
-    }
-
-    public static IEnumerable<object []> TestAddTimeout
-    {
-        get
-        {
-            // Goes fine
-            Action a1 = StartWindow;
-
-            yield return new object [] { a1, "Click Me", "Cancel", "Pew Pew", 0, 1, 2, 3, 4 };
-
-            // Also goes fine
-            Action a2 = () => Application.Invoke (StartWindow);
-
-            yield return new object [] { a2, "Click Me", "Cancel", "Pew Pew", 0, 1, 2, 3, 4 };
-        }
-    }
-
-    private static async void RunAsyncTest (object sender, EventArgs e)
-    {
-        Assert.Equal (clickMe, btn.Text);
-        Assert.Equal (zero, total);
-
-        btn.Text = "Cancel";
-        Interlocked.Increment (ref total);
-        btn.SetNeedsDraw ();
-
-        await Task.Run (
-                        () =>
-                        {
-                            try
-                            {
-                                Assert.Equal (cancel, btn.Text);
-                                Assert.Equal (one, total);
-
-                                RunSql ();
-                            }
-                            finally
-                            {
-                                SetReadyToRun ();
-                            }
-                        }
-                       )
-                  .ContinueWith (
-                                 async (s, e) =>
-                                 {
-                                     await Task.Delay (1000);
-                                     Assert.Equal (clickMe, btn.Text);
-                                     Assert.Equal (three, total);
-
-                                     Interlocked.Increment (ref total);
-
-                                     Assert.Equal (clickMe, btn.Text);
-                                     Assert.Equal (four, total);
-
-                                     taskCompleted = true;
-                                 },
-                                 TaskScheduler.FromCurrentSynchronizationContext ()
-                                );
-    }
-
-    private static void RunSql ()
-    {
-        Thread.Sleep (100);
-        Assert.Equal (cancel, btn.Text);
-        Assert.Equal (one, total);
-
-        Application.Invoke (
-                            () =>
-                            {
-                                btn.Text = "Pew Pew";
-                                Interlocked.Increment (ref total);
-                                btn.SetNeedsDraw ();
-                            }
-                           );
-    }
-
-    private static void SetReadyToRun ()
-    {
-        Thread.Sleep (100);
-        Assert.Equal (pewPew, btn.Text);
-        Assert.Equal (two, total);
-
-        Application.Invoke (
-                            () =>
-                            {
-                                btn.Text = "Click Me";
-                                Interlocked.Increment (ref total);
-                                btn.SetNeedsDraw ();
-                            }
-                           );
-    }
-
-    private static void StartWindow ()
-    {
-        var startWindow = new Window { Modal = true };
-
-        btn = new() { Text = "Click Me" };
-
-        btn.Accepting += RunAsyncTest;
-
-        var totalbtn = new Button { X = Pos.Right (btn), Text = "total" };
-
-        totalbtn.Accepting += (s, e) => { MessageBox.Query ("Count", $"Count is {total}", "Ok"); };
-
-        startWindow.Add (btn);
-        startWindow.Add (totalbtn);
-
-        Application.Run (startWindow);
-
-        Assert.Equal (clickMe, btn.Text);
-        Assert.Equal (four, total);
-
-        Application.RequestStop ();
-    }
-
-    private class MillisecondTolerance : IEqualityComparer<TimeSpan>
-    {
-        public MillisecondTolerance (int tolerance) { _tolerance = tolerance; }
-        private readonly int _tolerance;
-        public bool Equals (TimeSpan x, TimeSpan y) { return Math.Abs (x.Milliseconds - y.Milliseconds) <= _tolerance; }
-        public int GetHashCode (TimeSpan obj) { return obj.GetHashCode (); }
-    }
-
-    private class TestMainloop : IMainLoopDriver
-    {
-        private MainLoop mainLoop;
-        public bool EventsPending () { throw new NotImplementedException (); }
-        public void Iteration () { throw new NotImplementedException (); }
-        public void TearDown () { throw new NotImplementedException (); }
-        public void Setup (MainLoop mainLoop) { this.mainLoop = mainLoop; }
-        public void Wakeup () { throw new NotImplementedException (); }
-    }
-}

+ 0 - 1
Tests/UnitTests/Application/RunStateTests.cs

@@ -45,7 +45,6 @@ public class RunStateTests
 #endif
 
         Assert.Null (Application.Top);
-    //    Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 

+ 2 - 2
Tests/UnitTests/ConsoleDrivers/ConsoleDriverTests.cs

@@ -50,8 +50,8 @@ public class ConsoleDriverTests
     public void Init_Inits (Type driverType)
     {
         var driver = (IConsoleDriver)Activator.CreateInstance (driverType);
-        MainLoop ml = driver.Init ();
-        Assert.NotNull (ml);
+        driver.Init ();
+        // Note: MainLoop is no longer returned from Init() as part of legacy MainLoop removal
         Assert.NotNull (driver.Clipboard);
         Console.ForegroundColor = ConsoleColor.Red;
         Assert.Equal (ConsoleColor.Red, Console.ForegroundColor);

+ 0 - 1
Tests/UnitTests/View/Draw/AllViewsDrawTests.cs

@@ -12,7 +12,6 @@ public class AllViewsDrawTests (ITestOutputHelper output) : TestsAllViews
     {
         Application.ResetState (true);
         // Required for spinner view that wants to register timeouts
-        Application.MainLoop = new MainLoop (new FakeMainLoop (Application.Driver));
 
         var view = (View)CreateInstanceIfNotGeneric (viewType);
 

+ 0 - 1
Tests/UnitTests/View/Layout/LayoutTests.cs

@@ -12,7 +12,6 @@ public class LayoutTests (ITestOutputHelper output) : TestsAllViews
     {
 
         // Required for spinner view that wants to register timeouts
-        Application.MainLoop = new MainLoop (new FakeMainLoop (Application.Driver));
 
         var view = (View)CreateInstanceIfNotGeneric (viewType);
 

+ 0 - 1
Tests/UnitTests/Views/AllViewsTests.cs

@@ -14,7 +14,6 @@ public class AllViewsTests (ITestOutputHelper output) : TestsAllViews
     public void AllViews_Center_Properly (Type viewType)
     {
         // Required for spinner view that wants to register timeouts
-        Application.MainLoop = new (new FakeMainLoop (Application.Driver));
 
         var view = CreateInstanceIfNotGeneric (viewType);
 

+ 0 - 2
Tests/UnitTests/Views/Menuv1/MenuBarv1Tests.cs

@@ -623,7 +623,6 @@ public class MenuBarv1Tests (ITestOutputHelper output)
         Application.RaiseMouseEvent (new () { ScreenPosition = new (20, 5), Flags = MouseFlags.Button1Clicked });
 
         // Need to fool MainLoop into thinking it's running
-        Application.MainLoop.Running = true;
         AutoInitShutdownAttribute.RunIteration ();
         Assert.Equal (items [0], menu.Menus [0].Title);
 
@@ -815,7 +814,6 @@ public class MenuBarv1Tests (ITestOutputHelper output)
         Application.RaiseMouseEvent (new () { ScreenPosition = new (20, 5), Flags = MouseFlags.Button1Clicked });
 
         // Need to fool MainLoop into thinking it's running
-        Application.MainLoop.Running = true;
         AutoInitShutdownAttribute.RunIteration ();
         Assert.Equal (items [0], menu.Menus [0].Title);
 

+ 0 - 300
Tests/UnitTestsParallelizable/ConsoleDrivers/MainLoopDriverTests.cs

@@ -1,300 +0,0 @@
-using Xunit.Abstractions;
-
-// Alias Console to MockConsole so we don't accidentally use Console
-
-namespace UnitTests_Parallelizable.DriverTests;
-
-public class MainLoopDriverTests : UnitTests.Parallelizable.ParallelizableBase
-{
-    public MainLoopDriverTests (ITestOutputHelper output) { ConsoleDriver.RunningUnitTests = true; }
-
-    [Theory]
-    [InlineData (typeof (FakeDriver), typeof (FakeMainLoop))]
-    //[InlineData (typeof (DotNetDriver), typeof (NetMainLoop))]
-    //[InlineData (typeof (UnixDriver), typeof (UnixMainLoop))]
-    //[InlineData (typeof (WindowsDriver), typeof (WindowsMainLoop))]
-
-    //[InlineData (typeof (ANSIDriver), typeof (AnsiMainLoopDriver))]
-    public void MainLoop_AddTimeout_ValidIdleHandler_ReturnsToken (Type driverType, Type mainLoopDriverType)
-    {
-        var driver = (IConsoleDriver)Activator.CreateInstance (driverType);
-        var mainLoopDriver = (IMainLoopDriver)Activator.CreateInstance (mainLoopDriverType, driver);
-        var mainLoop = new MainLoop (mainLoopDriver);
-        var idleHandlerInvoked = false;
-
-        bool IdleHandler ()
-        {
-            idleHandlerInvoked = true;
-
-            return false;
-        }
-
-        var token = mainLoop.TimedEvents.Add(TimeSpan.Zero, IdleHandler);
-
-        Assert.NotNull (token);
-        Assert.False (idleHandlerInvoked); // Idle handler should not be invoked immediately
-        mainLoop.RunIteration (); // Run an iteration to process the idle handler
-        Assert.True (idleHandlerInvoked); // Idle handler should be invoked after processing
-        mainLoop.Dispose ();
-    }
-
-    [Theory]
-    [InlineData (typeof (FakeDriver), typeof (FakeMainLoop))]
-    //[InlineData (typeof (DotNetDriver), typeof (NetMainLoop))]
-    //[InlineData (typeof (UnixDriver), typeof (UnixMainLoop))]
-    //[InlineData (typeof (WindowsDriver), typeof (WindowsMainLoop))]
-
-    //[InlineData (typeof (ANSIDriver), typeof (AnsiMainLoopDriver))]
-    public void MainLoop_AddTimeout_ValidParameters_ReturnsToken (Type driverType, Type mainLoopDriverType)
-    {
-        var driver = (IConsoleDriver)Activator.CreateInstance (driverType);
-        var mainLoopDriver = (IMainLoopDriver)Activator.CreateInstance (mainLoopDriverType, driver);
-        var mainLoop = new MainLoop (mainLoopDriver);
-        var callbackInvoked = false;
-
-        object token = mainLoop.TimedEvents.Add (
-                                            TimeSpan.FromMilliseconds (100),
-                                            () =>
-                                            {
-                                                callbackInvoked = true;
-
-                                                return false;
-                                            }
-                                           );
-
-        Assert.NotNull (token);
-        mainLoop.RunIteration (); // Run an iteration to process the timeout
-        Assert.False (callbackInvoked); // Callback should not be invoked immediately
-        Thread.Sleep (200); // Wait for the timeout
-        mainLoop.RunIteration (); // Run an iteration to process the timeout
-        Assert.True (callbackInvoked); // Callback should be invoked after the timeout
-        mainLoop.Dispose ();
-    }
-
-    [Theory]
-    [InlineData (typeof (FakeDriver), typeof (FakeMainLoop))]
-    //[InlineData (typeof (DotNetDriver), typeof (NetMainLoop))]
-    //[InlineData (typeof (UnixDriver), typeof (UnixMainLoop))]
-    //[InlineData (typeof (WindowsDriver), typeof (WindowsMainLoop))]
-
-    //[InlineData (typeof (ANSIDriver), typeof (AnsiMainLoopDriver))]
-    public void MainLoop_CheckTimersAndIdleHandlers_IdleHandlersActive_ReturnsTrue (
-        Type driverType,
-        Type mainLoopDriverType
-    )
-    {
-        var driver = (IConsoleDriver)Activator.CreateInstance (driverType);
-        var mainLoopDriver = (IMainLoopDriver)Activator.CreateInstance (mainLoopDriverType, driver);
-        var mainLoop = new MainLoop (mainLoopDriver);
-
-        mainLoop.TimedEvents.Add (TimeSpan.Zero, () => false);
-        bool result = mainLoop.TimedEvents.CheckTimers (out int waitTimeout);
-
-        Assert.True (result);
-        Assert.Equal (0, waitTimeout);
-        mainLoop.Dispose ();
-    }
-
-    [Theory]
-    [InlineData (typeof (FakeDriver), typeof (FakeMainLoop))]
-    //[InlineData (typeof (DotNetDriver), typeof (NetMainLoop))]
-    //[InlineData (typeof (UnixDriver), typeof (UnixMainLoop))]
-    //[InlineData (typeof (WindowsDriver), typeof (WindowsMainLoop))]
-
-    //[InlineData (typeof (ANSIDriver), typeof (AnsiMainLoopDriver))]
-    public void MainLoop_CheckTimers_NoTimersOrIdleHandlers_ReturnsFalse (
-        Type driverType,
-        Type mainLoopDriverType
-    )
-    {
-        var driver = (IConsoleDriver)Activator.CreateInstance (driverType);
-        var mainLoopDriver = (IMainLoopDriver)Activator.CreateInstance (mainLoopDriverType, driver);
-        var mainLoop = new MainLoop (mainLoopDriver);
-
-        bool result = mainLoop.TimedEvents.CheckTimers (out int waitTimeout);
-
-        Assert.False (result);
-        Assert.Equal (-1, waitTimeout);
-        mainLoop.Dispose ();
-    }
-
-    [Theory]
-    [InlineData (typeof (FakeDriver), typeof (FakeMainLoop))]
-    //[InlineData (typeof (DotNetDriver), typeof (NetMainLoop))]
-    //[InlineData (typeof (UnixDriver), typeof (UnixMainLoop))]
-    //[InlineData (typeof (WindowsDriver), typeof (WindowsMainLoop))]
-
-    //[InlineData (typeof (ANSIDriver), typeof (AnsiMainLoopDriver))]
-    public void MainLoop_CheckTimersAndIdleHandlers_TimersActive_ReturnsTrue (
-        Type driverType,
-        Type mainLoopDriverType
-    )
-    {
-        var driver = (IConsoleDriver)Activator.CreateInstance (driverType);
-        var mainLoopDriver = (IMainLoopDriver)Activator.CreateInstance (mainLoopDriverType, driver);
-        var mainLoop = new MainLoop (mainLoopDriver);
-
-        mainLoop.TimedEvents.Add (TimeSpan.FromMilliseconds (100), () => false);
-        bool result = mainLoop.TimedEvents.CheckTimers(out int waitTimeout);
-
-        Assert.True (result);
-        Assert.True (waitTimeout >= 0);
-        mainLoop.Dispose ();
-    }
-
-    [Theory]
-    [InlineData (typeof (FakeDriver), typeof (FakeMainLoop))]
-    //[InlineData (typeof (DotNetDriver), typeof (NetMainLoop))]
-    //[InlineData (typeof (UnixDriver), typeof (UnixMainLoop))]
-    //[InlineData (typeof (WindowsDriver), typeof (WindowsMainLoop))]
-
-    //[InlineData (typeof (ANSIDriver), typeof (AnsiMainLoopDriver))]
-    public void MainLoop_Constructs_Disposes (Type driverType, Type mainLoopDriverType)
-    {
-        var driver = (IConsoleDriver)Activator.CreateInstance (driverType);
-        var mainLoopDriver = (IMainLoopDriver)Activator.CreateInstance (mainLoopDriverType, driver);
-        var mainLoop = new MainLoop (mainLoopDriver);
-
-        // Check default values
-        Assert.NotNull (mainLoop);
-        Assert.Equal (mainLoopDriver, mainLoop.MainLoopDriver);
-        Assert.Empty (mainLoop.TimedEvents.Timeouts);
-        Assert.False (mainLoop.Running);
-
-        // Clean up
-        mainLoop.Dispose ();
-
-        // TODO: It'd be nice if we could really verify IMainLoopDriver.TearDown was called
-        // and that it was actually cleaned up.
-        Assert.Null (mainLoop.MainLoopDriver);
-        Assert.Empty (mainLoop.TimedEvents.Timeouts);
-        Assert.False (mainLoop.Running);
-    }
-
-    [Theory]
-    [InlineData (typeof (FakeDriver), typeof (FakeMainLoop))]
-    //[InlineData (typeof (DotNetDriver), typeof (NetMainLoop))]
-    //[InlineData (typeof (UnixDriver), typeof (UnixMainLoop))]
-    //[InlineData (typeof (WindowsDriver), typeof (WindowsMainLoop))]
-
-    //[InlineData (typeof (ANSIDriver), typeof (AnsiMainLoopDriver))]
-    public void MainLoop_RemoveIdle_InvalidToken_ReturnsFalse (Type driverType, Type mainLoopDriverType)
-    {
-        var driver = (IConsoleDriver)Activator.CreateInstance (driverType);
-        var mainLoopDriver = (IMainLoopDriver)Activator.CreateInstance (mainLoopDriverType, driver);
-        var mainLoop = new MainLoop (mainLoopDriver);
-
-        bool result = mainLoop.TimedEvents.Remove("flibble");
-
-        Assert.False (result);
-        mainLoop.Dispose ();
-    }
-
-    [Theory]
-    [InlineData (typeof (FakeDriver), typeof (FakeMainLoop))]
-    //[InlineData (typeof (DotNetDriver), typeof (NetMainLoop))]
-    //[InlineData (typeof (UnixDriver), typeof (UnixMainLoop))]
-    //[InlineData (typeof (WindowsDriver), typeof (WindowsMainLoop))]
-
-    //[InlineData (typeof (ANSIDriver), typeof (AnsiMainLoopDriver))]
-    public void MainLoop_RemoveIdle_ValidToken_ReturnsTrue (Type driverType, Type mainLoopDriverType)
-    {
-        var driver = (IConsoleDriver)Activator.CreateInstance (driverType);
-        var mainLoopDriver = (IMainLoopDriver)Activator.CreateInstance (mainLoopDriverType, driver);
-        var mainLoop = new MainLoop (mainLoopDriver);
-
-        bool IdleHandler () { return false; }
-
-
-        var token = mainLoop.TimedEvents.Add (TimeSpan.Zero, IdleHandler);
-        bool result = mainLoop.TimedEvents.Remove (token);
-
-        Assert.True (result);
-        mainLoop.Dispose ();
-    }
-
-    [Theory]
-    [InlineData (typeof (FakeDriver), typeof (FakeMainLoop))]
-    //[InlineData (typeof (DotNetDriver), typeof (NetMainLoop))]
-    //[InlineData (typeof (UnixDriver), typeof (UnixMainLoop))]
-    //[InlineData (typeof (WindowsDriver), typeof (WindowsMainLoop))]
-
-    //[InlineData (typeof (ANSIDriver), typeof (AnsiMainLoopDriver))]
-    public void MainLoop_RemoveTimeout_InvalidToken_ReturnsFalse (Type driverType, Type mainLoopDriverType)
-    {
-        var driver = (IConsoleDriver)Activator.CreateInstance (driverType);
-        var mainLoopDriver = (IMainLoopDriver)Activator.CreateInstance (mainLoopDriverType, driver);
-        var mainLoop = new MainLoop (mainLoopDriver);
-
-        bool result = mainLoop.TimedEvents.Remove (new object ());
-
-        Assert.False (result);
-    }
-
-    [Theory]
-    [InlineData (typeof (FakeDriver), typeof (FakeMainLoop))]
-    //[InlineData (typeof (DotNetDriver), typeof (NetMainLoop))]
-    //[InlineData (typeof (UnixDriver), typeof (UnixMainLoop))]
-    //[InlineData (typeof (WindowsDriver), typeof (WindowsMainLoop))]
-
-    //[InlineData (typeof (ANSIDriver), typeof (AnsiMainLoopDriver))]
-    public void MainLoop_RemoveTimeout_ValidToken_ReturnsTrue (Type driverType, Type mainLoopDriverType)
-    {
-        var driver = (IConsoleDriver)Activator.CreateInstance (driverType);
-        var mainLoopDriver = (IMainLoopDriver)Activator.CreateInstance (mainLoopDriverType, driver);
-        var mainLoop = new MainLoop (mainLoopDriver);
-
-        object token = mainLoop.TimedEvents.Add (TimeSpan.FromMilliseconds (100), () => false);
-        bool result = mainLoop.TimedEvents.Remove (token);
-
-        Assert.True (result);
-        mainLoop.Dispose ();
-    }
-
-    [Theory]
-    [InlineData (typeof (FakeDriver), typeof (FakeMainLoop))]
-    //[InlineData (typeof (DotNetDriver), typeof (NetMainLoop))]
-    //[InlineData (typeof (UnixDriver), typeof (UnixMainLoop))]
-    //[InlineData (typeof (WindowsDriver), typeof (WindowsMainLoop))]
-
-    //[InlineData (typeof (ANSIDriver), typeof (AnsiMainLoopDriver))]
-    public void MainLoop_RunIteration_ValidIdleHandler_CallsIdleHandler (Type driverType, Type mainLoopDriverType)
-    {
-        var driver = (IConsoleDriver)Activator.CreateInstance (driverType);
-        var mainLoopDriver = (IMainLoopDriver)Activator.CreateInstance (mainLoopDriverType, driver);
-        var mainLoop = new MainLoop (mainLoopDriver);
-        var idleHandlerInvoked = false;
-
-        Func<bool> idleHandler = () =>
-                                 {
-                                     idleHandlerInvoked = true;
-
-                                     return false;
-                                 };
-
-        mainLoop.TimedEvents.Add (TimeSpan.Zero, idleHandler);
-        mainLoop.RunIteration (); // Run an iteration to process the idle handler
-
-        Assert.True (idleHandlerInvoked);
-        mainLoop.Dispose ();
-    }
-
-    //[Theory]
-    //[InlineData (typeof (FakeDriver), typeof (FakeMainLoop))]
-    ////[InlineData (typeof (DotNetDriver), typeof (NetMainLoop))]
-    ////[InlineData (typeof (UnixDriver), typeof (UnixMainLoop))]
-    ////[InlineData (typeof (WindowsDriver), typeof (WindowsMainLoop))]
-    //public void MainLoop_Invoke_ValidAction_RunsAction (Type driverType, Type mainLoopDriverType)
-    //{
-    //	var driver = (IConsoleDriver)Activator.CreateInstance (driverType);
-    //	var mainLoopDriver = (IMainLoopDriver)Activator.CreateInstance (mainLoopDriverType, new object [] { driver });
-    //	var mainLoop = new MainLoop (mainLoopDriver);
-    //	var actionInvoked = false;
-
-    //	mainLoop.Invoke (() => { actionInvoked = true; });
-    //	mainLoop.RunIteration (); // Run an iteration to process the action.
-
-    //	Assert.True (actionInvoked);
-    //	mainLoop.Dispose ();
-    //}
-}

+ 170 - 0
Tests/UnitTestsParallelizable/ConsoleDrivers/UrlHyperlinkerTests.cs

@@ -0,0 +1,170 @@
+#nullable enable
+using System.Text;
+using Xunit.Abstractions;
+
+namespace Terminal.Gui.DriverTests;
+
+public class Osc8UrlLinkerTests (ITestOutputHelper output)
+{
+    private readonly ITestOutputHelper _output = output;
+
+    [Theory]
+    [InlineData ("<https://example.com>", "<", "https://example.com", ">")]
+    [InlineData ("\"https://example.com\"", "\"", "https://example.com", "\"")]
+    public void WrapOsc8_Does_Not_Cross_Delimiters (string input, string prefix, string url, string suffix)
+    {
+        string actual = Wrap (input);
+        string expected = prefix + LinkWrappedWithOSCs (url) + suffix;
+        Assert.Equal (expected, actual);
+    }
+
+    [Theory]
+    [InlineData ("No url here")]
+    [InlineData ("http://")]
+    [InlineData ("://missing-scheme.com")]
+    public void WrapOsc8_Leaves_Text_Unchanged_Without_Urls (string input)
+    {
+        StringBuilder sb = new (input);
+        StringBuilder result = Osc8UrlLinker.WrapOsc8 (sb);
+
+        Assert.Same (sb, result);
+        Assert.Equal (input, result.ToString ());
+    }
+
+    [Fact]
+    public void WrapOsc8_Stops_At_Ansi_Escape_Sequence ()
+    {
+        var esc = "\x1B[38;2;173m";
+        string input = "https://example.com" + esc + "/more";
+
+        string wrapped = Wrap (input);
+        string expected = LinkWrappedWithOSCs ("https://example.com") + esc + "/more";
+        Assert.Equal (expected, wrapped);
+
+        // Verify that the hyperlinked visible content contains no ESC
+        string start = EscSeqUtils.OSC_StartHyperlink ("https://example.com");
+        string end = EscSeqUtils.OSC_EndHyperlink ();
+        int s = wrapped.IndexOf (start, StringComparison.Ordinal);
+        Assert.True (s >= 0);
+
+        int e = wrapped.IndexOf (end, s + start.Length, StringComparison.Ordinal);
+        Assert.True (e > s);
+
+        int contentStart = s + start.Length;
+        int contentLength = e - contentStart;
+        string visible = wrapped.Substring (contentStart, contentLength);
+
+        Assert.DoesNotContain ('\x1B', visible);
+        Assert.Equal ("https://example.com", visible);
+    }
+
+    [Theory]
+    [InlineData ("See https://example.com/path.", "See ", "https://example.com/path", ".")]
+    [InlineData ("See https://example.com/file.tar.gz,", "See ", "https://example.com/file.tar.gz", ",")]
+    [InlineData ("See https://example.com/path_(with)_parens)", "See ", "https://example.com/path_(with)_parens", ")")]
+    public void WrapOsc8_Trims_Trailing_Punctuation (string input, string prefix, string url, string suffix)
+    {
+        string actual = Wrap (input);
+        string expected = prefix + LinkWrappedWithOSCs (url) + suffix;
+        Assert.Equal (expected, actual);
+    }
+
+    [Theory]
+    [InlineData (
+                    "Multiple: https://a.com, https://b.com!",
+                    "Multiple: ",
+                    "https://a.com",
+                    ", ",
+                    "https://b.com",
+                    "!")]
+    [InlineData (
+                    "List https://one.com https://two.com https://three.com",
+                    "List ",
+                    "https://one.com",
+                    " ",
+                    "https://two.com",
+                    " ",
+                    "https://three.com",
+                    "")]
+    public void WrapOsc8_Wraps_Multiple_Urls (string input, params string [] segments)
+    {
+        // segments: text0, url1, text1, [url2, text2]...
+        string expected = BuildExpected (segments);
+
+        string actual = Wrap (input);
+        Assert.Equal (expected, actual);
+    }
+
+    [Theory]
+    [InlineData ("https://github.com", "https://github.com")]
+    [InlineData ("http://example.com", "http://example.com")]
+    [InlineData ("ftp://ftp.example.com/file.zip", "ftp://ftp.example.com/file.zip")]
+    [InlineData ("https://example.com:8080/path", "https://example.com:8080/path")]
+    [InlineData ("https://example.com/path#anchor", "https://example.com/path#anchor")]
+    [InlineData ("https://example.com/path?query=value&other=123", "https://example.com/path?query=value&other=123")]
+    [InlineData ("https://commons.wikimedia.org/wiki/File:Spinning_globe.gif", "https://commons.wikimedia.org/wiki/File:Spinning_globe.gif")]
+    public void WrapOsc8_Wraps_Standalone_Url (string input, string expectedUrl)
+    {
+        string actual = Wrap (input);
+        string expected = LinkWrappedWithOSCs (expectedUrl);
+        Assert.Equal (expected, actual);
+    }
+
+    [Theory]
+    [InlineData (
+                    "Visit https://github.com for more info",
+                    "Visit ",
+                    "https://github.com",
+                    " for more info")]
+    [InlineData (
+                    "Check out https://commons.wikimedia.org/wiki/File:Spinning_globe.gif!",
+                    "Check out ",
+                    "https://commons.wikimedia.org/wiki/File:Spinning_globe.gif",
+                    "!")]
+    [InlineData (
+                    "URLs: https://example.com and http://other.com",
+                    "URLs: ",
+                    "https://example.com",
+                    " and ",
+                    "http://other.com",
+                    "")]
+    public void WrapOsc8_Wraps_Urls_In_Text (string input, params string [] segments)
+    {
+        // segments: text0, url1, text1, [url2, text2]...
+        string expected = BuildExpected (segments);
+
+        string actual = Wrap (input);
+        Assert.Equal (expected, actual);
+    }
+
+    private static string BuildExpected (string [] segments)
+    {
+        // segments must be: text0, url1, text1, url2, text2, ...
+        string expected = segments.Length > 0 ? segments [0] : string.Empty;
+
+        for (var i = 1; i + 1 < segments.Length; i += 2)
+        {
+            string url = segments [i];
+            string textAfter = segments [i + 1];
+
+            expected += LinkWrappedWithOSCs (url);
+            expected += textAfter;
+        }
+
+        return expected;
+    }
+
+    private static string LinkWrappedWithOSCs (string url, string? display = null)
+    {
+        display ??= url;
+
+        return EscSeqUtils.OSC_StartHyperlink (url) + display + EscSeqUtils.OSC_EndHyperlink ();
+    }
+
+    private static string Wrap (string input)
+    {
+        StringBuilder sb = new (input);
+
+        return Osc8UrlLinker.WrapOsc8 (sb).ToString ();
+    }
+}

+ 1 - 1
Tests/UnitTestsParallelizable/MockConsoleDriver.cs

@@ -155,7 +155,7 @@ internal class MockConsoleDriver : IConsoleDriver
     public void UpdateCursor () {}
 
     /// <inheritdoc />
-    public MainLoop Init () { return null!; }
+    public void Init () { }
 
     /// <inheritdoc />
     public void End () {  }

+ 0 - 1
Tests/UnitTestsParallelizable/TestSetup.cs

@@ -47,7 +47,6 @@ public class GlobalTestSetup : IDisposable
         // Don't check Application.Force16Colors
         //Assert.False (Application.Force16Colors);
         Assert.Null (Application.Driver);
-        Assert.Null (Application.MainLoop);
         Assert.False (Application.EndAfterFirstIteration);
         Assert.Equal (Key.Tab.WithShift, Application.PrevTabKey);
         Assert.Equal (Key.Tab, Application.NextTabKey);

+ 632 - 57
docfx/docs/View.md

@@ -1,116 +1,691 @@
 # View Deep Dive
 
-## Hierarchy
+[View](~/api/Terminal.Gui.ViewBase.View.yml) is the base class for all visible UI elements in Terminal.Gui. View provides core functionality for layout, drawing, input handling, navigation, and scrolling. All interactive controls, windows, and dialogs derive from View.
 
-  * @Terminal.Gui.View - The base class for implementing higher-level visual/interactive Terminal.Gui elements. Implemented in the @Terminal.Gui.ViewBase.View base class.
-  
-  * *SubView* - A View that is contained in another view and will be rendered as part of the containing view's **ContentArea**. SubViews are added to another view via the @"Terminal.Gui.ViewBase.View.Add(Terminal.Gui.View)" method. A View may only be a SubView of a single View. Each View has a @Terminal.Gui.ViewBase.View.SubViews property that is a list of all SubViews that have been added.
-  
-  * @Terminal.Gui.View.SuperView - The View that is a container for SubViews. Each View has a @Terminal.Gui.ViewBase.View.SuperView property that references it's SuperView after it has been added.
-  
-  * *Child View* - A view that holds a reference to another view in a parent/child relationship. Terminal.Gui uses the terms "Child" and "Parent" sparingly. Generally SubView/SuperView is preferred.
-  
-  * *Parent View* - A view that holds a reference to another view in a parent/child relationship, but is NOT a SuperView of the child. Terminal.Gui uses the terms "Child" and "Parent" sparingly. Generally SubView/SuperView is preferred.
+See the [Views Overview](views.md) for a catalog of all built-in View subclasses.
+
+## Table of Contents
+
+- [View Hierarchy](#view-hierarchy)
+- [View Composition](#view-composition)
+- [Core Concepts](#core-concepts)
+- [View Lifecycle](#view-lifecycle)
+- [Subsystems](#subsystems)
+- [Common View Patterns](#common-view-patterns)
+- [Modal Views](#modal-views)
+
+---
+
+## View Hierarchy
+
+### Terminology
+
+- **[View](~/api/Terminal.Gui.ViewBase.View.yml)** - The base class for all visible UI elements
+- **SubView** - A View that is contained in another View and rendered as part of the containing View's content area. SubViews are added via [View.Add](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Add_Terminal_Gui_ViewBase_View_)
+- **SuperView** - The View that contains SubViews. Each View has a [View.SuperView](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_SuperView) property that references its container
+- **Child View** - A view that holds a reference to another view in a parent/child relationship (used sparingly; generally SubView/SuperView is preferred)
+- **Parent View** - A view that holds a reference to another view but is NOT a SuperView (used sparingly)
+
+### Key Properties
+
+- [View.SubViews](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_SubViews) - Read-only list of all SubViews added to this View
+- [View.SuperView](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_SuperView) - The View's container (null if the View has no container)
+- [View.Id](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Id) - Unique identifier for the View (should be unique among siblings)
+- [View.Data](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Data) - Arbitrary data attached to the View
 
-## Composition
+---
+
+## View Composition
+
+Views are composed of several nested layers that define how they are positioned, drawn, and scrolled:
 
 [!INCLUDE [View Composition](~/includes/view-composition.md)]
 
-### List of Built-In Views
+### The Layers
+
+1. **[Frame](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Frame)** - The outermost rectangle defining the View's location and size relative to the SuperView's content area
+2. **[Margin](~/api/Terminal.Gui.ViewBase.Margin.yml)** - Adornment that provides spacing between the View and other SubViews
+3. **[Border](~/api/Terminal.Gui.ViewBase.Border.yml)** - Adornment that draws the visual border and title
+4. **[Padding](~/api/Terminal.Gui.ViewBase.Padding.yml)** - Adornment that provides spacing between the border and the viewport
+5. **[Viewport](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Viewport)** - Rectangle describing the visible portion of the content area
+6. **Content Area** - The total area where content can be drawn (defined by [View.GetContentSize](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_GetContentSize))
+
+See the [Layout Deep Dive](layout.md) for complete details on View composition and layout.
+
+---
+
+## Core Concepts
+
+### Frame vs. Viewport
+
+- **Frame** - The View's location and size in SuperView-relative coordinates. Frame includes all adornments (Margin, Border, Padding)
+- **Viewport** - The visible "window" into the View's content, located inside the adornments. Viewport coordinates are always relative to (0,0) of the content area
+
+```csharp
+// Frame is SuperView-relative
+view.Frame = new Rectangle(10, 5, 50, 20);
+
+// Viewport is content-relative (the visible portal)
+view.Viewport = new Rectangle(0, 0, 45, 15); // Adjusted for adornments
+```
+
+### Content Area and Scrolling
+
+The **Content Area** is where the View's content is drawn. By default, the content area size matches the Viewport size. To enable scrolling:
+
+1. Call [View.SetContentSize](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_SetContentSize_System_Nullable_System_Drawing_Size__) with a size larger than the Viewport
+2. Change `Viewport.Location` to scroll the content
+
+See the [Scrolling Deep Dive](scrolling.md) for complete details.
+
+### Adornments
+
+[Adornments](~/api/Terminal.Gui.ViewBase.Adornment.yml) are special Views that surround the content:
+
+- **[Margin](~/api/Terminal.Gui.ViewBase.Margin.yml)** - Transparent spacing outside the Border
+- **[Border](~/api/Terminal.Gui.ViewBase.Border.yml)** - Visual frame with [LineStyle](~/api/Terminal.Gui.Drawing.LineStyle.yml), title, and arrangement UI
+- **[Padding](~/api/Terminal.Gui.ViewBase.Padding.yml)** - Spacing inside the Border, outside the Viewport
+
+Each adornment has a [Thickness](~/api/Terminal.Gui.Drawing.Thickness.yml) that defines the width of each side (Top, Right, Bottom, Left).
+
+See the [Layout Deep Dive](layout.md) for complete details on adornments.
+
+---
+
+## View Lifecycle
 
-See [List of Built-In Views](views.md)
+### Initialization
+
+Views implement [ISupportInitializeNotification](https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.isupportinitializenotification):
+
+1. **Constructor** - Creates the View and sets up default state
+2. **[BeginInit](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_BeginInit)** - Signals initialization is starting
+3. **[EndInit](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_EndInit)** - Signals initialization is complete; raises [View.Initialized](~/api/Terminal.Gui.ViewBase.View.yml) event
+4. **[IsInitialized](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_IsInitialized)** - Property indicating if initialization is complete
+
+### Disposal
+
+Views are [IDisposable](https://docs.microsoft.com/en-us/dotnet/api/system.idisposable):
+
+- Call [View.Dispose](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Dispose) to clean up resources
+- The [View.Disposing](~/api/Terminal.Gui.ViewBase.View.yml) event is raised when disposal begins
+- Automatically disposes SubViews, adornments, and scroll bars
+
+---
+
+## Subsystems
+
+View is organized as a partial class across multiple files, each handling a specific subsystem:
   
 ### Commands
 
 See the [Command Deep Dive](command.md).
 
-### Input
+- [View.AddCommand](~/api/Terminal.Gui.ViewBase.View.yml) - Declares commands the View supports
+- [View.InvokeCommand](~/api/Terminal.Gui.ViewBase.View.yml) - Invokes a command
+- [Command](~/api/Terminal.Gui.Input.Command.yml) enum - Standard set of commands (Accept, Select, HotKey, etc.)
+
+### Input Handling
+
+#### Keyboard
 
-See the [Keyboard Deep Dive](keyboard.md) and [Mouse Deep Dive](mouse.md).
+See the [Keyboard Deep Dive](keyboard.md).
+
+- [View.KeyBindings](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_KeyBindings) - Maps keys to Commands
+- [View.HotKey](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_HotKey) - The hot key for the View
+- [View.HotKeySpecifier](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_HotKeySpecifier) - Character used to denote hot keys in text (default: '_')
+- Events: `KeyDown`, `KeyUp`, `InvokingKeyBindings`
+
+#### Mouse
+
+See the [Mouse Deep Dive](mouse.md).
+
+- [View.MouseBindings](~/api/Terminal.Gui.ViewBase.View.yml) - Maps mouse events to Commands
+- [View.WantContinuousButtonPresses](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_WantContinuousButtonPresses) - Enables continuous button press events
+- [View.Highlight](~/api/Terminal.Gui.ViewBase.View.yml) - Event for visual feedback on mouse hover/click
+- [View.HighlightStyle](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_HighlightStyle) - Visual style when highlighted
+- Events: `MouseEnter`, `MouseLeave`, `MouseClick`, `MouseEvent`
 
 ### Layout and Arrangement
 
-See the [Layout Deep Dive](layout.md) and the [Arrangement Deep Dive](arrangement.md).
+See the [Layout Deep Dive](layout.md) and [Arrangement Deep Dive](arrangement.md).
+
+#### Position and Size
+
+- [View.X](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_X) - Horizontal position using [Pos](~/api/Terminal.Gui.Pos.yml)
+- [View.Y](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Y) - Vertical position using [Pos](~/api/Terminal.Gui.Pos.yml)
+- [View.Width](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Width) - Width using [Dim](~/api/Terminal.Gui.Dim.yml)
+- [View.Height](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Height) - Height using [Dim](~/api/Terminal.Gui.Dim.yml)
+
+#### Layout Features
+
+- [Dim.Auto](~/api/Terminal.Gui.Dim.yml#Terminal_Gui_Dim_Auto_Terminal_Gui_DimAutoStyle_Terminal_Gui_Dim_Terminal_Gui_Dim_) - Automatic sizing based on content
+- [Pos.AnchorEnd](~/api/Terminal.Gui.Pos.yml#Terminal_Gui_Pos_AnchorEnd_System_Int32_) - Anchor to right/bottom edges
+- [Pos.Align](~/api/Terminal.Gui.Pos.yml) - Align views relative to each other
+- [Pos.Center](~/api/Terminal.Gui.Pos.yml) - Center within SuperView
+- [Dim.Fill](~/api/Terminal.Gui.Dim.yml) - Fill available space
+
+#### Arrangement
+
+- [View.Arrangement](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Arrangement) - Controls if View is movable/resizable
+- [ViewArrangement](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml) - Flags: Fixed, Movable, Resizable, Overlapped
+
+#### Events
+
+- `LayoutStarted` - Before layout begins
+- `LayoutComplete` - After layout completes
+- `FrameChanged` - When Frame changes
+- `ViewportChanged` - When Viewport changes
 
 ### Drawing
 
 See the [Drawing Deep Dive](drawing.md).
 
-Views should use viewport-relative coordinates for all drawing operations. The `View.Move(col, row)` method positions the cursor using viewport-relative coordinates. For screen dimensions, use @Terminal.Gui.App.Application.Screen instead of accessing the driver directly.
+#### Color and Style
+
+- [View.Scheme](~/api/Terminal.Gui.ViewBase.View.yml) - Color scheme for the View
+- [View.SetAttribute](~/api/Terminal.Gui.ViewBase.View.yml) - Sets the attribute for subsequent drawing
+- [View.SetAttributeForRole](~/api/Terminal.Gui.ViewBase.View.yml) - Sets attribute based on [VisualRole](~/api/Terminal.Gui.Drawing.VisualRole.yml)
+
+See the [Scheme Deep Dive](scheme.md) for details on color theming.
+
+#### Drawing Methods
+
+- [View.Draw](~/api/Terminal.Gui.ViewBase.View.yml) - Main drawing method
+- [View.AddRune](~/api/Terminal.Gui.ViewBase.View.yml) - Draws a single Rune
+- [View.AddStr](~/api/Terminal.Gui.ViewBase.View.yml) - Draws a string
+- [View.Move](~/api/Terminal.Gui.ViewBase.View.yml) - Positions the cursor
+- [View.Clear](~/api/Terminal.Gui.ViewBase.View.yml) - Clears the View's content
+
+#### Drawing Events
+
+- `DrawingContent` - Before content is drawn
+- `DrawingContentComplete` - After content is drawn
+- `DrawingAdornments` - Before adornments are drawn
+- `DrawingAdornmentsComplete` - After adornments are drawn
+
+#### Invalidation
+
+- [View.SetNeedsDraw](~/api/Terminal.Gui.ViewBase.View.yml) - Marks View as needing redraw
+- [View.NeedsDraw](~/api/Terminal.Gui.ViewBase.View.yml) - Property indicating if View needs redraw
 
 ### Navigation
 
 See the [Navigation Deep Dive](navigation.md).
 
+- [View.CanFocus](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_CanFocus) - Whether the View can receive keyboard focus
+- [View.HasFocus](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_HasFocus) - Whether the View currently has focus
+- [View.TabStop](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_TabStop) - [TabBehavior](~/api/Terminal.Gui.Input.TabBehavior.yml) for tab navigation
+- [View.TabIndex](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_TabIndex) - Order in tab navigation
+- [View.SetFocus](~/api/Terminal.Gui.ViewBase.View.yml) - Gives focus to the View
+
+Events:
+- `HasFocusChanging` - Before focus changes (cancellable)
+- `HasFocusChanged` - After focus changes
+- `Accepting` - When Command.Accept is invoked (typically Enter key)
+- `Accepted` - After Command.Accept completes
+- `Selecting` - When Command.Select is invoked (typically Space or mouse click)
+- `Selected` - After Command.Select completes
+
 ### Scrolling
 
 See the [Scrolling Deep Dive](scrolling.md).
 
-## Modal Views
+- [View.Viewport](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Viewport) - Visible portion of the content area
+- [View.GetContentSize](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_GetContentSize) - Returns size of scrollable content
+- [View.SetContentSize](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_SetContentSize_System_Nullable_System_Drawing_Size__) - Sets size of scrollable content
+- [View.ScrollHorizontal](~/api/Terminal.Gui.ViewBase.View.yml) - Scrolls content horizontally
+- [View.ScrollVertical](~/api/Terminal.Gui.ViewBase.View.yml) - Scrolls content vertically
+- [View.VerticalScrollBar](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_VerticalScrollBar) - Built-in vertical scrollbar
+- [View.HorizontalScrollBar](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_HorizontalScrollBar) - Built-in horizontal scrollbar
+- [View.ViewportSettings](~/api/Terminal.Gui.ViewBase.View.yml) - [ViewportSettingsFlags](~/api/Terminal.Gui.ViewBase.ViewportSettingsFlags.yml) controlling scroll behavior
+
+### Text
+
+- [View.Text](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Text) - The View's text content
+- [View.Title](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Title) - The View's title (shown in Border)
+- [View.TextFormatter](~/api/Terminal.Gui.ViewBase.View.yml) - Handles text formatting and alignment
+- [View.TextDirection](~/api/Terminal.Gui.ViewBase.View.yml) - Text direction (LeftRight, RightToLeft, TopToBottom)
+- [View.TextAlignment](~/api/Terminal.Gui.ViewBase.View.yml) - Text alignment (Left, Centered, Right, Justified)
+- [View.VerticalTextAlignment](~/api/Terminal.Gui.ViewBase.View.yml) - Vertical alignment (Top, Middle, Bottom, Justified)
+
+---
+
+## View Lifecycle
+
+### 1. Creation
+
+```csharp
+View view = new ()
+{
+    X = Pos.Center(),
+    Y = Pos.Center(),
+    Width = Dim.Percent(50),
+    Height = Dim.Fill()
+};
+```
+
+### 2. Initialization
+
+When a View is added to a SuperView or when [Application.Run](~/api/Terminal.Gui.App.Application.yml#Terminal_Gui_App_Application_Run_Terminal_Gui_Views_Toplevel_System_Func_System_Exception_System_Boolean__) is called:
+
+1. [BeginInit](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_BeginInit) is called
+2. [EndInit](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_EndInit) is called
+3. [IsInitialized](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_IsInitialized) becomes true
+4. [Initialized](~/api/Terminal.Gui.ViewBase.View.yml) event is raised
+
+### 3. Layout
+
+Layout happens automatically when needed:
+
+1. [View.SetNeedsLayout](~/api/Terminal.Gui.ViewBase.View.yml) marks View as needing layout
+2. [View.Layout](~/api/Terminal.Gui.ViewBase.View.yml) calculates position and size
+3. `LayoutStarted` event is raised
+4. Frame and Viewport are calculated based on X, Y, Width, Height
+5. SubViews are laid out
+6. `LayoutComplete` event is raised
+
+### 4. Drawing
+
+Drawing happens automatically when needed:
+
+1. [View.SetNeedsDraw](~/api/Terminal.Gui.ViewBase.View.yml) marks View as needing redraw
+2. [View.Draw](~/api/Terminal.Gui.ViewBase.View.yml) renders the View
+3. `DrawingContent` event is raised
+4. [View.OnDrawingContent](~/api/Terminal.Gui.ViewBase.View.yml) is called (override to draw custom content)
+5. `DrawingContentComplete` event is raised
+6. Adornments are drawn
+7. SubViews are drawn
+
+### 5. Input Processing
+
+Input is processed in this order:
+
+1. **Keyboard**: Key → KeyBindings → Command → Command Handlers → Events
+2. **Mouse**: MouseEvent → MouseBindings → Command → Command Handlers → Events
+
+### 6. Disposal
+
+```csharp
+view.Dispose();
+```
+
+- Raises [View.Disposing](~/api/Terminal.Gui.ViewBase.View.yml) event
+- Disposes adornments, scrollbars, SubViews
+- Cleans up event handlers and resources
+
+---
+
+## Subsystems
+
+### Commands
 
-Views can either be Modal or Non-modal. Modal views take over all user input until the user closes the View. Examples of Modal Views are Toplevel, Dialog, and Wizard. Non-modal views can be used to create a new experience in your application, one where you would have a new top-level menu for example. Setting the `Modal` property on a View to `true` makes it modal.
+See the [Command Deep Dive](command.md) for complete details.
 
-To run any View (but especially Dialogs, Windows, or Toplevels) modally, invoke the `Application.Run` method on a Toplevel. Use the `Application.RequestStop()` method to terminate the modal execution.
+Views use a command pattern for handling input:
 
 ```csharp
+// Add a command the view supports
+view.AddCommand (Command.Accept, () => 
+{
+    // Handle the Accept command
+    return true;
+});
+
+// Bind a key to the command
+view.KeyBindings.Add (Key.Enter, Command.Accept);
+
+// Bind a mouse action to the command
+view.MouseBindings.Add (MouseFlags.Button1Clicked, Command.Select);
+```
+
+### Input
+
+#### Keyboard
+
+See the [Keyboard Deep Dive](keyboard.md) for complete details.
 
+The keyboard subsystem processes key presses through:
+
+1. [View.KeyDown](~/api/Terminal.Gui.ViewBase.View.yml) event (cancellable)
+2. [View.OnKeyDown](~/api/Terminal.Gui.ViewBase.View.yml) virtual method
+3. [View.KeyBindings](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_KeyBindings) - Converts keys to commands
+4. Command handlers (registered via [View.AddCommand](~/api/Terminal.Gui.ViewBase.View.yml))
+5. [View.KeyUp](~/api/Terminal.Gui.ViewBase.View.yml) event
+
+#### Mouse
+
+See the [Mouse Deep Dive](mouse.md) for complete details.
+
+The mouse subsystem processes mouse events through:
+
+1. [View.MouseEvent](~/api/Terminal.Gui.ViewBase.View.yml) event (low-level)
+2. [View.OnMouseEvent](~/api/Terminal.Gui.ViewBase.View.yml) virtual method
+3. [View.MouseEnter](~/api/Terminal.Gui.ViewBase.View.yml) / [View.MouseLeave](~/api/Terminal.Gui.ViewBase.View.yml) events
+4. [View.MouseBindings](~/api/Terminal.Gui.ViewBase.View.yml) - Converts mouse actions to commands
+5. Command handlers
+6. [View.MouseClick](~/api/Terminal.Gui.ViewBase.View.yml) event (high-level)
+
+### Layout
+
+See the [Layout Deep Dive](layout.md) for complete details.
+
+Layout is declarative using [Pos](~/api/Terminal.Gui.Pos.yml) and [Dim](~/api/Terminal.Gui.Dim.yml):
+
+```csharp
+var label = new Label { Text = "Name:" };
+var textField = new TextField 
+{ 
+    X = Pos.Right(label) + 1,
+    Y = Pos.Top(label),
+    Width = Dim.Fill()
+};
 ```
 
-There is no return value from running modally, so the modal view must have a mechanism to indicate the reason the modal was closed. In the case above, the `okpressed` value is set to true if the user pressed or selected the `Ok` button.
+The layout system automatically:
+- Calculates Frame based on X, Y, Width, Height
+- Handles Adornment thickness
+- Calculates Viewport
+- Lays out SubViews recursively
 
-### Dialogs
+### Drawing
 
-[Dialogs](~/api/Terminal.Gui.Views.Dialog.yml) are Modal [Windows](~/api/Terminal.Gui.Views.Window.yml) that are centered in the middle of the screen and are intended to be used modally - that is, they run, and they are expected to return a result before resuming execution of the application.
+See the [Drawing Deep Dive](drawing.md) for complete details.
 
-Dialogs expose an API for adding buttons and managing the layout such that buttons are at the bottom of the dialog (e.g. [`AddButton`](https://migueldeicaza.github.io/gui.cs/api/Terminal.Gui.Dialog.yml#Terminal_Gui_Dialog_AddButton_Terminal_Gui_Button_)).
+Views draw themselves using viewport-relative coordinates:
 
-Example:
 ```csharp
-bool okpressed = false;
-var ok = new Button() { Title = "Ok" };
-var cancel = new Button() { Title = "Cancel" };
-var dialog = new Dialog () { Text = "Are you sure you want to quit?", Title = "Quit", Buttons = { ok, cancel } };
+protected override bool OnDrawingContent()
+{
+    // Draw at viewport coordinates (0,0)
+    Move(0, 0);
+    SetAttribute(new Attribute(Color.White, Color.Blue));
+    AddStr("Hello, Terminal.Gui!");
+    
+    return true;
+}
 ```
 
-Which will show something like this:
+Key drawing concepts:
+- [LineCanvas](~/api/Terminal.Gui.Drawing.LineCanvas.yml) - For drawing lines with auto-joining
+- [Attribute](~/api/Terminal.Gui.Drawing.Attribute.yml) - Color and text style
+- [TextStyle](~/api/Terminal.Gui.Drawing.TextStyle.yml) - Bold, Italic, Underline, etc.
+- [Gradient](~/api/Terminal.Gui.Drawing.Gradient.yml) / [GradientFill](~/api/Terminal.Gui.Drawing.GradientFill.yml) - Color gradients
 
+### Navigation
+
+See the [Navigation Deep Dive](navigation.md) for complete details.
+
+Navigation controls keyboard focus movement:
+
+- [View.CanFocus](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_CanFocus) - Whether View can receive focus
+- [View.TabStop](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_TabStop) - [TabBehavior](~/api/Terminal.Gui.Input.TabBehavior.yml) (NoStop, TabStop, TabGroup)
+- [View.TabIndex](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_TabIndex) - Tab order within SuperView
+- [View.SetFocus](~/api/Terminal.Gui.ViewBase.View.yml) - Requests focus
+- [View.AdvanceFocus](~/api/Terminal.Gui.ViewBase.View.yml) - Moves focus to next/previous View
+
+### Scrolling
+
+See the [Scrolling Deep Dive](scrolling.md) for complete details.
+
+Scrolling is built into every View:
+
+```csharp
+// Set content size larger than viewport
+view.SetContentSize(new Size(100, 100));
+
+// Scroll the content
+view.Viewport = view.Viewport with { Location = new Point(10, 10) };
+
+// Or use helper methods
+view.ScrollVertical(5);
+view.ScrollHorizontal(3);
+
+// Enable scrollbars
+view.VerticalScrollBar.Visible = true;
+view.HorizontalScrollBar.Visible = true;
 ```
-+- Quit -----------------------------------------------+
-|            Are you sure you want to quit?            |
-|                                                      |
-|                  [ Ok ] [ Cancel ]                   |
-+------------------------------------------------------+
+
+---
+
+## Common View Patterns
+
+### Creating a Custom View
+
+```csharp
+public class MyCustomView : View
+{
+    public MyCustomView()
+    {
+        // Set up default size
+        Width = Dim.Auto();
+        Height = Dim.Auto();
+        
+        // Can receive focus
+        CanFocus = true;
+        
+        // Add supported commands
+        AddCommand(Command.Accept, HandleAccept);
+        
+        // Configure key bindings
+        KeyBindings.Add(Key.Enter, Command.Accept);
+    }
+    
+    protected override bool OnDrawingContent()
+    {
+        // Draw custom content using viewport coordinates
+        Move(0, 0);
+        SetAttributeForRole(VisualRole.Normal);
+        AddStr("My custom content");
+        
+        return true; // Handled
+    }
+    
+    private bool HandleAccept()
+    {
+        // Handle the Accept command
+        // Raise events, update state, etc.
+        return true; // Handled
+    }
+}
 ```
 
-### Wizards
+### Adding SubViews
 
-[Wizards](~/api/Terminal.Gui.Views.Wizard.yml) are Dialogs that let users step through a series of steps to complete a task. 
+```csharp
+var container = new View
+{
+    Width = Dim.Fill(),
+    Height = Dim.Fill()
+};
+
+var button1 = new Button { Text = "OK", X = 2, Y = 2 };
+var button2 = new Button { Text = "Cancel", X = Pos.Right(button1) + 2, Y = 2 };
 
+container.Add(button1, button2);
 ```
-╔╡Gandolf - The last step╞════════════════════════════════════╗
-║                                     The wizard is complete! ║
-║☐ Enable Final Final Step                                    ║
-║                                     Press the Finish        ║
-║                                     button to continue.     ║
-║                                                             ║
-║                                     Pressing ESC will       ║
-║                                     cancel the wizard.      ║
-║                                                             ║
-║                                                             ║
-║─────────────────────────────────────────────────────────────║
-║⟦ Back ⟧                                         ⟦► Finish ◄⟧║
-╚═════════════════════════════════════════════════════════════╝
+
+### Using Adornments
+
+```csharp
+var view = new View
+{
+    BorderStyle = LineStyle.Double,
+    Title = "My View"
+};
+
+// Configure border
+view.Border.Thickness = new Thickness(1);
+view.Border.Settings = BorderSettings.Title;
+
+// Add padding
+view.Padding.Thickness = new Thickness(1);
+
+// Add margin
+view.Margin.Thickness = new Thickness(2);
+```
+
+### Implementing Scrolling
+
+```csharp
+var view = new View
+{
+    Width = 40,
+    Height = 20
+};
+
+// Set content larger than viewport
+view.SetContentSize(new Size(100, 100));
+
+// Enable scrollbars with auto-show
+view.VerticalScrollBar.AutoShow = true;
+view.HorizontalScrollBar.AutoShow = true;
+
+// Add key bindings for scrolling
+view.KeyBindings.Add(Key.CursorUp, Command.ScrollUp);
+view.KeyBindings.Add(Key.CursorDown, Command.ScrollDown);
+view.KeyBindings.Add(Key.CursorLeft, Command.ScrollLeft);
+view.KeyBindings.Add(Key.CursorRight, Command.ScrollRight);
+
+// Add command handlers
+view.AddCommand(Command.ScrollUp, () => { view.ScrollVertical(-1); return true; });
+view.AddCommand(Command.ScrollDown, () => { view.ScrollVertical(1); return true; });
 ```
 
+---
+
+## Modal Views
+
+Views can run modally (exclusively capturing all input until closed). See [Toplevel](~/api/Terminal.Gui.Views.Toplevel.yml) for details.
+
+### Running a View Modally
 
-## Application Concepts 
+```csharp
+var dialog = new Dialog
+{
+    Title = "Confirmation",
+    Width = Dim.Percent(50),
+    Height = Dim.Percent(50)
+};
 
-  * *TopLevel* - The v1 term used to describe a view that can have a MenuBar and/or StatusBar. In v2, we will delete the `TopLevel` class and ensure ANY View can have a menu bar and/or status bar (via `Adornments`).
-    * NOTE: There will still be an `Application.Top` which is the [View](~/api/Terminal.Gui.ViewBase.View.yml) that is the root of the `Application`'s view hierarchy.
+// Add content...
+var label = new Label { Text = "Are you sure?", X = Pos.Center(), Y = 1 };
+dialog.Add(label);
 
-  * *Runnable* - TBD
+// Run modally - blocks until closed
+Application.Run(dialog);
 
-  * *Modal* - *Modal* - The term used when describing a [View](~/api/Terminal.Gui.Viewbase.View.yml) that was created using the `Application.Run(view)` or `Application.Run<T>` APIs. When a View is running as a modal, user input is restricted to just that View until `Application.Run` exits. A `Modal` View has its own `RunState`. 
-    * In v1, classes derived from `Dialog` were originally thought to only work modally. However, `Wizard` proved that a `Dialog`-based class can also work non-modally. 
-    * In v2, we will simplify the `Dialog` class, and let any class be run via `Applicaiton.Run`. The `Modal` property will be set by `Application.Run` so the class can detect it is running modally if it needs to. 
+// Dialog has been closed
+```
+
+### Modal View Types
+
+- **[Toplevel](~/api/Terminal.Gui.Views.Toplevel.yml)** - Base class for modal views, can fill entire screen
+- **[Window](~/api/Terminal.Gui.Views.Window.yml)** - Overlapped container with border and title
+- **[Dialog](~/api/Terminal.Gui.Views.Dialog.yml)** - Modal Window, centered with button support
+- **[Wizard](~/api/Terminal.Gui.Views.Wizard.yml)** - Multi-step modal dialog
+
+### Dialog Example
+
+[Dialogs](~/api/Terminal.Gui.Views.Dialog.yml) are Modal [Windows](~/api/Terminal.Gui.Views.Window.yml) centered on screen:
+
+```csharp
+bool okPressed = false;
+var ok = new Button { Text = "Ok" };
+ok.Accepting += (s, e) => { okPressed = true; Application.RequestStop(); };
+
+var cancel = new Button { Text = "Cancel" };
+cancel.Accepting += (s, e) => Application.RequestStop();
+
+var dialog = new Dialog 
+{ 
+    Title = "Quit",
+    Width = 50,
+    Height = 10
+};
+dialog.Add(new Label { Text = "Are you sure you want to quit?", X = Pos.Center(), Y = 2 });
+dialog.AddButton(ok);
+dialog.AddButton(cancel);
+
+Application.Run(dialog);
+
+if (okPressed)
+{
+    // User clicked OK
+}
+```
+
+Which displays:
+
+```
+╔═ Quit ═══════════════════════════════════════════╗
+║                                                  ║
+║          Are you sure you want to quit?         ║
+║                                                  ║
+║                                                  ║
+║                                                  ║
+║                [ Ok ]  [ Cancel ]                ║
+╚══════════════════════════════════════════════════╝
+```
+
+### Wizard Example
+
+[Wizards](~/api/Terminal.Gui.Views.Wizard.yml) let users step through multiple pages:
+
+```csharp
+var wizard = new Wizard { Title = "Setup Wizard" };
+
+var step1 = new WizardStep { Title = "Welcome" };
+step1.Add(new Label { Text = "Welcome to the wizard!", X = 1, Y = 1 });
+
+var step2 = new WizardStep { Title = "Configuration" };
+step2.Add(new TextField { X = 1, Y = 1, Width = 30 });
+
+wizard.AddStep(step1);
+wizard.AddStep(step2);
+
+Application.Run(wizard);
+```
+
+---
+
+## Advanced Topics
+
+### View Diagnostics
+
+[View.Diagnostics](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Diagnostics) - [ViewDiagnosticFlags](~/api/Terminal.Gui.ViewBase.ViewDiagnosticFlags.yml) for debugging:
+
+- `Ruler` - Shows a ruler around the View
+- `DrawIndicator` - Shows an animated indicator when drawing
+- `FramePadding` - Highlights the Frame with color
+
+### View States
+
+- [View.Enabled](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Enabled) - Whether the View is enabled
+- [View.Visible](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Visible) - Whether the View is visible
+- [View.CanFocus](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_CanFocus) - Whether the View can receive focus
+- [View.HasFocus](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_HasFocus) - Whether the View currently has focus
+
+### Shadow Effects
+
+[View.ShadowStyle](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_ShadowStyle) - [ShadowStyle](~/api/Terminal.Gui.ViewBase.ShadowStyle.yml) for drop shadows:
+
+```csharp
+view.ShadowStyle = ShadowStyle.Transparent;
+```
 
+---
+
+## See Also
+
+- **[Views Overview](views.md)** - Complete list of all built-in Views
+- **[Layout Deep Dive](layout.md)** - Detailed layout system documentation
+- **[Drawing Deep Dive](drawing.md)** - Drawing system and color management
+- **[Keyboard Deep Dive](keyboard.md)** - Keyboard input handling
+- **[Mouse Deep Dive](mouse.md)** - Mouse input handling
+- **[Navigation Deep Dive](navigation.md)** - Focus and navigation system
+- **[Scrolling Deep Dive](scrolling.md)** - Scrolling and viewport management
+- **[Command Deep Dive](command.md)** - Command pattern and bindings
+- **[Arrangement Deep Dive](arrangement.md)** - Movable and resizable views
+- **[Configuration Deep Dive](config.md)** - Configuration and persistence
+- **[Scheme Deep Dive](scheme.md)** - Color theming

+ 684 - 51
docfx/docs/arrangement.md

@@ -1,102 +1,735 @@
-# View Layout Arrangement
+# View Arrangement Deep Dive
 
-Terminal.Gui provides a feature of Layout known as **Arrangement**, which controls how the user can use the mouse and keyboard to arrange views and enables either **Tiled** or **Overlapped** layouts. Arrangement is a sub-topic of [Layout](layout.md).
+Terminal.Gui provides a powerful **Arrangement** system that enables users to interactively move and resize views using the keyboard and mouse. This system supports both **Tiled** and **Overlapped** layout modes, allowing for flexible UI organization.
 
-## Arrangement Taxonomy & Lexicon
+See the [Layout Deep Dive](layout.md) for the broader layout system context.
+
+## Table of Contents
+
+- [Overview](#overview)
+- [Arrangement Modes](#arrangement-modes)
+- [Arrange Mode (Interactive)](#arrange-mode-interactive)
+- [Tiled vs Overlapped Layouts](#tiled-vs-overlapped-layouts)
+- [Movable Views](#movable-views)
+- [Resizable Views](#resizable-views)
+- [Creating Resizable Splitters](#creating-resizable-splitters)
+- [Modal Views](#modal-views)
+- [Runnable Views](#runnable-views)
+- [Examples](#examples)
+
+---
+
+## Overview
+
+The [View.Arrangement](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Arrangement) property controls how users can arrange views within their [SuperView](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_SuperView). The [ViewArrangement](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml) enum provides flags that can be combined to specify arrangement behavior.
+
+### Arrangement Lexicon
 
 [!INCLUDE [Arrangement Lexicon](~/includes/arrangement-lexicon.md)]
 
-## Arrangement
+### ViewArrangement Flags
+
+The [ViewArrangement](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml) enum supports these flags (can be combined):
+
+- **Fixed** (0) - View cannot be moved or resized (default)
+- **Movable** (1) - View can be moved by the user
+- **LeftResizable** (2) - Left edge can be resized
+- **RightResizable** (4) - Right edge can be resized
+- **TopResizable** (8) - Top edge can be resized
+- **BottomResizable** (16) - Bottom edge can be resized
+- **Resizable** (30) - All edges can be resized (combines all resize flags)
+- **Overlapped** (32) - View overlaps other views (enables Z-order)
+
+---
+
+## Arrangement Modes
+
+### Fixed (Default)
+
+Views with [ViewArrangement.Fixed](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml) cannot be moved or resized by the user:
+
+```csharp
+var view = new View
+{
+    Arrangement = ViewArrangement.Fixed // Default
+};
+```
+
+### Movable
+
+Views with [ViewArrangement.Movable](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml) can be dragged with the mouse or moved with keyboard:
+
+```csharp
+var window = new Window
+{
+    Title = "Movable Window",
+    Arrangement = ViewArrangement.Movable
+};
+```
+
+**User Interaction:**
+- **Mouse**: Drag the top [Border](~/api/Terminal.Gui.ViewBase.Border.yml)
+- **Keyboard**: Press `Ctrl+F5` to enter Arrange Mode, use arrow keys to move
+
+### Resizable
+
+Views with [ViewArrangement.Resizable](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml) can be resized by the user:
+
+```csharp
+var window = new Window
+{
+    Title = "Resizable Window",
+    Arrangement = ViewArrangement.Resizable
+};
+```
+
+**User Interaction:**
+- **Mouse**: Drag any border edge
+- **Keyboard**: Press `Ctrl+F5` to enter Arrange Mode, press `Tab` to cycle resize handles
+
+### Movable and Resizable
+
+Combine flags for full desktop-like experience:
+
+```csharp
+var window = new Window
+{
+    Title = "Movable and Resizable",
+    Arrangement = ViewArrangement.Movable | ViewArrangement.Resizable
+};
+```
+
+**Note:** When both `Movable` and `Resizable` are set, the top edge cannot be resized (Movable takes precedence).
+
+### Individual Edge Resizing
+
+For fine-grained control, use individual edge flags:
+
+```csharp
+// Only bottom edge resizable
+var view = new View
+{
+    Arrangement = ViewArrangement.BottomResizable
+};
+
+// Left and right edges resizable
+var view2 = new View
+{
+    Arrangement = ViewArrangement.LeftResizable | ViewArrangement.RightResizable
+};
+```
+
+---
+
+## Arrange Mode (Interactive)
+
+**Arrange Mode** is an interactive mode for arranging views using the keyboard. It is activated by pressing the **Arrange Key** (default: `Ctrl+F5`, configurable via [Application.ArrangeKey](~/api/Terminal.Gui.App.Application.yml#Terminal_Gui_App_Application_ArrangeKey)).
+
+### Entering Arrange Mode
+
+When the user presses `Ctrl+F5`:
+
+1. Visual indicators appear on arrangeable views
+2. If [ViewArrangement.Movable](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml), a move indicator (`◊`) appears in top-left corner
+3. If [ViewArrangement.Resizable](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml), pressing `Tab` cycles to resize indicators
+4. Arrow keys move or resize the view
+5. Press `Esc`, `Ctrl+F5`, or click outside to exit
+
+### Arrange Mode Indicators
+
+The [Border](~/api/Terminal.Gui.ViewBase.Border.yml) shows visual indicators based on arrangement options:
+
+| Arrangement Flag | Indicator | Location |
+|------------------|-----------|----------|
+| Movable | `◊` (Glyphs.Move) | Top-left corner |
+| Resizable | `⇲` (Glyphs.SizeBottomRight) | Bottom-right corner |
+| LeftResizable | `↔` (Glyphs.SizeHorizontal) | Left edge, centered |
+| RightResizable | `↔` (Glyphs.SizeHorizontal) | Right edge, centered |
+| TopResizable | `↕` (Glyphs.SizeVertical) | Top edge, centered |
+| BottomResizable | `↕` (Glyphs.SizeVertical) | Bottom edge, centered |
+
+### Keyboard Controls in Arrange Mode
+
+- **Arrow Keys** - Move or resize based on active mode
+- **Tab** - Cycle between move and resize modes (if both available)
+- **Shift+Tab** - Cycle backwards
+- **Esc** - Exit Arrange Mode
+- **Ctrl+F5** - Exit Arrange Mode
+
+### Requirements for Arrangement
+
+For a View to be arrangeable:
+
+1. Must be part of a [SuperView](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_SuperView)
+2. Position and dimensions must be independent of other SubViews
+3. Must have [View.Arrangement](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Arrangement) flags set
+4. Typically needs a [Border](~/api/Terminal.Gui.ViewBase.Border.yml) for mouse interaction
 
-Describes the feature of [Layout](layout.md) which controls how the user can use the mouse and keyboard to arrange views and enables either **Tiled** or **Overlapped** layouts. The @Terminal.Gui.ViewBase.View.Arrangement property controls the arrangement behavior for each view.
+---
 
-## Arrange Mode
+## Tiled vs Overlapped Layouts
 
-The Arrange Modes are set via the @Terminal.Gui.ViewBase.View.Arrangement property. When a user presses `Ctrl+F5` (configurable via the @Terminal.Gui.App.Application.ArrangeKey property) the application goes into **Arrange Mode**. 
+### Tiled Layout
 
-In this mode, indicators are displayed on an arrangeable view indicating which aspect of the View can be arranged:
-- If @Terminal.Gui.ViewBase.ViewArrangement.Movable, a `◊` will be displayed in the top-left corner of the @Terminal.Gui.ViewBase.View.Border
-- If @Terminal.Gui.ViewBase.ViewArrangement.Resizable, pressing `Tab` (or `Shift+Tab`) will cycle to an indicator in the bottom-right corner of the Border
+In **Tiled** layouts, SubViews typically do not overlap. There is no Z-order; all views are at the same layer.
 
-The up/down/left/right cursor keys will act appropriately. `Esc`, `Ctrl+F5` or clicking outside of the Border will exit Arrange Mode.
+```csharp
+var container = new View { Arrangement = ViewArrangement.Fixed };
 
-## Modal
+var view1 = new View { X = 0, Y = 0, Width = 20, Height = 10 };
+var view2 = new View { X = 21, Y = 0, Width = 20, Height = 10 };
 
-A modal view is one that is run as an "application" via @Terminal.Gui.App.Application.Run(System.Func{System.Exception,System.Boolean},Terminal.Gui.Drivers.IConsoleDriver) where `Modal == true`. 
+container.Add(view1, view2);
+// Views are side-by-side, non-overlapping
+```
 
-`Dialog`, `MessageBox`, and `Wizard` are the prototypical examples. When run this way, there IS a `z-order` but it is highly-constrained: the modal view has a z-order of 1 and everything else is at 0.
+**Characteristics:**
+- Default mode for most TUI applications
+- Views use [Pos](~/api/Terminal.Gui.Pos.yml) and [Dim](~/api/Terminal.Gui.Dim.yml) for relative positioning
+- No Z-order management needed
+- More predictable layout behavior
 
-## Movable
+### Overlapped Layout
 
-Describes a View that can be moved by the user using the keyboard or mouse. **Movable** is enabled on a per-View basis by setting the @Terminal.Gui.ViewBase.ViewArrangement.Movable flag on @Terminal.Gui.ViewBase.View.Arrangement. 
+In **Overlapped** layouts, SubViews can overlap with Z-order determining visual stacking.
 
-Dragging on the top @Terminal.Gui.ViewBase.View.Border of a View will move such a view. Pressing `Ctrl+F5` will activate **Arrange Mode** letting the user move the view with the up/down/left/right cursor keys.
+Enable overlapped mode with [ViewArrangement.Overlapped](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml):
 
-## Overlapped
+```csharp
+var container = new View 
+{ 
+    Arrangement = ViewArrangement.Overlapped 
+};
 
-A form of layout where SubViews of a View are visually arranged such that their Frames overlap. In Overlap view arrangements there is a Z-axis (Z-order) in addition to the X and Y dimension. The Z-order indicates which Views are shown above other views. 
+var window1 = new Window 
+{ 
+    X = 5, Y = 3, Width = 40, Height = 15,
+    Arrangement = ViewArrangement.Movable | ViewArrangement.Overlapped
+};
+
+var window2 = new Window 
+{ 
+    X = 15, Y = 8, Width = 40, Height = 15,
+    Arrangement = ViewArrangement.Movable | ViewArrangement.Overlapped
+};
+
+container.Add(window1, window2);
+// window2 will overlap window1
+```
 
-**Overlapped** is enabled on a per-View basis by setting the @Terminal.Gui.ViewBase.ViewArrangement.Overlapped flag on @Terminal.Gui.ViewBase.View.Arrangement.
+**Characteristics:**
+- Z-order determined by SubViews collection order
+- Later views appear above earlier views
+- Tab navigation constrained to current overlapped view
+- Use `Ctrl+Tab` / `Ctrl+Shift+Tab` to switch between overlapped views
 
-## Resizable
+---
+
+## Movable Views
+
+Views with [ViewArrangement.Movable](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml) can be repositioned by the user.
+
+### Enabling Movable
+
+```csharp
+var window = new Window
+{
+    Title = "Drag Me!",
+    X = 10,
+    Y = 5,
+    Width = 40,
+    Height = 15,
+    Arrangement = ViewArrangement.Movable,
+    BorderStyle = LineStyle.Single
+};
+```
 
-Describes a View that can be sized by the user using the keyboard or mouse. **Resizable** is enabled on a per-View basis by setting the @Terminal.Gui.ViewBase.ViewArrangement.Resizable flag on @Terminal.Gui.ViewBase.View.Arrangement. 
+### Moving with Mouse
 
-Dragging on the left, right, or bottom @Terminal.Gui.ViewBase.View.Border of a View will size that side of such a view. Pressing `Ctrl+F5` will activate **Arrange Mode** letting the user size the view with the up/down/left/right cursor keys.
+- **Click and drag** the top [Border](~/api/Terminal.Gui.ViewBase.Border.yml) to move the view
+- The view's [Frame](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Frame) updates as it moves
+- Release the mouse to complete the move
 
-## Tiled
+### Moving with Keyboard
 
-A form of layout where SubViews of a View are visually arranged such that their Frames do not typically overlap. With **Tiled** views, there is no 'z-order` to the SubViews of a View. 
+1. Press `Ctrl+F5` to enter **Arrange Mode**
+2. A move indicator (`◊`) appears in the top-left corner
+3. Use **arrow keys** to move the view
+4. Press `Esc` or `Ctrl+F5` to exit Arrange Mode
 
-In most use-cases, subviews do not overlap with each other (the exception being when it's done intentionally to create some visual effect). As a result, the default layout for most TUI apps is "tiled", and by default @Terminal.Gui.ViewBase.View.Arrangement is set to @Terminal.Gui.ViewBase.ViewArrangement.Fixed.
+---
 
-### Creating a Resizable Splitter
+## Resizable Views
 
-A common pattern in tiled layouts is to create a resizable splitter between two views. This can be achieved using the @Terminal.Gui.ViewBase.ViewArrangement.LeftResizable, @Terminal.Gui.ViewBase.ViewArrangement.RightResizable, @Terminal.Gui.ViewBase.ViewArrangement.TopResizable, or @Terminal.Gui.ViewBase.ViewArrangement.BottomResizable flags.
+Views with resizable flags can be resized by the user on specific edges.
 
-Here's an example of creating a horizontal resizable splitter between two views:
+### All Edges Resizable
+
+```csharp
+var window = new Window
+{
+    Title = "Resize Me!",
+    Arrangement = ViewArrangement.Resizable,
+    BorderStyle = LineStyle.Single
+};
+```
+
+### Specific Edge Resizable
+
+```csharp
+// Only right and bottom edges resizable
+var view = new View
+{
+    Arrangement = ViewArrangement.RightResizable | ViewArrangement.BottomResizable,
+    BorderStyle = LineStyle.Single
+};
+```
+
+### Resizing with Mouse
+
+- **Click and drag** any enabled border edge
+- Resize indicators appear on hover
+- The view's [Width](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Width) and [Height](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Height) update
+
+### Resizing with Keyboard
+
+1. Press `Ctrl+F5` to enter **Arrange Mode**
+2. Press `Tab` to cycle to resize mode
+3. Resize indicator (`⇲`) appears
+4. Use **arrow keys** to resize
+5. Press `Esc` or `Ctrl+F5` to exit
+
+---
+
+## Creating Resizable Splitters
+
+A common pattern in tiled layouts is creating a resizable splitter between two panes.
+
+### Horizontal Splitter (Left/Right Panes)
 
 ```csharp
-// Create left pane that fills remaining space
 View leftPane = new ()
 {
     X = 0,
     Y = 0,
-    Width = Dim.Fill (Dim.Func (_ => rightPane.Frame.Width)),
-    Height = Dim.Fill (),
-    CanFocus = true
+    Width = Dim.Fill(Dim.Func(_ => rightPane.Frame.Width)),
+    Height = Dim.Fill(),
+    BorderStyle = LineStyle.Single
 };
 
-// Create right pane with resizable left border (acts as splitter)
 View rightPane = new ()
 {
-    X = Pos.Right (leftPane) - 1,
+    X = Pos.Right(leftPane) - 1,
     Y = 0,
-    Width = Dim.Fill (),
-    Height = Dim.Fill (),
+    Width = Dim.Fill(),
+    Height = Dim.Fill(),
     Arrangement = ViewArrangement.LeftResizable,
     BorderStyle = LineStyle.Single,
-    SuperViewRendersLineCanvas = true,
-    CanFocus = true
+    SuperViewRendersLineCanvas = true
+};
+rightPane.Border.Thickness = new Thickness(1, 0, 0, 0); // Only left border
+
+container.Add(leftPane, rightPane);
+```
+
+**How it works:**
+- `rightPane` has [ViewArrangement.LeftResizable](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml) - its left border is draggable
+- `leftPane` uses [Dim.Fill](~/api/Terminal.Gui.Dim.yml) with a function to fill remaining space
+- `SuperViewRendersLineCanvas = true` ensures proper line rendering
+- Only the left border is visible, acting as the splitter
+
+### Vertical Splitter (Top/Bottom Panes)
+
+```csharp
+View topPane = new ()
+{
+    X = 0,
+    Y = 0,
+    Width = Dim.Fill(),
+    Height = Dim.Fill(Dim.Func(_ => bottomPane.Frame.Height)),
+    BorderStyle = LineStyle.Single
+};
+
+View bottomPane = new ()
+{
+    X = 0,
+    Y = Pos.Bottom(topPane) - 1,
+    Width = Dim.Fill(),
+    Height = Dim.Fill(),
+    Arrangement = ViewArrangement.TopResizable,
+    BorderStyle = LineStyle.Single,
+    SuperViewRendersLineCanvas = true
 };
-rightPane.Border!.Thickness = new (1, 0, 0, 0); // Only left border
+bottomPane.Border.Thickness = new Thickness(1, 0, 0, 0); // Only top border
 
-container.Add (leftPane, rightPane);
+container.Add(topPane, bottomPane);
 ```
 
-In this example:
-- The `rightPane` has `ViewArrangement.LeftResizable` which makes its left border draggable
-- The left border acts as a splitter that users can drag to resize both panes
-- The `leftPane` uses `Dim.Fill` with a function that subtracts the `rightPane`'s width to automatically fill the remaining space
-- The `rightPane` has `SuperViewRendersLineCanvas = true` to ensure the border is rendered properly
-- Only the left border is shown by setting `Border.Thickness` to `(1, 0, 0, 0)`
+---
+
+## Modal Views
+
+**Modal** views run as exclusive applications that capture all user input until closed.
+
+See the [Multitasking Deep Dive](multitasking.md) for complete details on modal execution.
+
+### What Makes a View Modal
+
+A view is modal when:
+- Run via [Application.Run](~/api/Terminal.Gui.App.Application.yml#Terminal_Gui_App_Application_Run_Terminal_Gui_Views_Toplevel_System_Func_System_Exception_System_Boolean__)
+- [Toplevel.Modal](~/api/Terminal.Gui.Views.Toplevel.yml#Terminal_Gui_Views_Toplevel_Modal) = `true`
+
+### Modal Characteristics
+
+- **Exclusive Input** - All keyboard and mouse input goes to the modal view
+- **Constrained Z-Order** - Modal view has Z-order of 1, everything else at 0
+- **Blocks Execution** - `Application.Run` blocks until [Application.RequestStop](~/api/Terminal.Gui.App.Application.yml#Terminal_Gui_App_Application_RequestStop_Terminal_Gui_Views_Toplevel_) is called
+- **Own RunState** - Each modal view has its own [RunState](~/api/Terminal.Gui.App.RunState.yml)
+
+### Modal View Types
+
+- [Dialog](~/api/Terminal.Gui.Views.Dialog.yml) - Centered modal window with button support
+- [MessageBox](~/api/Terminal.Gui.Views.MessageBox.yml) - Simple message dialogs
+- [Wizard](~/api/Terminal.Gui.Views.Wizard.yml) - Multi-step modal dialogs
+
+### Modal Example
+
+```csharp
+var dialog = new Dialog
+{
+    Title = "Confirm",
+    Width = 40,
+    Height = 10
+};
+
+var label = new Label 
+{ 
+    Text = "Are you sure?", 
+    X = Pos.Center(), 
+    Y = 2 
+};
+dialog.Add(label);
+
+var ok = new Button { Text = "OK" };
+ok.Accepting += (s, e) => Application.RequestStop();
+dialog.AddButton(ok);
+
+// Run modally - blocks until closed
+Application.Run(dialog);
+
+// Dialog has been closed
+```
+
+---
+
+## Runnable Views
+
+**Runnable** views are those run via [Application.Run](~/api/Terminal.Gui.App.Application.yml). Each non-modal Runnable view operates as a self-contained "application" with its own [RunState](~/api/Terminal.Gui.App.RunState.yml).
+
+See the [Multitasking Deep Dive](multitasking.md) for complete details.
+
+### Non-Modal Runnable Views
+
+```csharp
+var toplevel = new Toplevel
+{
+    Modal = false // Non-modal
+};
+
+// Runs as independent application
+Application.Run(toplevel);
+```
+
+**Characteristics:**
+- Has its own `RunState`
+- Events dispatched independently
+- Can run on separate threads
+- See `BackgroundWorkerCollection` for multi-threaded examples
+
+### Modal vs Non-Modal Runnable
+
+| Aspect | Modal | Non-Modal |
+|--------|-------|-----------|
+| Input | Exclusive | Shared |
+| Z-Order | Constrained (1 vs 0) | Full Z-order support |
+| Blocks Execution | Yes | No |
+| Use Case | Dialogs, confirmations | Multi-window apps |
+
+---
+
+## Tiled vs Overlapped Layouts
+
+### Tiled Layout (Default)
+
+SubViews do not overlap, positioned side-by-side or top-to-bottom:
+
+```csharp
+var container = new View();
+
+var left = new View 
+{ 
+    X = 0, 
+    Y = 0, 
+    Width = Dim.Percent(50), 
+    Height = Dim.Fill() 
+};
+
+var right = new View 
+{ 
+    X = Pos.Right(left), 
+    Y = 0, 
+    Width = Dim.Fill(), 
+    Height = Dim.Fill() 
+};
+
+container.Add(left, right);
+```
+
+**Benefits:**
+- Simpler layout logic
+- No Z-order management
+- More predictable behavior
+- Standard for most TUI applications
+
+### Overlapped Layout
+
+SubViews can overlap with Z-order determining which is on top:
+
+```csharp
+var container = new View 
+{ 
+    Arrangement = ViewArrangement.Overlapped 
+};
+
+var window1 = new Window 
+{ 
+    X = 5, 
+    Y = 3, 
+    Width = 40, 
+    Height = 15,
+    Arrangement = ViewArrangement.Movable | ViewArrangement.Overlapped
+};
+
+var window2 = new Window 
+{ 
+    X = 15, 
+    Y = 8, 
+    Width = 40, 
+    Height = 15,
+    Arrangement = ViewArrangement.Movable | ViewArrangement.Overlapped
+};
+
+container.Add(window1, window2);
+// window2 appears on top of window1
+```
+
+**Z-Order:**
+- Order in [View.SubViews](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_SubViews) determines Z-order
+- Later views appear above earlier views
+- Use [View.BringSubviewToFront](~/api/Terminal.Gui.ViewBase.View.yml) to change Z-order
+
+**Navigation:**
+- `Tab` / `Shift+Tab` - Navigate within current overlapped view
+- `Ctrl+Tab` (`Ctrl+PageDown`) - Switch to next overlapped view
+- `Ctrl+Shift+Tab` (`Ctrl+PageUp`) - Switch to previous overlapped view
+
+---
+
+## Examples
+
+### Example 1: Movable and Resizable Window
+
+```csharp
+using Terminal.Gui;
+
+Application.Init();
+
+var window = new Window
+{
+    Title = "Drag and Resize Me! (Ctrl+F5 for keyboard mode)",
+    X = Pos.Center(),
+    Y = Pos.Center(),
+    Width = 50,
+    Height = 15,
+    Arrangement = ViewArrangement.Movable | ViewArrangement.Resizable,
+    BorderStyle = LineStyle.Double
+};
+
+var label = new Label
+{
+    Text = "Try dragging the border with mouse\nor press Ctrl+F5!",
+    X = Pos.Center(),
+    Y = Pos.Center()
+};
+window.Add(label);
+
+Application.Run(window);
+Application.Shutdown();
+```
+
+### Example 2: Horizontal Resizable Splitter
+
+```csharp
+Application.Init();
+
+var top = new Toplevel();
+
+var leftPane = new FrameView
+{
+    Title = "Left Pane",
+    X = 0,
+    Y = 0,
+    Width = Dim.Fill(Dim.Func(_ => rightPane.Frame.Width)),
+    Height = Dim.Fill()
+};
+
+var rightPane = new FrameView
+{
+    Title = "Right Pane (drag left edge)",
+    X = Pos.Right(leftPane) - 1,
+    Y = 0,
+    Width = Dim.Fill(),
+    Height = Dim.Fill(),
+    Arrangement = ViewArrangement.LeftResizable,
+    SuperViewRendersLineCanvas = true
+};
+rightPane.Border.Thickness = new Thickness(1, 0, 0, 0);
+
+top.Add(leftPane, rightPane);
+
+Application.Run(top);
+Application.Shutdown();
+```
+
+### Example 3: Overlapped Windows
+
+```csharp
+Application.Init();
+
+var desktop = new Toplevel 
+{ 
+    Arrangement = ViewArrangement.Overlapped 
+};
+
+var window1 = new Window
+{
+    Title = "Window 1",
+    X = 5,
+    Y = 3,
+    Width = 40,
+    Height = 12,
+    Arrangement = ViewArrangement.Movable | ViewArrangement.Resizable | ViewArrangement.Overlapped
+};
+
+var window2 = new Window
+{
+    Title = "Window 2 (overlaps Window 1)",
+    X = 15,
+    Y = 8,
+    Width = 40,
+    Height = 12,
+    Arrangement = ViewArrangement.Movable | ViewArrangement.Resizable | ViewArrangement.Overlapped
+};
+
+desktop.Add(window1, window2);
+
+Application.Run(desktop);
+Application.Shutdown();
+```
+
+### Example 4: Custom Arrange Key
+
+```csharp
+using Terminal.Gui;
+using Terminal.Gui.Configuration;
+
+// Change the arrange key
+Application.ArrangeKey = Key.F2;
+
+var window = new Window
+{
+    Title = "Press F2 to enter arrange mode",
+    Arrangement = ViewArrangement.Movable | ViewArrangement.Resizable
+};
+
+Application.Run(window);
+```
+
+---
+
+## Advanced Topics
+
+### Constraints and Limitations
+
+Arrangement only works when:
+
+1. **View has a SuperView** - Root views cannot be arranged
+2. **Independent Position/Size** - Views with [Pos.Align](~/api/Terminal.Gui.Pos.yml) or complex [Dim](~/api/Terminal.Gui.Dim.yml) constraints may not resize properly
+3. **Border Required** - Mouse-based arrangement requires a visible [Border](~/api/Terminal.Gui.ViewBase.Border.yml)
+
+### SuperViewRendersLineCanvas
+
+When creating splitters, set [View.SuperViewRendersLineCanvas](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_SuperViewRendersLineCanvas) = `true`:
+
+```csharp
+rightPane.SuperViewRendersLineCanvas = true;
+```
+
+This ensures [LineCanvas](~/api/Terminal.Gui.Drawing.LineCanvas.yml) properly handles line intersections at borders.
+
+### Z-Order Management
+
+For overlapped views, manage Z-order with:
+
+```csharp
+// Bring a view to the front
+container.BringSubviewToFront(window1);
+
+// Send a view to the back
+container.SendSubviewToBack(window2);
+
+// Check current order
+int index = container.SubViews.IndexOf(window1);
+```
+
+### Arrangement Events
+
+Monitor arrangement changes by handling layout events:
+
+```csharp
+view.FrameChanged += (s, e) =>
+{
+    Console.WriteLine($"View moved/resized to {e.NewValue}");
+};
+
+view.LayoutComplete += (s, e) =>
+{
+    // Layout has completed after arrangement change
+};
+```
+
+---
+
+## See Also
 
-For a vertical splitter (top and bottom panes), use `ViewArrangement.TopResizable` or `ViewArrangement.BottomResizable` instead.
+- **[Layout Deep Dive](layout.md)** - Overall layout system
+- **[View Deep Dive](View.md)** - View base class
+- **[Multitasking Deep Dive](multitasking.md)** - Modal and runnable views
+- **[Drawing Deep Dive](drawing.md)** - LineCanvas and borders
+- **[Configuration Deep Dive](config.md)** - Configuring Application.ArrangeKey
 
-## Runnable
+### API Reference
 
-Today, Overlapped and Runnable are intrinsically linked. A runnable view is one where `Application.Run(Toplevel)` is called. Each *Runnable* view where (`Modal == false`) has it's own `RunState` and is, effectively, a self-contained "application". 
+- [View.Arrangement](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Arrangement)
+- [ViewArrangement](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml)
+- [Border](~/api/Terminal.Gui.ViewBase.Border.yml)
+- [Application.ArrangeKey](~/api/Terminal.Gui.App.Application.yml#Terminal_Gui_App_Application_ArrangeKey)
+- [Toplevel.Modal](~/api/Terminal.Gui.Views.Toplevel.yml#Terminal_Gui_Views_Toplevel_Modal)
 
-`Application.Run()` non-preemptively dispatches events (screen, keyboard, mouse, Timers, and Idle handlers) to the associated `Toplevel`. It is possible for such a `Toplevel` to create a thread and call `Application.Run(someotherToplevel)` on that thread, enabling pre-emptive user-interface multitasking (`BackgroundWorkerCollection` does this).
+### UICatalog Examples
 
+The UICatalog application demonstrates arrangement:
 
+- **Arrangement Editor** - Interactive arrangement demonstration
+- **Overlapped** scenario - Shows overlapped window management
+- **Splitter** examples - Various splitter configurations

+ 807 - 217
docfx/docs/config.md

@@ -1,380 +1,970 @@
-# Configuration Management
+# Configuration Management Deep Dive
 
-Terminal.Gui provides persistent configuration settings via the [`ConfigurationManager`](~/api/Terminal.Gui.Configuration.ConfigurationManager.yml) class.
+Terminal.Gui provides a comprehensive configuration system that allows users and developers to customize application behavior and appearance through JSON configuration files. The [ConfigurationManager](~/api/Terminal.Gui.Configuration.ConfigurationManager.yml) enables persistent settings, themes, and application-specific preferences.
 
-## Configuration Lexicon and Taxonomy
+## Table of Contents
 
-[!INCLUDE [Config Lexicon](~/includes/config-lexicon.md)]
+- [Overview](#overview)
+- [Getting Started](#getting-started)
+- [Configuration Scopes](#configuration-scopes)
+- [Configuration Locations and Precedence](#configuration-locations-and-precedence)
+- [Themes and Schemes](#themes-and-schemes)
+- [Defining Configuration Properties](#defining-configuration-properties)
+- [Loading and Applying Configuration](#loading-and-applying-configuration)
+- [Events](#events)
+- [What Can Be Configured](#what-can-be-configured)
+- [Configuration File Format](#configuration-file-format)
+- [Best Practices](#best-practices)
 
-# Fundamentals
+---
 
-The `ConfigurationManager` class provides a way to store and retrieve configuration settings for an application. The configuration is stored in JSON documents, which can be located in the user's home directory, the current working directory, in memory, or as a resource within the application's main assembly.
+## Overview
 
-Settings are defined in JSON format, according to this schema: https://gui-cs.github.io/Terminal.GuiV2Docs/schemas/tui-config-schema.json.
+The [ConfigurationManager](~/api/Terminal.Gui.Configuration.ConfigurationManager.yml) provides:
 
-Terminal.Gui library developers can define settings in code and set the default values in the Terminal.Gui assembly's resources (e.g. `Terminal.Gui.Resources.config.json`).
+- **Persistent Settings** - User preferences stored in JSON files
+- **Theme System** - Named collections of visual settings
+- **Scheme Management** - Color and text style definitions
+- **Configuration Precedence** - Layered configuration from multiple sources
+- **Runtime Configuration** - In-memory configuration without files
+- **AOT Compatible** - Works with Native AOT compilation
 
-Terminal.Gui application developers can define settings in their apps' code and set the default values in their apps' resources (e.g. `Resources/config.json`) or by setting @Terminal.Gui.Configuration.ConfigurationManager.RuntimeConfig to string containing JSON.
+### Key Features
 
-Users can change settings on a global or per-application basis by providing JSON formatted configuration files. The configuration files can be placed in at .tui folder in the user's home directory (e.g. `C:/Users/username/.tui`, or `/usr/username/.tui`) or the folder where the Terminal.Gui application was launched from (e.g. `./.tui`).
+- JSON-based configuration with schema validation
+- Multiple configuration locations (user home, app directory, resources)
+- Process-wide settings using static properties
+- Built-in themes (Default, Dark, Light, etc.)
+- Custom glyphs and Unicode characters
+- Event-driven configuration changes
 
-## CM is Disabled by Default
+---
 
-The `ConfigurationManager` must be enabled explicitly by calling @Terminal.Gui.Configuration.ConfigurationManager.Enable(Terminal.Gui.Configuration.ConfigLocations) in an application's `Main` method.
+## Getting Started
 
-```csharp
-// Enable configuration with all sources  
-ConfigurationManager.Enable(ConfigLocations.All);
-```
+### Enabling Configuration
 
-If `ConfigurationManager.Enable()` is not called (`ConfigurationManager.IsEnabled` is 'false'), all configuration settings are ignored and ConfigurationManager will effectively be a no-op. All `[ConfigurationProperty]` properties will initially be their hard-coded default values. 
+**ConfigurationManager is disabled by default** and must be explicitly enabled:
 
-Other than that, no other ConfigurationManager APIs will have any effect.
-
-## Loading and Applying Configuration
+```csharp
+using Terminal.Gui.Configuration;
 
-Optionally, developers can more granularly control the loading and applying of configuration by calling the `Load` and `Apply` methods directly.
+class Program
+{
+    static void Main()
+    {
+        // Enable configuration with all sources
+        ConfigurationManager.Enable(ConfigLocations.All);
+        
+        Application.Init();
+        // ... rest of app
+    }
+}
+```
 
-When a configuration has been loaded, the @Terminal.Gui.Configuration.ConfigurationManager.Apply method must be called to apply the settings to the application. This method uses reflection to find all static fields decorated with the `[ConfigurationProperty]` attribute and applies the settings to the corresponding properties.
+### Quick Example
 
 ```csharp
-// Load the configuration from just the users home directory.
-ConfigurationManager.Enable(ConfigLocations.HardCoded);
-ConfigurationManager.Load(ConfigLocations.GlobalHome);
+// Enable configuration
+ConfigurationManager.Enable(ConfigLocations.All);
+
+// Listen for configuration changes
+ConfigurationManager.Applied += (sender, e) => 
+{
+    Console.WriteLine("Configuration applied!");
+};
+
+// Switch themes
+ThemeManager.Theme = "Dark";
 ConfigurationManager.Apply();
 ```
 
-> [!IMPORTANT]
-> Configuration Settings Apply at the Process Level. 
-> Configuration settings are applied at the process level, which means that they are applied to all applications that are part of the same process. This is due to the fact that configuration properties are defined as static fields, which are static for the process.
+---
+
+## Configuration Scopes
 
-## Configuration Types and Scopes
+Terminal.Gui uses three configuration scopes, each serving a different purpose:
 
-Terminal.Gui supports three main configuration scopes. See the section below titled [What Can Be Configured](#what-can-be-configured) for more details.
+### 1. SettingsScope
 
-### SettingsScope
+System-level settings that affect Terminal.Gui behavior. Only Terminal.Gui library developers can define [SettingsScope](~/api/Terminal.Gui.Configuration.SettingsScope.yml) properties.
 
-System-level settings that affect Terminal.Gui behavior:
 ```csharp
-[ConfigurationProperty (Scope = typeof (SettingsScope))]
-public static int MaxSearchResults { get; set; } = 10000;
+[ConfigurationProperty(Scope = typeof(SettingsScope))]
+public static bool Force16Colors { get; set; } = false;
 ```
 
-### ThemeScope
-Visual appearance settings that can be themed:
+**Examples:**
+- `Application.QuitKey` - Default key to quit applications
+- `Application.Force16Colors` - Force 16-color mode
+- `Key.Separator` - Character separating keys in key combinations
+
+### 2. ThemeScope
+
+Visual appearance settings that can be themed. Only Terminal.Gui library developers can define [ThemeScope](~/api/Terminal.Gui.Configuration.ThemeScope.yml) properties.
+
 ```csharp
- [ConfigurationProperty (Scope = typeof (ThemeScope))]
- public new static LineStyle DefaultBorderStyle { get; set; } = LineStyle.Single;
+[ConfigurationProperty(Scope = typeof(ThemeScope))]
+public static LineStyle DefaultBorderStyle { get; set; } = LineStyle.Single;
 ```
 
-### AppSettingsScope (default)
-Application-specific settings:
+**Examples:**
+- `Window.DefaultBorderStyle` - Default border style for windows
+- `Dialog.DefaultShadow` - Default shadow style for dialogs
+- `Schemes` - Color schemes for the theme
+
+### 3. AppSettingsScope (Default)
+
+Application-specific settings. Application developers can define [AppSettingsScope](~/api/Terminal.Gui.Configuration.AppSettingsScope.yml) properties for their apps.
+
 ```csharp
 [ConfigurationProperty] // AppSettingsScope is default
-public static string MyAppSetting { get; set; } = "default";
+public static string MyAppSetting { get; set; } = "default value";
 ```
 
-## Configuration Precedence
+**Important:** 
+- App developers **cannot** define `SettingsScope` or `ThemeScope` properties
+- AppSettings property names must be globally unique (automatically prefixed with class name)
+
+---
+
+## Configuration Locations and Precedence
+
+Configuration is loaded from multiple locations with increasing precedence (higher numbers override lower):
+
+### ConfigLocations Enum
+
+[ConfigLocations](~/api/Terminal.Gui.Configuration.ConfigLocations.yml) specifies where configuration can be loaded from:
+
+1. **[ConfigLocations.HardCoded](~/api/Terminal.Gui.Configuration.ConfigLocations.yml)** (Lowest Precedence)
+   - Default values in code (static property initializers)
+   - Always available, even when ConfigurationManager is disabled
+
+2. **[ConfigLocations.LibraryResources](~/api/Terminal.Gui.Configuration.ConfigLocations.yml)**
+   - Settings in `Terminal.Gui.dll` resources (`Terminal.Gui.Resources.config.json`)
+   - Defines default themes and settings for the library
+
+3. **[ConfigLocations.Runtime](~/api/Terminal.Gui.Configuration.ConfigLocations.yml)**
+   - Settings in [ConfigurationManager.RuntimeConfig](~/api/Terminal.Gui.Configuration.ConfigurationManager.yml#Terminal_Gui_Configuration_ConfigurationManager_RuntimeConfig) string property
+   - In-memory configuration without files
+
+4. **[ConfigLocations.AppResources](~/api/Terminal.Gui.Configuration.ConfigLocations.yml)**
+   - App-specific resources (`MyApp.Resources.config.json` or `Resources/config.json`)
+   - Embedded in the application assembly
+
+5. **[ConfigLocations.AppHome](~/api/Terminal.Gui.Configuration.ConfigLocations.yml)**
+   - App-specific file in user's home directory (`~/.tui/MyApp.config.json`)
+
+6. **[ConfigLocations.AppCurrent](~/api/Terminal.Gui.Configuration.ConfigLocations.yml)**
+   - App-specific file in current directory (`./.tui/MyApp.config.json`)
+
+7. **[ConfigLocations.GlobalHome](~/api/Terminal.Gui.Configuration.ConfigLocations.yml)**
+   - Global file in user's home directory (`~/.tui/config.json`)
+
+8. **[ConfigLocations.GlobalCurrent](~/api/Terminal.Gui.Configuration.ConfigLocations.yml)** (Highest Precedence)
+   - Global file in current directory (`./.tui/config.json`)
+
+### Precedence Diagram
 
 ```mermaid
 graph TD
-    A[Hard-coded Defaults] --> B[Terminal.Gui Defaults]
-    B --> C[Runtime Config]
-    C --> D[App Resources]
-    D --> E[App Home Directory]
-    E --> F[App Current Directory]
-    F --> G[Global Home Directory]
-    G --> H[Global Current Directory]
+    A[1. Hard-coded Defaults] --> B[2. Library Resources]
+    B --> C[3. Runtime Config]
+    C --> D[4. App Resources]
+    D --> E[5. App Home Directory]
+    E --> F[6. App Current Directory]
+    F --> G[7. Global Home Directory]
+    G --> H[8. Global Current Directory]
+    
+    style A fill:#f9f9f9
+    style H fill:#90EE90
 ```
 
-Settings are applied using the following precedence (higher precedence settings overwrite lower precedence settings):
+### File Locations
 
-1. @Terminal.Gui.Configuration.ConfigLocations.HardCoded Hard-coded default values in any static property decorated with the `[ConfigurationProperty]` attribute.
+**Global Settings** (`config.json`):
+- Windows: `C:\Users\username\.tui\config.json`
+- macOS/Linux: `~/.tui/config.json` or `./.tui/config.json`
 
-2. @Terminal.Gui.Configuration.ConfigLocations.LibraryResources - Default settings in the Terminal.Gui assembly -- Lowest precedence.
+**App-Specific Settings** (`AppName.config.json`):
+- Windows: `C:\Users\username\.tui\UICatalog.config.json`
+- macOS/Linux: `~/.tui/UICatalog.config.json` or `./.tui/UICatalog.config.json`
 
-3. @Terminal.Gui.Configuration.ConfigLocations.Runtime - Settings stored in the @Terminal.Gui.Configuration.ConfigurationManager.RuntimeConfig static property.
+---
 
-4. @Terminal.Gui.Configuration.ConfigLocations.AppResources - App settings in app resources (`Resources/config.json`).
+## Themes and Schemes
 
-5. @Terminal.Gui.Configuration.ConfigLocations.AppHome - App-specific settings in the users's home directory (`~/.tui/appname.config.json`). 
+### Theme System
 
-6. @Terminal.Gui.Configuration.ConfigLocations.AppCurrent - App-specific settings in the directory the app was launched from (`./.tui/appname.config.json`).
+A **Theme** is a named collection of visual settings bundled together. Terminal.Gui includes several built-in themes.
 
-7. @Terminal.Gui.Configuration.ConfigLocations.GlobalHome - Global settings in the the user's home directory (`~/.tui/config.json`).
+#### Built-in Themes
 
-8. @Terminal.Gui.Configuration.ConfigLocations.GlobalCurrent - Global settings in the directory the app was launched from (`./.tui/config.json`) --- Hightest precedence.
+- **Default** - The default Terminal.Gui theme (matches hard-coded defaults)
+- **Dark** - Dark color scheme with heavy borders
+- **Light** - Light color scheme
+- **TurboPascal 5** - Classic Turbo Pascal IDE colors
+- **And more** - See `Terminal.Gui/Resources/config.json` for all built-in themes
 
+#### Using Themes
 
-The [`ConfigurationManager`](~/api/Terminal.Gui.Configuration.ConfigurationManager.yml) will look for configuration files in the `.tui` folder in the user's home directory (e.g. `C:/Users/username/.tui` or `/usr/username/.tui`), the folder where the Terminal.Gui application was launched from (e.g. `./.tui`), or as a resource within the Terminal.Gui application's main assembly.
+```csharp
+// Get current theme
+ThemeScope currentTheme = ThemeManager.GetCurrentTheme();
 
-Settings that will apply to all applications (global settings) reside in files named `config.json`. Settings that will apply to a specific Terminal.Gui application reside in files named `appname.config.json`, where *appname* is the assembly name of the application (e.g. `UICatalog.config.json`).
+// Get all available themes
+Dictionary<string, ThemeScope> themes = ThemeManager.GetThemes();
+
+// Get theme names
+ImmutableList<string> themeNames = ThemeManager.GetThemeNames();
 
+// Switch themes
+ThemeManager.Theme = "Dark";
+ConfigurationManager.Apply();
 
-## Configuration Events
+// Listen for theme changes
+ThemeManager.ThemeChanged += (sender, e) => 
+{
+    // Update UI based on new theme
+};
+```
 
-The ConfigurationManager provides several events to track configuration changes:
+### Scheme System
+
+A **Scheme** defines the colors and text styles for a specific UI context (e.g., Dialog, Menu, TopLevel).
+
+See the [Scheme Deep Dive](scheme.md) for complete details on the scheme system.
+
+#### Built-in Schemes
+
+[Schemes](~/api/Terminal.Gui.Drawing.Schemes.yml) enum defines the standard schemes:
+
+- **TopLevel** - Top-level application windows
+- **Base** - Default for most views
+- **Dialog** - Dialogs and message boxes
+- **Menu** - Menus and status bars
+- **Error** - Error messages and dialogs
+
+#### Working with Schemes
 
 ```csharp
-// Called after configuration is applied
-ConfigurationManager.Applied += (sender, e) => {
-    // Handle configuration changes
-};
+// Get all schemes for current theme
+Dictionary<string, Scheme> schemes = SchemeManager.GetCurrentSchemes();
+
+// Get specific scheme
+Scheme dialogScheme = SchemeManager.GetScheme(Schemes.Dialog);
 
-// Called when the active theme changes
-ConfigurationManager.ThemeChanged += (sender, e) => {
-    // Handle theme changes
+// Get scheme names
+ImmutableList<string> schemeNames = SchemeManager.GetSchemeNames();
+
+// Add custom scheme
+SchemeManager.AddScheme("MyScheme", new Scheme
+{
+    Normal = new Attribute(Color.White, Color.Blue),
+    Focus = new Attribute(Color.Black, Color.Cyan)
+});
+
+// Listen for scheme changes
+SchemeManager.CollectionChanged += (sender, e) => 
+{
+    // Handle scheme changes
 };
 ```
 
+#### Scheme Structure
 
-## How Settings are Defined 
+Each [Scheme](~/api/Terminal.Gui.Drawing.Scheme.yml) maps [VisualRole](~/api/Terminal.Gui.Drawing.VisualRole.yml) to [Attribute](~/api/Terminal.Gui.Drawing.Attribute.yml):
 
-Application developers define settings by decorating static properties with the `[ConfigurationProperty]` attribute.
+```json
+{
+  "TopLevel": {
+    "Normal": {
+      "Foreground": "BrightGreen",
+      "Background": "Black",
+      "Style": "None"
+    },
+    "Focus": {
+      "Foreground": "White",
+      "Background": "Cyan",
+      "Style": "Bold"
+    },
+    "HotNormal": {
+      "Foreground": "Yellow",
+      "Background": "Black"
+    },
+    "HotFocus": {
+      "Foreground": "Blue",
+      "Background": "Cyan",
+      "Style": "Underline"
+    },
+    "Disabled": {
+      "Foreground": "DarkGray",
+      "Background": "Black",
+      "Style": "Faint"
+    }
+  }
+}
+```
+
+---
+
+## Defining Configuration Properties
+
+### Basic Property Definition
+
+Application developers define settings using the [ConfigurationPropertyAttribute](~/api/Terminal.Gui.Configuration.ConfigurationPropertyAttribute.yml):
 
 ```csharp
-class MyApp
+public class MyApp
 {
     [ConfigurationProperty]
     public static string MySetting { get; set; } = "Default Value";
+    
+    [ConfigurationProperty]
+    public static int MaxItems { get; set; } = 100;
 }
 ```
 
-Configuration Properties must be `public` or `internal` `static` properties.
+**Requirements:**
+- Must be `public` or `internal`
+- Must be `static`
+- Must be a property (not a field)
+- Must have a default value
 
-The above example will define a configuration property in the `AppSettings` scope. The name of the property will be `MyApp.MySetting` and will appear in JSON as:
+### Property Naming
 
-```json
+AppSettings properties are automatically prefixed with the class name to ensure global uniqueness:
+
+```csharp
+// Code
+public class MyApp
 {
-    "AppSettings": {
-      "MyApp.MySetting": "Default Value"
-    }
+    [ConfigurationProperty]
+    public static string MySetting { get; set; } = "value";
+}
+
+// JSON
+{
+  "AppSettings": {
+    "MyApp.MySetting": "value"
+  }
 }
 ```
 
-`AppSettings` property names must be globally unique. To ensure this, the name of the AppSettings property is the name of the property prefixed with a period and the full name of the class that holds it. In the example above, the AppSettings property is named `MyApp.MySetting`.
+### Scope Specification
+
+Use the `Scope` parameter to specify non-default scopes (Terminal.Gui library only):
+
+```csharp
+// SettingsScope - Library-wide settings
+[ConfigurationProperty(Scope = typeof(SettingsScope))]
+public static bool Force16Colors { get; set; } = false;
+
+// ThemeScope - Visual settings
+[ConfigurationProperty(Scope = typeof(ThemeScope))]
+public static LineStyle DefaultBorderStyle { get; set; } = LineStyle.Single;
 
-Terminal.Gui library developers can use the `SettingsScope` and `ThemeScope` attributes to define settings and themes for the terminal.Gui library.
+// AppSettingsScope - Application settings (default)
+[ConfigurationProperty] // or explicitly: Scope = typeof(AppSettingsScope)
+public static string MyAppSetting { get; set; } = "default";
+```
+
+### Omit Class Name (Advanced)
 
-> [!IMPORTANT] 
-App developers cannot define `SettingScope` or `ThemeScope` properties.
+For library developers only, use `OmitClassName = true` for cleaner JSON:
 
 ```csharp
-    /// <summary>
-    ///     Gets or sets whether <see cref="Button"/>s are shown with a shadow effect by default.
-    /// </summary>
-    [ConfigurationProperty (Scope = typeof (ThemeScope))]
-    public static ShadowStyle DefaultShadow { get; set; } = ShadowStyle.None;
+[ConfigurationProperty(Scope = typeof(ThemeScope), OmitClassName = true)]
+public static Dictionary<string, Scheme> Schemes { get; set; } = new();
 ```
 
-# Sample Code
+---
 
-The `UICatalog` application provides an example of how to use the [`ConfigurationManager`](~/api/Terminal.Gui.Configuration.ConfigurationManager.yml) class to load and save configuration files. 
+## Loading and Applying Configuration
 
-The `Configuration Editor` Scenario provides an editor that allows users to edit the configuration files. UI Catalog also uses a file system watcher to detect changes to the configuration files to tell [`ConfigurationManager`](~/api/Terminal.Gui.Configuration.ConfigurationManager.yml) to reload them; allowing users to change settings without having to restart the application.
+### Enable with Load and Apply
 
-The `Themes` Scenario in the UI Catalog provides a viewer for the themes defined in the configuration files.
+The simplest approach - enable and load in one call:
 
-# What Can Be Configured
+```csharp
+ConfigurationManager.Enable(ConfigLocations.All);
+```
 
-`ConfigurationManager` provides the following features:
+This:
+1. Enables ConfigurationManager
+2. Loads configuration from all locations
+3. Applies settings to the application
 
-1) **Settings**. Settings are applied to the [`Application`](~/api/Terminal.Gui.App.Application.yml) class. Settings are accessed via the `Settings` property of [`ConfigurationManager`](~/api/Terminal.Gui.Configuration.ConfigurationManager.yml). E.g. `Settings["Application.QuitKey"]`
-2) **Themes**. Themes are a named collection of settings impacting how applications look. The default theme is named "Default". Two other built-in themes are provided: "Dark", and "Light". Additional themes can be defined in the configuration files. `Settings ["Themes"]` is a dictionary of theme names to theme settings.
-3) **AppSettings**. Applications can use the [`ConfigurationManager`](~/api/Terminal.Gui.Configuration.ConfigurationManager.yml) to store and retrieve application-specific settings.
+### Granular Control
 
-Methods for discovering what can be configured are available in the `ConfigurationManager` class:
+For more control, use [Load](~/api/Terminal.Gui.Configuration.ConfigurationManager.yml#Terminal_Gui_Configuration_ConfigurationManager_Load_Terminal_Gui_Configuration_ConfigLocations_) and [Apply](~/api/Terminal.Gui.Configuration.ConfigurationManager.yml#Terminal_Gui_Configuration_ConfigurationManager_Apply) separately:
 
-- Call @Terminal.Gui.Configuration.ConfigurationManager.GetHardCodedConfig()
-- Search the source code for `[ConfigurationProperty]` 
+```csharp
+// Enable without loading
+ConfigurationManager.Enable(ConfigLocations.None);
 
-For complete schema details and examples, refer to:
-- Schema: https://gui-cs.github.io/Terminal.GuiV2Docs/schemas/tui-config-schema.json
-- Default configuration: Terminal.Gui/Resources/config.json
+// Load from specific locations
+ConfigurationManager.Load(ConfigLocations.GlobalHome | ConfigLocations.AppResources);
 
-## Themes
+// Apply settings
+ConfigurationManager.Apply();
+```
 
-A Theme is a named collection of settings that impact the visual style of Terminal.Gui applications. The default theme is named "Default". The built-in configuration within the Terminal.Gui library defines two more themes: "Dark", and "Light". Additional themes can be defined in the configuration files. The JSON property `Theme` defines the name of the theme that will be used. If the theme is not found, the default theme will be used.
+### Runtime Configuration
 
-Themes support defining Schemes (a set of colors and styles that define the appearance of views) as well as various default settings for Views. Both the default color schemes and user-defined color schemes can be configured. See [Schemes](~/api/Terminal.Gui.Drawing.Schemes.yml) for more information.
+Set configuration directly in code without files:
 
-### Theme Configuration
+```csharp
+ConfigurationManager.RuntimeConfig = @"
+{
+  ""Application.QuitKey"": ""Ctrl+Q"",
+  ""Application.Force16Colors"": true
+}";
 
-Themes provide a way to bundle visual settings together. When @Terminal.Gui.Configuration.ConfigurationManager.Apply is called, the theme settings are applied to the application. 
+ConfigurationManager.Enable(ConfigLocations.Runtime);
+```
 
-```json
-// ...
- "Dark": {
-   "Dialog.DefaultButtonAlignment": "End",
-   "Dialog.DefaultButtonAlignmentModes": "AddSpaceBetweenItems",
-   "Dialog.DefaultBorderStyle": "Heavy",
-   "Dialog.DefaultShadow": "Transparent",
-   "FrameView.DefaultBorderStyle": "Single",
-   "Window.DefaultBorderStyle": "Single",
-   "MessageBox.DefaultButtonAlignment": "Center",
-   "MessageBox.DefaultBorderStyle": "Heavy",
-   "Button.DefaultShadow": "Opaque",
-   "Schemes": [
-     {
-       "TopLevel": {
-         "Normal": {
-           "Foreground": "LightGray",
-           "Background": "Black",
-           "Style": "None"
-         },
-// etc...
-```
-
-Only properties that are defined in the theme will be applied, meaning that themes can be used to override the a previously applied theme.
-
-To ensure a theme inherits from the default theme, first apply the default theme, then apply the new theme, like this:
-
-```csharp
-// Apply the default theme
-  ThemeManager.Theme = "Default";
-ConfigurationManager.Apply();
+### Reset to Defaults
 
-// Apply the new theme
-ThemeManager.Theme = "MyCustomTheme";
-ConfigurationManager.Apply();
+Reset all settings to hard-coded defaults:
+
+```csharp
+ConfigurationManager.ResetToHardCodedDefaults();
 ```
 
-### Glyphs
+---
+
+## Events
+
+The ConfigurationManager provides events to track configuration changes:
+
+### Applied Event
+
+Raised after configuration is applied to the application:
+
+```csharp
+ConfigurationManager.Applied += (sender, e) => 
+{
+    // Configuration has been applied
+    // Update UI or refresh views
+};
+```
 
-Themes support changing the standard set of glyphs used by views (e.g. the default indicator for [Button](~/api/Terminal.Gui.Views.Button.yml)) and line drawing (e.g. [LineCanvas](~/api/Terminal.Gui.Drawing.LineCanvas.yml)).
+### ThemeChanged Event
 
+Raised when the active theme changes:
 
-The value can be either a decimal number or a string. The string may be:
+```csharp
+ThemeManager.ThemeChanged += (sender, e) => 
+{
+    // Theme has changed
+    // Refresh all views to use new theme
+    Application.Top?.SetNeedsDraw();
+};
+```
+
+### CollectionChanged Event
+
+Raised when schemes collection changes:
+
+```csharp
+SchemeManager.CollectionChanged += (sender, e) => 
+{
+    // Schemes have changed
+};
+```
+
+---
+
+## What Can Be Configured
+
+### Application Settings
+
+System-wide settings from [SettingsScope](~/api/Terminal.Gui.Configuration.SettingsScope.yml):
+
+```json
+{
+  "Application.QuitKey": "Esc",
+  "Application.Force16Colors": false,
+  "Application.IsMouseDisabled": false,
+  "Application.ArrangeKey": "Ctrl+F5",
+  "Application.NextTabKey": "Tab",
+  "Application.PrevTabKey": "Shift+Tab",
+  "Application.NextTabGroupKey": "F6",
+  "Application.PrevTabGroupKey": "Shift+F6",
+  "Key.Separator": "+"
+}
+```
+
+### View-Specific Settings
+
+Settings for individual View types from [ThemeScope](~/api/Terminal.Gui.Configuration.ThemeScope.yml):
+
+```json
+{
+  "Window.DefaultBorderStyle": "Single",
+  "Window.DefaultShadow": "None",
+  "Dialog.DefaultBorderStyle": "Heavy",
+  "Dialog.DefaultShadow": "Transparent",
+  "Dialog.DefaultButtonAlignment": "End",
+  "FrameView.DefaultBorderStyle": "Rounded",
+  "Button.DefaultShadow": "None",
+  "PopoverMenu.DefaultKey": "Shift+F10",
+  "FileDialog.MaxSearchResults": 10000
+}
+```
+
+### Glyphs
 
-- A Unicode char (e.g. "☑")
-- A hex value in U+ format (e.g. "U+2611")
-- A hex value in UTF-16 format (e.g. "\\u2611")
+Customize the Unicode characters used for drawing:
 
 ```json
+{
   "Glyphs.RightArrow": "►",
   "Glyphs.LeftArrow": "U+25C4",
   "Glyphs.DownArrow": "\\u25BC",
-  "Glyphs.UpArrow": 965010
+  "Glyphs.UpArrow": 965010,
+  "Glyphs.LeftBracket": "[",
+  "Glyphs.RightBracket": "]",
+  "Glyphs.Checked": "☑",
+  "Glyphs.UnChecked": "☐",
+  "Glyphs.Selected": "◉",
+  "Glyphs.UnSelected": "○"
+}
 ```
 
-The `UI Catalog` application defines a `UICatalog` Theme. Look at the UI Catalog's `./Resources/config.json` file to see how to define a theme.
-
-### Theme and Scheme Management
+Glyphs can be specified as:
+- Unicode character: `"►"`
+- U+ format: `"U+25C4"`
+- UTF-16 format: `"\\u25BC"`
+- Decimal codepoint: `965010`
 
-Terminal.Gui provides two key managers for handling visual themes and schemes:
+### Discovering Configuration Properties
 
-The ThemeManager provides convenient methods for working with themes:
+To find all available configuration properties:
 
 ```csharp
-// Get the currently active theme
-ThemeScope currentTheme = ThemeManager.GetCurrentTheme();
+// Get hard-coded configuration
+SettingsScope hardCoded = ConfigurationManager.GetHardCodedConfig();
 
-// Get all available themes
-Dictionary<string, ThemeScope> themes = ThemeManager.GetThemes();
+// Iterate through all properties
+foreach (var property in hardCoded)
+{
+    Console.WriteLine($"{property.Key} = {property.Value}");
+}
+```
 
-// Get list of theme names
-ImmutableList<string> themeNames = ThemeManager.GetThemeNames();
+Or search the source code for `[ConfigurationProperty]` attributes.
 
-// Get/Set current theme name
-string currentThemeName = ThemeManager.GetCurrentThemeName();
-ThemeManager.Theme = "Dark"; // Switch themes
+---
 
-// Listen for theme changes
-ThemeManager.ThemeChanged += (sender, e) => {
-    // Handle theme changes
-};
+## Themes and Schemes
+
+### Theme Structure
+
+A theme is a named collection bundling visual settings and schemes:
+
+```json
+{
+  "Themes": [
+    {
+      "Dark": {
+        "Dialog.DefaultBorderStyle": "Heavy",
+        "Dialog.DefaultShadow": "Transparent",
+        "Window.DefaultBorderStyle": "Single",
+        "Button.DefaultShadow": "Opaque",
+        "Schemes": [
+          {
+            "TopLevel": {
+              "Normal": { "Foreground": "BrightGreen", "Background": "Black" },
+              "Focus": { "Foreground": "White", "Background": "Cyan" }
+            },
+            "Dialog": {
+              "Normal": { "Foreground": "Black", "Background": "Gray" }
+            }
+          }
+        ]
+      }
+    }
+  ]
+}
 ```
 
-### SchemeManager
+### Creating Custom Themes
 
-The SchemeManager handles schemes within themes. Each theme contains multiple schemes for different UI contexts:
+Custom themes can be defined in configuration files:
+
+```json
+{
+  "Themes": [
+    {
+      "MyCustomTheme": {
+        "Window.DefaultBorderStyle": "Double",
+        "Dialog.DefaultShadow": "Opaque",
+        "Schemes": [
+          {
+            "Base": {
+              "Normal": {
+                "Foreground": "Cyan",
+                "Background": "Black",
+                "Style": "Bold"
+              }
+            }
+          }
+        ]
+      }
+    }
+  ]
+}
+```
+
+Then activate the theme:
 
 ```csharp
-// Get current schemes
-Dictionary<string, Scheme> schemes = SchemeManager.GetCurrentSchemes();
+ThemeManager.Theme = "MyCustomTheme";
+ConfigurationManager.Apply();
+```
 
-// Get list of scheme names
-ImmutableList<string> schemeNames = SchemeManager.GetSchemeNames();
+### Theme Inheritance
 
-// Access specific schemes
-Scheme topLevelScheme = SchemeManager.GetScheme("TopLevel");
+Themes only override specified properties. To build on an existing theme:
 
-// Listen for scheme changes
-SchemeManager.CollectionChanged += (sender, e) => {
-    // Handle scheme changes
-};
+```csharp
+// Start with default theme
+ThemeManager.Theme = "Default";
+ConfigurationManager.Apply();
+
+// Apply custom theme (overrides only what's specified)
+ThemeManager.Theme = "MyCustomTheme";
+ConfigurationManager.Apply();
 ```
 
-### Built-in Schemes
+### TextStyle in Schemes
 
-The following Schemes are available by default:
+Each [Attribute](~/api/Terminal.Gui.Drawing.Attribute.yml) in a scheme now includes [TextStyle](~/api/Terminal.Gui.Drawing.TextStyle.yml):
 
-- **TopLevel**: Used for the application's top-level windows
-- **Base**: Default scheme for most views
-- **Dialog**: Used for dialogs and message boxes
-- **Menu**: Used for menus and status bars
-- **Error**: Used for error messages and dialogs
+```json
+{
+  "Normal": {
+    "Foreground": "White",
+    "Background": "Blue",
+    "Style": "Bold, Underline"
+  }
+}
+```
+
+Available styles (combinable):
+- `None`
+- `Bold`
+- `Faint`
+- `Italic`
+- `Underline`
+- `Blink`
+- `Reverse`
+- `Strikethrough`
 
-Each Scheme defines the attributes for different VisualRoles.
+---
 
-## Application Settings
+## Configuration File Format
 
-Terminal.Gui provides several top-level application settings:
+### Schema
+
+All configuration files must conform to the JSON schema:
+
+**Schema URL:** https://gui-cs.github.io/Terminal.Gui/schemas/tui-config-schema.json
+
+### Root Structure
 
 ```json
 {
-  "Key.Separator": "+",
-  "Application.ArrangeKey": "Ctrl+F5",
+  "$schema": "https://gui-cs.github.io/Terminal.Gui/schemas/tui-config-schema.json",
+  
+  // SettingsScope properties
+  "Application.QuitKey": "Esc",
   "Application.Force16Colors": false,
-  "Application.IsMouseDisabled": false,
-  "Application.NextTabGroupKey": "F6",
-  "Application.NextTabKey": "Tab",
-  "Application.PrevTabGroupKey": "Shift+F6",
-  "Application.PrevTabKey": "Shift+Tab",
-  "Application.QuitKey": "Esc"
+  
+  // Current theme name
+  "Theme": "Dark",
+  
+  // Theme definitions
+  "Themes": [
+    {
+      "Dark": {
+        // ThemeScope properties
+        "Window.DefaultBorderStyle": "Single",
+        // Schemes
+        "Schemes": [ ... ]
+      }
+    }
+  ],
+  
+  // AppSettings
+  "AppSettings": {
+    "MyApp.MySetting": "value"
+  }
 }
 ```
 
-### View-Specific Settings
+### Complete Example
 
-Examples of settings that control specific view behaviors:
+See the default configuration file:
 
-```json
+[!code-json[config.json](../../Terminal.Gui/Resources/config.json)]
+
+---
+
+## Best Practices
+
+### For Application Developers
+
+**1. Enable Early**
+
+Enable ConfigurationManager at the start of `Main()`, before `Application.Init()`:
+
+```csharp
+static void Main()
 {
-  "PopoverMenu.DefaultKey": "Shift+F10",
-  "FileDialog.MaxSearchResults": 10000,
-  "FileDialogStyle.DefaultUseColors": false,
-  "FileDialogStyle.DefaultUseUnicodeCharacters": false
+    ConfigurationManager.Enable(ConfigLocations.All);
+    Application.Init();
+    // ...
 }
 ```
 
-### Key Bindings
+**2. Use AppSettings for App Configuration**
+
+```csharp
+public class MyApp
+{
+    [ConfigurationProperty]
+    public static bool ShowWelcomeMessage { get; set; } = true;
+    
+    [ConfigurationProperty]
+    public static string DefaultDirectory { get; set; } = "";
+}
+```
+
+**3. Ship Default Configuration as Resource**
+
+Include a `Resources/config.json` file in your app:
+
+```xml
+<ItemGroup>
+  <EmbeddedResource Include="Resources\config.json" />
+</ItemGroup>
+```
+
+**4. Handle Configuration Changes**
+
+```csharp
+ConfigurationManager.Applied += (sender, e) => 
+{
+    // Refresh UI when configuration changes
+    RefreshAllViews();
+};
+```
+
+### For Library Developers
+
+**1. Use Appropriate Scopes**
+
+- `SettingsScope` - For system-wide behavior
+- `ThemeScope` - For visual appearance that should be themeable
+- Don't use `AppSettingsScope` in library code
+
+**2. Provide Meaningful Defaults**
+
+```csharp
+[ConfigurationProperty(Scope = typeof(ThemeScope))]
+public static LineStyle DefaultBorderStyle { get; set; } = LineStyle.Single;
+```
+
+**3. Document Configuration Properties**
+
+```csharp
+/// <summary>
+///     Gets or sets the default border style for all Windows.
+/// </summary>
+[ConfigurationProperty(Scope = typeof(ThemeScope))]
+public static LineStyle DefaultBorderStyle { get; set; } = LineStyle.Single;
+```
+
+### Process-Wide Settings
+
+> [!IMPORTANT]
+> Configuration settings are applied at the **process level**. 
+> 
+> Since configuration properties are static, changes affect all applications in the same process. This is typically not an issue for normal applications, but can affect scenarios with:
+> - Multiple Terminal.Gui apps in the same process
+> - Unit tests running in parallel
+> - Hot reload scenarios
 
-> [!WARNING]
->  Configuration Manager support for key bindings is not yet implemented.
+---
 
-Key bindings are defined in the `KeyBindings` property of the configuration file. The value is an array of objects, each object defining a key binding. The key binding object has the following properties:
+## Advanced Topics
 
-- `Key`: The key to bind to. The format is a string describing the key (e.g. "q", "Q,  "Ctrl+Q"). Function keys are specified as "F1", "F2", etc. 
+### JSON Error Handling
 
-# Error Handling
+Control how JSON parsing errors are handled:
 
 ```json
 {
-  "ConfigurationManager.ThrowOnJsonErrors": false
+  "ConfigurationManager.ThrowOnJsonErrors": true
 }
 ```
 
-Set to `true` to throw exceptions on JSON parsing errors instead of silent failures.
+- `false` (default) - Silent failures, errors logged
+- `true` - Throws exceptions on JSON parsing errors
+
+### Manually Trigger Updates
+
+Update ConfigurationManager to reflect current static property values:
+
+```csharp
+// Change a setting programmatically
+Application.QuitKey = Key.Q.WithCtrl;
+
+// Update ConfigurationManager to reflect the change
+ConfigurationManager.UpdateToCurrentValues();
+
+// Save to file (if needed)
+string json = ConfigurationManager.Serialize();
+File.WriteAllText("my-config.json", json);
+```
+
+### Disable ConfigurationManager
+
+Disable and optionally reset to defaults:
+
+```csharp
+// Disable but keep current settings
+ConfigurationManager.Disable(resetToHardCodedDefaults: false);
+
+// Disable and reset to hard-coded defaults
+ConfigurationManager.Disable(resetToHardCodedDefaults: true);
+```
+
+### File System Watching
+
+Watch for configuration file changes:
+
+```csharp
+var watcher = new FileSystemWatcher(
+    Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".tui"));
+watcher.Filter = "*.json";
+watcher.Changed += (s, e) => 
+{
+    ConfigurationManager.Load(ConfigLocations.GlobalHome);
+    ConfigurationManager.Apply();
+};
+watcher.EnableRaisingEvents = true;
+```
+
+See UICatalog's `ConfigurationEditor` scenario for a complete example.
+
+---
+
+## Examples
+
+### Example 1: Simple Theme Switching
+
+```csharp
+using Terminal.Gui;
+using Terminal.Gui.Configuration;
+
+ConfigurationManager.Enable(ConfigLocations.All);
+Application.Init();
+
+var themeSelector = new ComboBox
+{
+    X = 1,
+    Y = 1,
+    Width = 20
+};
+themeSelector.SetSource(ThemeManager.GetThemeNames());
+themeSelector.SelectedItemChanged += (s, e) =>
+{
+    ThemeManager.Theme = e.Value.ToString();
+    ConfigurationManager.Apply();
+};
+
+Application.Run(new Window { Title = "Theme Demo" }).Add(themeSelector);
+Application.Shutdown();
+```
+
+### Example 2: Custom Application Settings
+
+```csharp
+public class MyApp
+{
+    [ConfigurationProperty]
+    public static string LastOpenedFile { get; set; } = "";
+    
+    [ConfigurationProperty]
+    public static int WindowWidth { get; set; } = 80;
+    
+    [ConfigurationProperty]
+    public static int WindowHeight { get; set; } = 25;
+}
+
+// Enable and use
+ConfigurationManager.Enable(ConfigLocations.All);
+
+// Settings are automatically loaded and applied
+var window = new Window
+{
+    Width = MyApp.WindowWidth,
+    Height = MyApp.WindowHeight
+};
+
+// Later, save updated settings
+MyApp.WindowWidth = 100;
+ConfigurationManager.UpdateToCurrentValues();
+// Could save to file here
+```
+
+### Example 3: Runtime Configuration
+
+```csharp
+ConfigurationManager.RuntimeConfig = @"
+{
+  ""Application.QuitKey"": ""Ctrl+Q"",
+  ""Application.Force16Colors"": true,
+  ""Theme"": ""Dark""
+}";
+
+ConfigurationManager.Enable(ConfigLocations.Runtime);
+
+// Settings are now applied
+// QuitKey is Ctrl+Q
+// 16-color mode is forced
+// Dark theme is active
+```
+
+---
+
+## See Also
 
-# Configuration File Schema
+- **[Scheme Deep Dive](scheme.md)** - Color scheme details
+- **[Drawing Deep Dive](drawing.md)** - Color and attribute system
+- **[View Deep Dive](View.md)** - View configuration properties
+- **[Theme Schema](https://gui-cs.github.io/Terminal.Gui/schemas/tui-config-schema.json)** - JSON schema for validation
+- **[Default Config](../../Terminal.Gui/Resources/config.json)** - Complete default configuration
 
-Settings are defined in JSON format, according to the schema found here:
+### UICatalog Examples
 
-https://gui-cs.github.io/Terminal.Gui/schemas/tui-config-schema.json
+The UICatalog application demonstrates configuration management:
 
-## The Default Config File
+- **Configuration Editor** - Interactive editor for configuration files
+- **Themes** - Theme viewer and selector
+- **File System Watcher** - Automatic reload on configuration file changes
 
-To illustrate the syntax, the below is the `config.json` file found in `Terminal.Gui.dll`:
+### API Reference
 
-[!code-json[config.json](../../Terminal.Gui/Resources/config.json)]
+- [ConfigurationManager](~/api/Terminal.Gui.Configuration.ConfigurationManager.yml)
+- [ConfigLocations](~/api/Terminal.Gui.Configuration.ConfigLocations.yml)
+- [SettingsScope](~/api/Terminal.Gui.Configuration.SettingsScope.yml)
+- [ThemeScope](~/api/Terminal.Gui.Configuration.ThemeScope.yml)
+- [AppSettingsScope](~/api/Terminal.Gui.Configuration.AppSettingsScope.yml)
+- [ThemeManager](~/api/Terminal.Gui.Configuration.ThemeManager.yml)
+- [SchemeManager](~/api/Terminal.Gui.Configuration.SchemeManager.yml)
+- [ConfigurationPropertyAttribute](~/api/Terminal.Gui.Configuration.ConfigurationPropertyAttribute.yml)

+ 2 - 0
docfx/docs/drivers.md

@@ -291,6 +291,8 @@ Application.Init();
 
 Terminal.Gui v1 drivers that implement `IConsoleDriver` but not `IConsoleDriverFacade` are still supported through a legacy compatibility layer. However, they do not benefit from the v2 architecture improvements (multi-threading, component separation, etc.).
 
+**Note**: The legacy `MainLoop` infrastructure (including the `MainLoop` class, `IMainLoopDriver` interface, and `FakeMainLoop`) has been removed in favor of the modern architecture. All drivers now use the `MainLoopCoordinator` and `ApplicationMainLoop` system exclusively.
+
 ## See Also
 
 - @Terminal.Gui.Drivers - API Reference

+ 16 - 7
docfx/docs/migratingfromv1.md

@@ -81,7 +81,7 @@ When measuring the screen space taken up by a `string` you can use the extension
 + myString.GetColumns();
 ```
 
-## `View Life Cycle Management
+## View Life Cycle Management
 
 In v1, @Terminal.Gui.View was derived from `Responder` which supported `IDisposable`. In v2, `Responder` has been removed and @Terminal.Gui.View is the base-class supporting `IDisposable`. 
 
@@ -187,7 +187,7 @@ The API for handling keyboard input is significantly improved. See [Keyboard API
 + Application.KeyDown(object? sender, Key e)
 ```
 
-## **@"Terminal.Gui.Input.Command" has been expanded and simplified
+## @Terminal.Gui.Input.Command has been expanded and simplified
 
 In v1, the `Command` enum had duplicate entries and inconsistent naming. In v2 it has been both expanded and simplified.
 
@@ -306,7 +306,7 @@ In v2, this is made consistent and configurable:
 - `Key.CursorDown` - Operates identically to `Application.NextTabStopKey`.
 - `Key.CursorLeft` - Operates identically to `Application.PrevTabStopKey`.
 - `Key.CursorUp` - Operates identically to `Application.PrevTabStopKey`.
-- `Application.NextTabGroupKey` (`Key.F6`) - Navigates to the next view in the view-hierarchy that is a `TabGroup` (see below). If there is no next, the first view which is a `TabGroup`` will gain focus.
+- `Application.NextTabGroupKey` (`Key.F6`) - Navigates to the next view in the view-hierarchy that is a `TabGroup` (see below). If there is no next, the first view which is a `TabGroup` will gain focus.
 - `Application.PrevTabGroupKey` (`Key.F6.WithShift`) - Opposite of `Application.NextTabGroupKey`.
 
 `F6` was chosen to match [Windows](https://learn.microsoft.com/en-us/windows/apps/design/input/keyboard-accelerators#common-keyboard-accelerators)
@@ -336,7 +336,7 @@ Alternatively, if you want to have key events as well as mouse events to fire an
 
 Previously events in Terminal.Gui used a mixture of `Action` (no arguments), `Action<string>` (or other raw datatype) and `Action<EventArgs>`. Now all events use the `EventHandler<EventArgs>` [standard .net design pattern](https://learn.microsoft.com/en-us/dotnet/csharp/event-pattern#event-delegate-signatures).
 
-For example, `event Action`<long> TimeoutAdded` has become `event EventHandler<TimeoutEventArgs> TimeoutAdded`
+For example, `event Action<long> TimeoutAdded` has become `event EventHandler<TimeoutEventArgs> TimeoutAdded`
 
 This change was made for the following reasons:
 
@@ -456,17 +456,26 @@ Additionally, the `Toggle` event was renamed `CheckStateChanging` and made cance
 +cb.AdvanceCheckState ();
 ```
 
-## `MainLoop` is no longer accessible from `Application`
+## `MainLoop` has been removed from `Application`
 
-In v1, you could add timeouts via `Application.MainLoop.AddTimeout` among other things.  In v2, the `MainLoop` object is internal to `Application` and methods previously accessed via `MainLoop` can now be accessed directly via `Application`
+In v1, you could add timeouts via `Application.MainLoop.AddTimeout` and access the `MainLoop` object directly. In v2, the legacy `MainLoop` class has been completely removed as part of the architectural modernization. Timeout functionality and other features previously accessed via `MainLoop` are now available directly through `Application` or `ApplicationImpl`.
 
 ### How to Fix
 
+Replace any `Application.MainLoop` references:
+
 ```diff
 - Application.MainLoop.AddTimeout (TimeSpan time, Func<MainLoop, bool> callback)
 + Application.AddTimeout (TimeSpan time, Func<bool> callback)
 ```
 
+```diff
+- Application.MainLoop.Wakeup ()
++ // No replacement needed - wakeup is handled automatically by the modern architecture
+```
+
+**Note**: The legacy `MainLoop` infrastructure (including `IMainLoopDriver` and `FakeMainLoop`) has been removed. The modern v2 architecture uses `ApplicationImpl`, `MainLoopCoordinator`, and `ApplicationMainLoop` instead.
+
 ## `SendSubViewXXX` renamed and corrected
 
 In v1, the `View` methods to move SubViews within the SubViews list were poorly named and actually operated in reverse of what their names suggested.
@@ -516,4 +525,4 @@ new (
 
 * In v1, `Application.End` called `Dispose ()` on @Terminal.Gui.App.Application.Top (via `Runstate.Toplevel`). This was incorrect as it meant that after `Application.Run` returned, `Application.Top` had been disposed, and any code that wanted to interrogate the results of `Run` by accessing `Application.Top` only worked by accident. This is because GC had not actually happened; if it had the application would have crashed. In v2 `Application.End` does NOT call `Dispose`, and it is the caller to `Application.Run` who is responsible for disposing the `Toplevel` that was either passed to `Application.Run (View)` or created by `Application.Run<T> ()`.
 
-* Any code that creates a `Toplevel`, either by using `top = new()` or by calling either `top = Application.Run ()` or `top = ApplicationRun<T>()` must call `top.Dispose` when complete. The exception to this is if `top` is passed to `myView.Add(top)` making it a subview of `myView`. This is because the semantics of `Add` are that the `myView` takes over responsibility for the subviews lifetimes. Of course, if someone calls `myView.Remove(top)` to remove said subview, they then re-take responsbility for `top`'s lifetime and they must call `top.Dispose`.
+* Any code that creates a `Toplevel`, either by using `top = new()` or by calling either `top = Application.Run ()` or `top = ApplicationRun<T>()` must call `top.Dispose` when complete. The exception to this is if `top` is passed to `myView.Add(top)` making it a subview of `myView`. This is because the semantics of `Add` are that the `myView` takes over responsibility for the subviews lifetimes. Of course, if someone calls `myView.Remove(top)` to remove said subview, they then re-take responsbility for `top`'s lifetime and they must call `top.Dispose`.

+ 72 - 27
docfx/docs/newinv2.md

@@ -18,17 +18,26 @@ This architectural shift has resulted in the removal of thousands of lines of re
 ## Modern Look & Feel - Technical Details
 
 ### TrueColor Support
-- **Implementation**: v2 introduces 24-bit color support by extending the @Terminal.Gui.Drawing.Attribute class to handle RGB values, with fallback to 16-color mode for older terminals. This is evident in the @Terminal.Gui.Drivers.IConsoleDriver implementations, which now map colors to the appropriate terminal escape sequences.
-- **Impact**: Developers can now use a full spectrum of colors without manual palette management, as seen in v1. The @Terminal.Gui.Drawing.Color struct in v2 supports direct RGB input, and drivers handle the translation to terminal capabilities via [IConsoleDriver.SupportsTrueColor](~/api/Terminal.Gui.Drivers.IConsoleDriver.yml#Terminal_Gui_Drivers_IConsoleDriver_SupportsTrueColor).
+
+See the [Drawing Deep Dive](drawing.md) for complete details on the color system.
+
+- **Implementation**: v2 introduces 24-bit color support by extending the [Attribute](~/api/Terminal.Gui.Drawing.Attribute.yml) class to handle RGB values, with fallback to 16-color mode for older terminals. This is evident in the [IConsoleDriver](~/api/Terminal.Gui.Drivers.IConsoleDriver.yml) implementations, which now map colors to the appropriate terminal escape sequences.
+- **Impact**: Developers can now use a full spectrum of colors without manual palette management, as seen in v1. The [Color](~/api/Terminal.Gui.Drawing.Color.yml) struct in v2 supports direct RGB input, and drivers handle the translation to terminal capabilities via [IConsoleDriver.SupportsTrueColor](~/api/Terminal.Gui.Drivers.IConsoleDriver.yml#Terminal_Gui_Drivers_IConsoleDriver_SupportsTrueColor).
 - **Usage**: See the [ColorPicker](~/api/Terminal.Gui.Views.ColorPicker.yml) view for an example of how TrueColor is leveraged to provide a rich color selection UI.
 
 ### Enhanced Borders and Padding (Adornments)
-- **Implementation**: v2 introduces a new @Terminal.Gui.ViewBase.Adornment class hierarchy, with @Terminal.Gui.ViewBase.Margin, @Terminal.Gui.ViewBase.Border, and @Terminal.Gui.ViewBase.Padding as distinct view-like entities that wrap content. This is a significant departure from v1, where borders were often hardcoded or required custom drawing.
-- **Code Change**: In v1, @Terminal.Gui.ViewBase.View had rudimentary border support via properties like `BorderStyle`. In v2, @Terminal.Gui.ViewBase.View has a @Terminal.Gui.ViewBase.View.Border property of type @Terminal.Gui.ViewBase.Border, which is itself a configurable entity with properties like @Terminal.Gui.Drawing.Thickness, [Border.LineStyle](~/api/Terminal.Gui.ViewBase.Border.yml#Terminal_Gui_ViewBase_Border_LineStyle), and [Border.Settings](~/api/Terminal.Gui.ViewBase.Border.yml#Terminal_Gui_ViewBase_Border_Settings).
+
+See the [Layout Deep Dive](layout.md) for complete details on the adornments system.
+
+- **Implementation**: v2 introduces a new [Adornment](~/api/Terminal.Gui.ViewBase.Adornment.yml) class hierarchy, with [Margin](~/api/Terminal.Gui.ViewBase.Margin.yml), [Border](~/api/Terminal.Gui.ViewBase.Border.yml), and [Padding](~/api/Terminal.Gui.ViewBase.Padding.yml) as distinct view-like entities that wrap content. This is a significant departure from v1, where borders were often hardcoded or required custom drawing.
+- **Code Change**: In v1, [View](~/api/Terminal.Gui.ViewBase.View.yml) had rudimentary border support via properties like `BorderStyle`. In v2, [View](~/api/Terminal.Gui.ViewBase.View.yml) has a [View.Border](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Border) property of type [Border](~/api/Terminal.Gui.ViewBase.Border.yml), which is itself a configurable entity with properties like [Thickness](~/api/Terminal.Gui.Drawing.Thickness.yml), [Border.LineStyle](~/api/Terminal.Gui.ViewBase.Border.yml#Terminal_Gui_ViewBase_Border_LineStyle), and [Border.Settings](~/api/Terminal.Gui.ViewBase.Border.yml#Terminal_Gui_ViewBase_Border_Settings).
 - **Impact**: This allows for consistent border rendering across all views and simplifies custom view development by providing a reusable adornment framework.
 
 ### User Configurable Color Themes and Text Styles
-- **Implementation**: v2 adds a @Terminal.Gui.Configuration.ConfigurationManager that supports loading and saving color schemes from configuration files. Themes are applied via @Terminal.Gui.Drawing.Scheme objects, which can be customized per view or globally. Each @Terminal.Gui.Drawing.Attribute in a @Terminal.Gui.Drawing.Scheme now includes a [TextStyle](~/api/Terminal.Gui.Drawing.TextStyle.yml) property supporting Bold, Italic, Underline, Strikethrough, Blink, Reverse, and Faint text styles.
+
+See the [Configuration Deep Dive](config.md) and [Scheme Deep Dive](scheme.md) for complete details.
+
+- **Implementation**: v2 adds a [ConfigurationManager](~/api/Terminal.Gui.Configuration.ConfigurationManager.yml) that supports loading and saving color schemes from configuration files. Themes are applied via [Scheme](~/api/Terminal.Gui.Drawing.Scheme.yml) objects, which can be customized per view or globally. Each [Attribute](~/api/Terminal.Gui.Drawing.Attribute.yml) in a [Scheme](~/api/Terminal.Gui.Drawing.Scheme.yml) now includes a [TextStyle](~/api/Terminal.Gui.Drawing.TextStyle.yml) property supporting Bold, Italic, Underline, Strikethrough, Blink, Reverse, and Faint text styles.
 - **Impact**: Unlike v1, where color schemes were static or required manual override, v2 enables end-users to personalize not just colors but also text styling (bold, italic, underline, etc.) without code changes, significantly enhancing accessibility and user preference support.
 
 ### Enhanced Unicode/Wide Character Support
@@ -36,14 +45,17 @@ This architectural shift has resulted in the removal of thousands of lines of re
 - **Impact**: This fixes v1 issues where wide characters (e.g., CJK scripts) could break layout or input handling, making Terminal.Gui v2 suitable for international applications.
 
 ### LineCanvas
+
+See the [Drawing Deep Dive](drawing.md) for complete details on LineCanvas and the drawing system.
+
 - **Implementation**: A new [LineCanvas](~/api/Terminal.Gui.Drawing.LineCanvas.yml) class provides a drawing API for creating lines and shapes using box-drawing characters. It includes logic for auto-joining lines at intersections, selecting appropriate glyphs dynamically.
-- **Code Example**: In v2, [LineCanvas](~/api/Terminal.Gui.Drawing.LineCanvas.yml) is used internally by views like @Terminal.Gui.ViewBase.Border and @Terminal.Gui.Views.Line to draw clean, connected lines, a feature absent in v1.
+- **Code Example**: In v2, [LineCanvas](~/api/Terminal.Gui.Drawing.LineCanvas.yml) is used internally by views like [Border](~/api/Terminal.Gui.ViewBase.Border.yml) and [Line](~/api/Terminal.Gui.Views.Line.yml) to draw clean, connected lines, a feature absent in v1.
 - **Impact**: Developers can create complex diagrams or UI elements with minimal effort, improving the visual fidelity of terminal applications.
 
 ## Simplified API - Under the Hood
 
 ### API Consistency and Reduction
-- **Change**: v2 revisits every public API, consolidating redundant methods and properties. For example, v1 had multiple focus-related methods scattered across @Terminal.Gui.ViewBase.View and @Terminal.Gui.App.Application; v2 centralizes these in [ApplicationNavigation](~/api/Terminal.Gui.App.ApplicationNavigation.yml).
+- **Change**: v2 revisits every public API, consolidating redundant methods and properties. For example, v1 had multiple focus-related methods scattered across [View](~/api/Terminal.Gui.ViewBase.View.yml) and [Application](~/api/Terminal.Gui.App.Application.yml); v2 centralizes these in [ApplicationNavigation](~/api/Terminal.Gui.App.ApplicationNavigation.yml).
 - **Impact**: This reduces the learning curve for new developers and minimizes the risk of using deprecated or inconsistent APIs.
 - **Example**: The v1 `View.MostFocused` property is replaced by `Application.Navigation.GetFocused()`, reducing traversal overhead and clarifying intent.
 
@@ -63,48 +75,65 @@ This architectural shift has resulted in the removal of thousands of lines of re
 - **Impact**: Developers can predict when resources are released, reducing bugs related to dangling references or uninitialized states.
 
 ### Adornments Framework
-- **Technical Detail**: Adornments are implemented as nested views that surround the content area, each with its own drawing and layout logic. @Terminal.Gui.ViewBase.Border supports multiple @Terminal.Gui.Drawing.LineStyle options (Single, Double, Heavy, Rounded, Dashed, Dotted) with automatic line intersection handling via [LineCanvas](~/api/Terminal.Gui.Drawing.LineCanvas.yml).
-- **Code Change**: In v2, @Terminal.Gui.ViewBase.View has properties @Terminal.Gui.ViewBase.View.Margin, @Terminal.Gui.ViewBase.View.Border, and @Terminal.Gui.ViewBase.View.Padding, each configurable independently, unlike v1's limited border support.
+
+See the [Layout Deep Dive](layout.md) and [View Deep Dive](View.md) for complete details.
+
+- **Technical Detail**: Adornments are implemented as nested views that surround the content area, each with its own drawing and layout logic. [Border](~/api/Terminal.Gui.ViewBase.Border.yml) supports multiple [LineStyle](~/api/Terminal.Gui.Drawing.LineStyle.yml) options (Single, Double, Heavy, Rounded, Dashed, Dotted) with automatic line intersection handling via [LineCanvas](~/api/Terminal.Gui.Drawing.LineCanvas.yml).
+- **Code Change**: In v2, [View](~/api/Terminal.Gui.ViewBase.View.yml) has properties [View.Margin](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Margin), [View.Border](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Border), and [View.Padding](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Padding), each configurable independently, unlike v1's limited border support.
 - **Impact**: This modular approach allows for reusable UI elements and simplifies creating visually consistent applications.
 
 ### Built-in Scrolling/Virtual Content Area
+
+See the [Scrolling Deep Dive](scrolling.md) and [Layout Deep Dive](layout.md) for complete details.
+
 - **v1 Issue**: Scrolling required using `ScrollView` or manual offset management, which was error-prone.
-- **v2 Solution**: Every @Terminal.Gui.ViewBase.View in v2 has a @Terminal.Gui.ViewBase.View.Viewport rectangle representing the visible portion of a potentially larger content area defined by [View.GetContentSize](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_GetContentSize). Changing `Viewport.Location` scrolls the content.
+- **v2 Solution**: Every [View](~/api/Terminal.Gui.ViewBase.View.yml) in v2 has a [View.Viewport](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Viewport) rectangle representing the visible portion of a potentially larger content area defined by [View.GetContentSize](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_GetContentSize). Changing `Viewport.Location` scrolls the content.
 - **Code Example**: In v2, [TextView](~/api/Terminal.Gui.Views.TextView.yml) uses this to handle large text buffers without additional wrapper views.
 - **Impact**: Simplifies implementing scrollable content and reduces the need for specialized container views.
 
 ### Improved ScrollBar
-- **Change**: v2 replaces `ScrollBarView` with [ScrollBar](~/api/Terminal.Gui.Views.ScrollBar.yml), a cleaner implementation integrated with the built-in scrolling system. @Terminal.Gui.ViewBase.View.VerticalScrollBar and @Terminal.Gui.ViewBase.View.HorizontalScrollBar properties enable scroll bars with minimal code.
+- **Change**: v2 replaces `ScrollBarView` with [ScrollBar](~/api/Terminal.Gui.Views.ScrollBar.yml), a cleaner implementation integrated with the built-in scrolling system. [View.VerticalScrollBar](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_VerticalScrollBar) and [View.HorizontalScrollBar](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_HorizontalScrollBar) properties enable scroll bars with minimal code.
 - **Impact**: Developers can add scroll bars to any view without managing separate view hierarchies, a significant usability improvement over v1.
 
 ### DimAuto, PosAnchorEnd, and PosAlign
+
+See the [Layout Deep Dive](layout.md) and [DimAuto Deep Dive](dimauto.md) for complete details.
+
 - **[Dim.Auto](~/api/Terminal.Gui.Dim.yml#Terminal_Gui_Dim_Auto_Terminal_Gui_DimAutoStyle_Terminal_Gui_Dim_Terminal_Gui_Dim_)**: Automatically sizes views based on content or subviews, reducing manual layout calculations.
 - **[Pos.AnchorEnd](~/api/Terminal.Gui.Pos.yml#Terminal_Gui_Pos_AnchorEnd_System_Int32_)**: Allows anchoring to the right or bottom of a superview, enabling flexible layouts not easily achievable in v1.
 - **[Pos.Align](~/api/Terminal.Gui.Pos.yml)**: Provides alignment options (left, center, right) for multiple views, streamlining UI design.
 - **Impact**: These features reduce boilerplate layout code and support responsive designs in terminal constraints.
 
 ### View Arrangement
-- **Technical Detail**: The @Terminal.Gui.ViewBase.View.Arrangement property supports flags like @Terminal.Gui.ViewBase.ViewArrangement.Movable, @Terminal.Gui.ViewBase.ViewArrangement.Resizable, and @Terminal.Gui.ViewBase.ViewArrangement.Overlapped, enabling dynamic UI interactions via keyboard and mouse.
-- **Code Example**: [Window](~/api/Terminal.Gui.Views.Window.yml) in v2 uses @Terminal.Gui.ViewBase.View.Arrangement to allow dragging and resizing, a feature requiring custom logic in v1.
+
+See the [Arrangement Deep Dive](arrangement.md) for complete details.
+
+- **Technical Detail**: The [View.Arrangement](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Arrangement) property supports flags like [ViewArrangement.Movable](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml), [ViewArrangement.Resizable](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml), and [ViewArrangement.Overlapped](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml), enabling dynamic UI interactions via keyboard and mouse.
+- **Code Example**: [Window](~/api/Terminal.Gui.Views.Window.yml) in v2 uses [View.Arrangement](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Arrangement) to allow dragging and resizing, a feature requiring custom logic in v1.
 - **Impact**: Developers can create desktop-like experiences in the terminal with minimal effort.
 
 ### Keyboard Navigation Overhaul
-- **v1 Issue**: Navigation was inconsistent, with coupled concepts like @Terminal.Gui.ViewBase.View.CanFocus and `TabStop` leading to unpredictable focus behavior.
-- **v2 Solution**: v2 decouples these concepts, introduces @Terminal.Gui.Input.TabBehavior enum for clearer intent (`TabStop`, `TabGroup`, `NoStop`), and centralizes navigation logic in [ApplicationNavigation](~/api/Terminal.Gui.App.ApplicationNavigation.yml).
+
+See the [Navigation Deep Dive](navigation.md) for complete details on the navigation system.
+
+- **v1 Issue**: Navigation was inconsistent, with coupled concepts like [View.CanFocus](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_CanFocus) and `TabStop` leading to unpredictable focus behavior.
+- **v2 Solution**: v2 decouples these concepts, introduces [TabBehavior](~/api/Terminal.Gui.Input.TabBehavior.yml) enum for clearer intent (`TabStop`, `TabGroup`, `NoStop`), and centralizes navigation logic in [ApplicationNavigation](~/api/Terminal.Gui.App.ApplicationNavigation.yml).
 - **Impact**: Ensures accessibility by guaranteeing keyboard access to all focusable elements, with unit tests enforcing navigation keys on built-in views.
 
 ### Sizable/Movable Views
-- **Implementation**: Any view can be made resizable or movable by setting @Terminal.Gui.ViewBase.View.Arrangement flags, with built-in mouse and keyboard handlers for interaction.
+- **Implementation**: Any view can be made resizable or movable by setting [View.Arrangement](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Arrangement) flags, with built-in mouse and keyboard handlers for interaction.
 - **Impact**: Enhances user experience by allowing runtime UI customization, a feature limited to specific views like [Window](~/api/Terminal.Gui.Views.Window.yml) in v1.
 
 ## New and Improved Built-in Views - Detailed Analysis
 
+See the [Views Overview](views.md) for a complete catalog of all built-in views.
+
 ### New Views
 
 v2 introduces many new View subclasses that were not present in v1:
 
 - **Bar**: A foundational view for horizontal or vertical layouts of `Shortcut` or other items, used in `StatusBar`, `MenuBarv2`, and `PopoverMenu`.
-- **CharMap**: A scrollable, searchable Unicode character map with support for the Unicode Character Database (UCD) API, enabling users to browse and select from all Unicode codepoints with detailed character information.
+- **CharMap**: A scrollable, searchable Unicode character map with support for the Unicode Character Database (UCD) API, enabling users to browse and select from all Unicode codepoints with detailed character information. See [Character Map Deep Dive](CharacterMap.md).
 - **ColorPicker**: Leverages TrueColor for a comprehensive color selection experience, supporting multiple color models (HSV, RGB, HSL, Grayscale) with interactive color bars.
 - **DatePicker**: Provides a calendar-based date selection UI with month/year navigation, leveraging v2's improved drawing and navigation systems.
 - **FlagSelector**: Enables selection of non-mutually-exclusive flags with checkbox-based UI, supporting both dictionary-based and enum-based flag definitions.
@@ -124,25 +153,37 @@ Many existing views from v1 have been significantly enhanced in v2:
 - **FileDialog** (OpenDialog, SaveDialog): Completely modernized with `TreeView` for hierarchical file navigation, Unicode glyphs for icons, search functionality, and history tracking - far surpassing v1's basic file dialogs.
 - **ScrollBar**: Replaces v1's `ScrollBarView` with a cleaner implementation featuring automatic show/hide, proportional sizing with `ScrollSlider`, and seamless integration with View's built-in scrolling system.
 - **StatusBar**: Rebuilt on the `Bar` infrastructure, providing more flexible item management, automatic sizing, and better visual presentation.
-- **TableView**: Massively enhanced with support for generic collections (via `IEnumerableTableSource`), checkboxes with `CheckBoxTableSourceWrapper`, tree structures via `TreeTableSource`, custom cell rendering, and significantly improved performance.
+- **TableView**: Massively enhanced with support for generic collections (via `IEnumerableTableSource`), checkboxes with `CheckBoxTableSourceWrapper`, tree structures via `TreeTableSource`, custom cell rendering, and significantly improved performance. See [TableView Deep Dive](tableview.md).
 - **ScrollView**: Deprecated in favor of View's built-in scrolling capabilities, eliminating the need for wrapper views and simplifying scrollable content implementation.
 
 ## Beauty - Visual Enhancements
 
 ### Borders
-- **Implementation**: Uses the @Terminal.Gui.ViewBase.Border adornment with @Terminal.Gui.Drawing.LineStyle options and [LineCanvas](~/api/Terminal.Gui.Drawing.LineCanvas.yml) for automatic line intersection handling.
+
+See the [Drawing Deep Dive](drawing.md) for complete details on borders and LineCanvas.
+
+- **Implementation**: Uses the [Border](~/api/Terminal.Gui.ViewBase.Border.yml) adornment with [LineStyle](~/api/Terminal.Gui.Drawing.LineStyle.yml) options and [LineCanvas](~/api/Terminal.Gui.Drawing.LineCanvas.yml) for automatic line intersection handling.
 - **Impact**: Adds visual polish to UI elements, making applications feel more refined compared to v1's basic borders.
 
 ### Gradient
+
+See the [Drawing Deep Dive](drawing.md) for complete details on gradients and fills.
+
 - **Implementation**: [Gradient](~/api/Terminal.Gui.Drawing.Gradient.yml) and [GradientFill](~/api/Terminal.Gui.Drawing.GradientFill.yml) APIs allow rendering color transitions across view elements, using TrueColor for smooth effects.
 - **Impact**: Enables modern-looking UI elements like gradient borders or backgrounds, not possible in v1 without custom drawing.
 
 ## Configuration Manager - Persistence and Customization
-- **Technical Detail**: @Terminal.Gui.Configuration.ConfigurationManager in v2 uses JSON to persist settings like themes, key bindings, and view properties to disk via @Terminal.Gui.Configuration.SettingsScope and [ConfigLocations](~/api/Terminal.Gui.Configuration.ConfigLocations.yml).
+
+See the [Configuration Deep Dive](config.md) for complete details on the configuration system.
+
+- **Technical Detail**: [ConfigurationManager](~/api/Terminal.Gui.Configuration.ConfigurationManager.yml) in v2 uses JSON to persist settings like themes, key bindings, and view properties to disk via [SettingsScope](~/api/Terminal.Gui.Configuration.SettingsScope.yml) and [ConfigLocations](~/api/Terminal.Gui.Configuration.ConfigLocations.yml).
 - **Code Change**: Unlike v1, where settings were ephemeral or hardcoded, v2 provides a centralized system for loading/saving configurations using the [ConfigurationManagerAttribute](~/api/Terminal.Gui.Configuration.ConfigurationManagerAttribute.yml).
 - **Impact**: Allows for user-specific customizations and library-wide settings without recompilation, enhancing flexibility.
 
 ## Logging & Metrics - Debugging and Performance
+
+See the [Logging Deep Dive](logging.md) for complete details on the logging and metrics system.
+
 - **Implementation**: v2 introduces a multi-level logging system via [Logging](~/api/Terminal.Gui.App.Logging.yml) for internal operations (e.g., rendering, input handling) using Microsoft.Extensions.Logging.ILogger, and metrics for performance tracking via [Logging.Meter](~/api/Terminal.Gui.App.Logging.yml#Terminal_Gui_App_Logging_Meter) (e.g., frame rate, redraw times, iteration timing).
 - **Impact**: Developers can diagnose issues like slow redraws or terminal compatibility problems using standard .NET logging frameworks (Serilog, NLog, etc.) and metrics tools (dotnet-counters), a capability absent in v1, reducing guesswork in debugging.
 
@@ -153,32 +194,36 @@ Many existing views from v1 have been significantly enhanced in v2:
 
 ## Updated Keyboard API - Comprehensive Input Handling
 
+See the [Keyboard Deep Dive](keyboard.md) and [Command Deep Dive](command.md) for complete details.
+
 ### Key Class
 - **Change**: Replaces v1's `KeyEvent` struct with a [Key](~/api/Terminal.Gui.Input.Key.yml) class, providing a high-level abstraction over raw key codes with properties for modifiers and key type.
 - **Impact**: Simplifies keyboard handling by abstracting platform differences, making code more portable and readable.
 
 ### Key Bindings
-- **Implementation**: v2 introduces a binding system mapping keys to @Terminal.Gui.Input.Command enums via @Terminal.Gui.ViewBase.View.KeyBindings, with scopes (`Application`, `Focused`, `HotKey`) for priority.
-- **Impact**: Replaces v1's ad-hoc key handling with a structured approach, allowing views to declare supported commands via @Terminal.Gui.ViewBase.View.AddCommand and customize responses easily.
+- **Implementation**: v2 introduces a binding system mapping keys to [Command](~/api/Terminal.Gui.Input.Command.yml) enums via [View.KeyBindings](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_KeyBindings), with scopes (`Application`, `Focused`, `HotKey`) for priority.
+- **Impact**: Replaces v1's ad-hoc key handling with a structured approach, allowing views to declare supported commands via [View.AddCommand](~/api/Terminal.Gui.ViewBase.View.yml) and customize responses easily.
 - **Example**: [TextField](~/api/Terminal.Gui.Views.TextField.yml) in v2 binds `Key.Tab` to text insertion rather than focus change, customizable by developers.
 
 ### Default Close Key
-- **Change**: Changed from `Ctrl+Q` in v1 to `Esc` in v2 for closing apps or @Terminal.Gui.Views.Toplevel views, accessible via [Application.QuitKey](~/api/Terminal.Gui.App.Application.yml#Terminal_Gui_App_Application_QuitKey).
+- **Change**: Changed from `Ctrl+Q` in v1 to `Esc` in v2 for closing apps or [Toplevel](~/api/Terminal.Gui.Views.Toplevel.yml) views, accessible via [Application.QuitKey](~/api/Terminal.Gui.App.Application.yml#Terminal_Gui_App_Application_QuitKey).
 - **Impact**: Aligns with common user expectations, improving UX consistency across terminal applications.
 
 ## Updated Mouse API - Enhanced Interaction
 
+See the [Mouse Deep Dive](mouse.md) for complete details on mouse handling.
+
 ### MouseEventArgs Class
-- **Change**: Replaces v1's `MouseEventEventArgs` with [MouseEventArgs](~/api/Terminal.Gui.Input.MouseEventArgs.yml), providing a cleaner structure for mouse data (position, flags via @Terminal.Gui.Input.MouseFlags).
+- **Change**: Replaces v1's `MouseEventEventArgs` with [MouseEventArgs](~/api/Terminal.Gui.Input.MouseEventArgs.yml), providing a cleaner structure for mouse data (position, flags via [MouseFlags](~/api/Terminal.Gui.Input.MouseFlags.yml)).
 - **Impact**: Simplifies event handling with a more intuitive API, reducing errors in mouse interaction logic.
 
 ### Granular Mouse Handling
-- **Implementation**: v2 offers specific events for clicks (@Terminal.Gui.ViewBase.View.MouseClick), double-clicks, and movement, with [MouseFlags](~/api/Terminal.Gui.Input.MouseFlags.yml) for button states.
+- **Implementation**: v2 offers specific events for clicks ([View.MouseClick](~/api/Terminal.Gui.ViewBase.View.yml)), double-clicks, and movement, with [MouseFlags](~/api/Terminal.Gui.Input.MouseFlags.yml) for button states.
 - **Impact**: Developers can handle complex mouse interactions (e.g., drag-and-drop) more easily than in v1.
 
 ### Highlight Event and Continuous Button Presses
-- **Highlight**: Views can visually respond to mouse hover or click via the @Terminal.Gui.ViewBase.View.Highlight event and [View.HighlightStyle](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_HighlightStyle) property.
-- **Continuous Presses**: Setting @Terminal.Gui.ViewBase.View.WantContinuousButtonPresses = true repeats @Terminal.Gui.Input.Command.Accept during button hold, useful for sliders or buttons.
+- **Highlight**: Views can visually respond to mouse hover or click via the [View.Highlight](~/api/Terminal.Gui.ViewBase.View.yml) event and [View.HighlightStyle](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_HighlightStyle) property.
+- **Continuous Presses**: Setting [View.WantContinuousButtonPresses](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_WantContinuousButtonPresses) = true repeats [Command.Accept](~/api/Terminal.Gui.Input.Command.yml) during button hold, useful for sliders or buttons.
 - **Impact**: Enhances interactive feedback, making terminal UIs feel more responsive.
 
 ## AOT Support - Deployment and Performance

+ 6 - 6
docfx/includes/arrangement-lexicon.md

@@ -1,10 +1,10 @@
 | Term | Meaning |
 |:-----|:--------|
-| **Arrange Mode** | Interactive mode activated via `Ctrl+F5` that displays indicators on arrangeable views and allows keyboard-based arrangement. |
+| **Arrange Mode** | Interactive mode activated via `Ctrl+F5` (configurable via [Application.ArrangeKey](~/api/Terminal.Gui.App.Application.yml#Terminal_Gui_App_Application_ArrangeKey)) that displays indicators on arrangeable views and allows keyboard-based arrangement. |
 | **Arrangement** | The feature of [Layout](~/docs/layout.md) which controls how the user can use the mouse and keyboard to arrange views and enables either **Tiled** or **Overlapped** layouts. |
-| **Modal** | A view run as an "application" via @Terminal.Gui.App.Application.Run where `Modal == true`. Has constrained z-order with modal view at z-order 1. |
-| **Movable** | A View that can be moved by the user using keyboard or mouse. Enabled by setting @Terminal.Gui.ViewBase.ViewArrangement.Movable flag. |
-| **Overlapped** | Layout where SubViews have overlapping Frames with Z-order determining visual stacking. Enabled by @Terminal.Gui.ViewBase.ViewArrangement.Overlapped flag. |
-| **Resizable** | A View that can be resized by the user using keyboard or mouse. Enabled by setting @Terminal.Gui.ViewBase.ViewArrangement.Resizable flag. |
+| **Modal** | A view run as an "application" via [Application.Run](~/api/Terminal.Gui.App.Application.yml) where `Modal == true`. Has constrained z-order with modal view at z-order 1. |
+| **Movable** | A View that can be moved by the user using keyboard or mouse. Enabled by setting [ViewArrangement.Movable](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml) flag. |
+| **Overlapped** | Layout where SubViews have overlapping Frames with Z-order determining visual stacking. Enabled by [ViewArrangement.Overlapped](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml) flag. |
+| **Resizable** | A View that can be resized by the user using keyboard or mouse. Enabled by setting [ViewArrangement.Resizable](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml) flag. |
 | **Runnable** | A view where `Application.Run(Toplevel)` is called. Each non-modal Runnable view has its own `RunState` and operates as a self-contained application. |
-| **Tiled** | Layout where SubViews typically do not overlap, with no z-order. Default layout mode set to @Terminal.Gui.ViewBase.ViewArrangement.Fixed. |
+| **Tiled** | Layout where SubViews typically do not overlap, with no z-order. Default layout mode set to [ViewArrangement.Fixed](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml). |

BIN
local_packages/Terminal.Gui.2.0.0.nupkg


BIN
local_packages/Terminal.Gui.2.0.0.snupkg