Explorar el Código

Fixed more bad code

Tig hace 1 año
padre
commit
6ebee8d42b

+ 84 - 96
Terminal.Gui/Application.cs

@@ -8,19 +8,12 @@ namespace Terminal.Gui;
 /// <summary>A static, singleton class representing the application. This class is the entry point for the application.</summary>
 /// <example>
 ///     <code>
-/// // A simple Terminal.Gui app that creates a window with a frame and title with 
-/// // 5 rows/columns of padding.
-/// Application.Init();
-/// var win = new Window ($"Example App ({Application.QuitKey} to quit)") {
-///   X = 5,
-///   Y = 5,
-///   Width = Dim.Fill (5),
-///   Height = Dim.Fill (5)
-/// };
-/// Application.Top.Add(win);
-/// Application.Run();
-/// Application.Shutdown();
-/// </code>
+///     Application.Init();
+///     var win = new Window ($"Example App ({Application.QuitKey} to quit)");
+///     Application.Run(win);
+///     win.Dispose();
+///     Application.Shutdown();
+///     </code>
 /// </example>
 /// <remarks>TODO: Flush this out.</remarks>
 public static partial class Application
@@ -93,6 +86,7 @@ public static partial class Application
         {
             t.Running = false;
 #if DEBUG_IDISPOSABLE
+
             // Don't dispose the toplevels. It's up to caller dispose them
             Debug.Assert (t.WasDisposed);
 #endif
@@ -101,10 +95,12 @@ public static partial class Application
         _topLevels.Clear ();
         Current = null;
 #if DEBUG_IDISPOSABLE
+
         // Don't dispose the Top. It's up to caller dispose it
         if (Top is { })
         {
             Debug.Assert (Top.WasDisposed);
+
             // If End wasn't called _cachedRunStateToplevel may be null
             if (_cachedRunStateToplevel is { })
             {
@@ -181,12 +177,14 @@ public static partial class Application
     /// </para>
     /// <para>
     ///     <see cref="Shutdown"/> must be called when the application is closing (typically after
-    ///     <see cref="Run(Func{Exception, bool}, ConsoleDriver)"/> has returned) to ensure resources are cleaned up and terminal settings
+    ///     <see cref="Run(Func{Exception, bool}, ConsoleDriver)"/> has returned) to ensure resources are cleaned up and
+    ///     terminal settings
     ///     restored.
     /// </para>
     /// <para>
     ///     The <see cref="Run{T}(Func{Exception, bool}, ConsoleDriver)"/> function combines
-    ///     <see cref="Init(ConsoleDriver, string)"/> and <see cref="Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/> into a single
+    ///     <see cref="Init(ConsoleDriver, string)"/> and <see cref="Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/>
+    ///     into a single
     ///     call. An application cam use <see cref="Run{T}(Func{Exception, bool}, ConsoleDriver)"/> without explicitly calling
     ///     <see cref="Init(ConsoleDriver, string)"/>.
     /// </para>
@@ -247,7 +245,7 @@ public static partial class Application
         // valid after a Driver is loaded. In this cases we need just 
         // `Settings` so we can determine which driver to use.
         // Don't reset, so we can inherit the theme from the previous run.
-        Load (false);
+        Load ();
         Apply ();
 
         // Ignore Configuration for ForceDriver if driverName is specified
@@ -346,7 +344,8 @@ public static partial class Application
     /// <summary>Shutdown an application initialized with <see cref="Init"/>.</summary>
     /// <remarks>
     ///     Shutdown must be called for every call to <see cref="Init"/> or
-    ///     <see cref="Application.Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/> to ensure all resources are cleaned up (Disposed)
+    ///     <see cref="Application.Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/> to ensure all resources are cleaned
+    ///     up (Disposed)
     ///     and terminal settings are restored.
     /// </remarks>
     public static void Shutdown ()
@@ -393,13 +392,11 @@ public static partial class Application
     /// </remarks>
     public static RunState Begin (Toplevel toplevel)
     {
-        if (toplevel is null)
-        {
-            throw new ArgumentNullException (nameof (toplevel));
-        }
+        ArgumentNullException.ThrowIfNull (toplevel);
 
 #if DEBUG_IDISPOSABLE
         Debug.Assert (!toplevel.WasDisposed);
+
         if (_cachedRunStateToplevel is { } && _cachedRunStateToplevel != toplevel)
         {
             Debug.Assert (_cachedRunStateToplevel.WasDisposed);
@@ -411,7 +408,7 @@ public static partial class Application
             throw new InvalidOperationException ("Only one Overlapped Container is allowed.");
         }
 
-        // Ensure the mouse is ungrabed.
+        // Ensure the mouse is ungrabbed.
         MouseGrabView = null;
 
         var rs = new RunState (toplevel);
@@ -437,7 +434,7 @@ public static partial class Application
             if (Top is { } && toplevel != Top && !_topLevels.Contains (Top))
             {
                 // If Top was already disposed and isn't on the Toplevels Stack,
-                // clean it up here if is the same as _latestClosedRunStateToplevel
+                // clean it up here if is the same as _cachedRunStateToplevel
                 if (Top == _cachedRunStateToplevel)
                 {
                     Top = null;
@@ -482,7 +479,7 @@ public static partial class Application
 
             if (_topLevels.FindDuplicates (new ToplevelEqualityComparer ()).Count > 0)
             {
-                throw new ArgumentException ("There are duplicates Toplevels Id's");
+                throw new ArgumentException ("There are duplicates Toplevel IDs");
             }
         }
 
@@ -502,7 +499,7 @@ public static partial class Application
             if (toplevel.Visible)
             {
                 Current?.OnDeactivate (toplevel);
-                var previousCurrent = Current;
+                Toplevel previousCurrent = Current;
                 Current = toplevel;
                 Current.OnActivate (previousCurrent);
 
@@ -528,11 +525,8 @@ public static partial class Application
             MoveCurrent (Current);
         }
 
-        //if (Toplevel.LayoutStyle == LayoutStyle.Computed) {
         toplevel.SetRelativeLayout (Driver.Bounds);
 
-        //}
-
         // BUGBUG: This call is likely not needed.
         toplevel.LayoutSubviews ();
         toplevel.PositionToplevels ();
@@ -548,39 +542,40 @@ public static partial class Application
             Driver.Refresh ();
         }
 
-        NotifyNewRunState?.Invoke (toplevel, new RunStateEventArgs (rs));
+        NotifyNewRunState?.Invoke (toplevel, new (rs));
 
         return rs;
     }
 
     /// <summary>
-    ///     Runs the application by calling <see cref="Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/> with the value of
-    ///     <see cref="Top"/>.
+    ///     Runs the application by creating a <see cref="Toplevel"/> object and calling <see cref="Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/>.
     /// </summary>
     /// <remarks>
+    ///     <para>Calling <see cref="Init"/> first is not needed as this function will initialize the application.</para>
     ///     <para>
     ///         <see cref="Shutdown"/> must be called when the application is closing (typically after Run> has returned) to
     ///         ensure resources are cleaned up and terminal settings restored.
     ///     </para>
-    /// <para>
-    /// The caller is responsible for disposing the object returned by this method.</para>
-    /// </para>
+    ///     <para>
+    ///         The caller is responsible for disposing the object returned by this method.
+    ///     </para>
+    /// </remarks>
     /// <returns>The created <see cref="Toplevel"/> object. The caller is responsible for disposing this object.</returns>
     public static Toplevel Run (Func<Exception, bool> errorHandler = null, ConsoleDriver driver = null) { return Run<Toplevel> (errorHandler, driver); }
 
     /// <summary>
-    ///     Runs the application by calling <see cref="Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/> with a new instance of the
-    ///     specified <see cref="Toplevel"/>-derived class.
-    ///     <para>Calling <see cref="Init"/> first is not needed as this function will initialize the application.</para>
+    ///     Runs the application by creating a <see cref="Toplevel"/>-derived object of type <c>T</c> and calling
+    ///     <see cref="Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/>.
     /// </summary>
     /// <remarks>
+    ///     <para>Calling <see cref="Init"/> first is not needed as this function will initialize the application.</para>
     ///     <para>
     ///         <see cref="Shutdown"/> must be called when the application is closing (typically after Run> has returned) to
     ///         ensure resources are cleaned up and terminal settings restored.
     ///     </para>
-    /// <para>
-    /// The caller is responsible for disposing the object returned by this method.</para>
-    /// </para>
+    ///     <para>
+    ///         The caller is responsible for disposing the object returned by this method.
+    ///     </para>
     /// </remarks>
     /// <param name="errorHandler"></param>
     /// <param name="driver">
@@ -590,18 +585,16 @@ public static partial class Application
     /// </param>
     /// <returns>The created T object. The caller is responsible for disposing this object.</returns>
     public static T Run<T> (Func<Exception, bool> errorHandler = null, ConsoleDriver driver = null)
-        where T : Toplevel, new()
+        where T : Toplevel, new ()
     {
         var top = new T ();
 
-        EnsureValidInitialization (top, driver);
-
-        RunApp (top, errorHandler);
+        Run (top, errorHandler, driver);
 
         return top;
     }
 
-    /// <summary>Runs the main loop on the given <see cref="Toplevel"/> container.</summary>
+    /// <summary>Runs the Application using the provided <see cref="Toplevel"/> view.</summary>
     /// <remarks>
     ///     <para>
     ///         This method is used to start processing events for the main application, but it is also used to run other
@@ -623,6 +616,7 @@ public static partial class Application
     ///         <see cref="RunLoop(RunState)"/> method will only process any pending events, timers, idle handlers and then
     ///         return control immediately.
     ///     </para>
+    ///     <para>Calling <see cref="Init"/> first is not needed as this function will initialize the application.</para>
     ///     <para>
     ///         RELEASE builds only: When <paramref name="errorHandler"/> is <see langword="null"/> any exceptions will be
     ///         rethrown. Otherwise, if <paramref name="errorHandler"/> will be called. If <paramref name="errorHandler"/>
@@ -638,17 +632,35 @@ public static partial class Application
     /// <param name="driver">
     ///     The <see cref="ConsoleDriver"/> to use. If not specified the default driver for the platform will
     ///     be used ( <see cref="WindowsDriver"/>, <see cref="CursesDriver"/>, or <see cref="NetDriver"/>). Must be
-    ///     <see langword="null"/> if <see cref="Init"/> has already been called.
+    ///     <see langword="null"/> if <see cref="Init"/> was called.
     /// </param>
     public static void Run (Toplevel view, Func<Exception, bool> errorHandler = null, ConsoleDriver driver = null)
     {
-        EnsureValidInitialization (view, driver);
+        // Validate that Init has been called and that the Toplevel is valid.
+        if (view is null)
+        {
+            throw new ArgumentException ($"{view.GetType ().Name} must be derived from TopLevel");
+        }
 
-        RunApp (view, errorHandler);
-    }
+        if (_initialized)
+        {
+            if (Driver is null)
+            {
+                // Disposing before throwing
+                view.Dispose ();
+
+                // This code path should be impossible because Init(null, null) will select the platform default driver
+                throw new InvalidOperationException (
+                                                     "Init() completed without a driver being set (this should be impossible); Run<T>() cannot be called."
+                                                    );
+            }
+        }
+        else
+        {
+            // Init() has NOT been called.
+            InternalInit (driver, null, true);
+        }
 
-    private static void RunApp (Toplevel view, Func<Exception, bool> errorHandler = null)
-    {
         var resume = true;
 
         while (resume)
@@ -683,33 +695,6 @@ public static partial class Application
         }
     }
 
-    private static void EnsureValidInitialization (Toplevel top, ConsoleDriver driver)
-    {
-        if (top is null)
-        {
-            throw new ArgumentException ($"{top.GetType ().Name} must be derived from TopLevel");
-        }
-
-        if (_initialized)
-        {
-            if (Driver is null)
-            {
-                // Ensure disposing the toplevel before throwing
-                top.Dispose ();
-
-                // This code path should be impossible because Init(null, null) will select the platform default driver
-                throw new InvalidOperationException (
-                                                     "Init() completed without a driver being set (this should be impossible); Run<T>() cannot be called."
-                                                    );
-            }
-        }
-        else
-        {
-            // Init() has NOT been called.
-            InternalInit (driver, null, true);
-        }
-    }
-
     /// <summary>Adds a timeout to the application.</summary>
     /// <remarks>
     ///     When time specified passes, the callback will be invoked. If the callback returns true, the timeout will be
@@ -838,7 +823,7 @@ public static partial class Application
             }
 
             MainLoop.RunIteration ();
-            Iteration?.Invoke (null, new IterationEventArgs ());
+            Iteration?.Invoke (null, new ());
             EnsureModalOrVisibleAlwaysOnTop (state.Toplevel);
 
             if (state.Toplevel != Current)
@@ -897,10 +882,10 @@ public static partial class Application
         }
     }
 
-    /// <summary>Stops running the most recent <see cref="Toplevel"/> or the <paramref name="top"/> if provided.</summary>
+    /// <summary>Stops the provided <see cref="Toplevel"/>, causing or the <paramref name="top"/> if provided.</summary>
     /// <param name="top">The <see cref="Toplevel"/> to stop.</param>
     /// <remarks>
-    ///     <para>This will cause <see cref="Application.Run(Func{Exception, bool}, ConsoleDriver)"/> to return.</para>
+    ///     <para>This will cause <see cref="Application.Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/> to return.</para>
     ///     <para>
     ///         Calling <see cref="Application.RequestStop"/> is equivalent to setting the <see cref="Toplevel.Running"/>
     ///         property on the currently running <see cref="Toplevel"/> to false.
@@ -935,7 +920,7 @@ public static partial class Application
                 return;
             }
 
-            ev = new ToplevelClosingEventArgs (top);
+            ev = new (top);
             top.OnClosing (ev);
 
             if (ev.Cancel)
@@ -1023,7 +1008,7 @@ public static partial class Application
     {
         if (EndAfterFirstIteration)
         {
-            NotifyStopRunState?.Invoke (top, new ToplevelEventArgs (top));
+            NotifyStopRunState?.Invoke (top, new (top));
         }
     }
 
@@ -1106,6 +1091,7 @@ public static partial class Application
         {
             _cachedRunStateToplevel = runState.Toplevel;
         }
+
         runState.Toplevel = null;
         runState.Dispose ();
     }
@@ -1125,10 +1111,12 @@ public static partial class Application
     public static Toplevel Top { get; private set; }
 
     /// <summary>
-    ///     The current <see cref="Toplevel"/> object. This is updated when
-    ///     <see cref="Application.Run(Func{Exception, bool}, ConsoleDriver)"/> enters and leaves to point to the current
+    ///     The current <see cref="Toplevel"/> object. This is updated in <see cref="Application.Begin"/> enters and leaves to point to the current
     ///     <see cref="Toplevel"/> .
     /// </summary>
+    /// <remarks>
+    /// Only relevant in scenarios where <see cref="Toplevel.IsOverlappedContainer"/> is <see langword="true"/>.
+    /// </remarks>
     /// <value>The current.</value>
     public static Toplevel Current { get; private set; }
 
@@ -1314,7 +1302,7 @@ public static partial class Application
             t.SetRelativeLayout (Rectangle.Empty with { Size = args.Size });
             t.LayoutSubviews ();
             t.PositionToplevels ();
-            t.OnSizeChanging (new SizeChangedEventArgs (args.Size));
+            t.OnSizeChanging (new (args.Size));
         }
 
         Refresh ();
@@ -1380,7 +1368,7 @@ public static partial class Application
 
         if (!OnUnGrabbingMouse (MouseGrabView))
         {
-            var view = MouseGrabView;
+            View view = MouseGrabView;
             MouseGrabView = null;
             OnUnGrabbedMouse (view);
         }
@@ -1419,7 +1407,7 @@ public static partial class Application
             return;
         }
 
-        GrabbedMouse?.Invoke (view, new ViewEventArgs (view));
+        GrabbedMouse?.Invoke (view, new (view));
     }
 
     private static void OnUnGrabbedMouse (View view)
@@ -1429,7 +1417,7 @@ public static partial class Application
             return;
         }
 
-        UnGrabbedMouse?.Invoke (view, new ViewEventArgs (view));
+        UnGrabbedMouse?.Invoke (view, new (view));
     }
 
 #nullable enable
@@ -1474,7 +1462,7 @@ public static partial class Application
             a.MouseEvent.View = view;
         }
 
-        MouseEvent?.Invoke (null, new MouseEventEventArgs (a.MouseEvent));
+        MouseEvent?.Invoke (null, new (a.MouseEvent));
 
         if (a.MouseEvent.Handled)
         {
@@ -1541,9 +1529,9 @@ public static partial class Application
 
         if (view is Adornment adornment)
         {
-            var frameLoc = adornment.ScreenToFrame (a.MouseEvent.X, a.MouseEvent.Y);
+            Point frameLoc = adornment.ScreenToFrame (a.MouseEvent.X, a.MouseEvent.Y);
 
-            me = new MouseEvent
+            me = new()
             {
                 X = frameLoc.X,
                 Y = frameLoc.Y,
@@ -1556,7 +1544,7 @@ public static partial class Application
         {
             Point boundsPoint = view.ScreenToBounds (a.MouseEvent.X, a.MouseEvent.Y);
 
-            me = new MouseEvent
+            me = new()
             {
                 X = boundsPoint.X,
                 Y = boundsPoint.Y,
@@ -1620,7 +1608,7 @@ public static partial class Application
             {
                 Key oldKey = _alternateForwardKey;
                 _alternateForwardKey = value;
-                OnAlternateForwardKeyChanged (new KeyChangedEventArgs (oldKey, value));
+                OnAlternateForwardKeyChanged (new (oldKey, value));
             }
         }
     }
@@ -1647,7 +1635,7 @@ public static partial class Application
             {
                 Key oldKey = _alternateBackwardKey;
                 _alternateBackwardKey = value;
-                OnAlternateBackwardKeyChanged (new KeyChangedEventArgs (oldKey, value));
+                OnAlternateBackwardKeyChanged (new (oldKey, value));
             }
         }
     }
@@ -1674,7 +1662,7 @@ public static partial class Application
             {
                 Key oldKey = _quitKey;
                 _quitKey = value;
-                OnQuitKeyChanged (new KeyChangedEventArgs (oldKey, value));
+                OnQuitKeyChanged (new (oldKey, value));
             }
         }
     }

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

@@ -9,7 +9,7 @@ namespace Terminal.Gui;
 /// </summary>
 /// <remarks>
 ///     To run the <see cref="Dialog"/> modally, create the <see cref="Dialog"/>, and pass it to
-///     <see cref="Application.Run(Func{Exception, bool})"/>. This will execute the dialog until it terminates via the
+///     <see cref="Application.Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/>. This will execute the dialog until it terminates via the
 ///     [ESC] or [CTRL-Q] key, or when one of the views or buttons added to the dialog calls
 ///     <see cref="Application.RequestStop"/>.
 /// </remarks>

+ 2 - 2
Terminal.Gui/Views/FileDialog.cs

@@ -339,7 +339,7 @@ public class FileDialog : Dialog
 
     /// <summary>
     ///     Gets all files/directories selected or an empty collection <see cref="AllowsMultipleSelection"/> is
-    ///     <see langword="false"/> or <see cref="Canceled"/>.
+    ///     <see langword="false"/> or <see cref="CancelSearch"/>.
     /// </summary>
     /// <remarks>If selecting only a single file/directory then you should use <see cref="Path"/> instead.</remarks>
     public IReadOnlyList<string> MultiSelected { get; private set; }
@@ -359,7 +359,7 @@ public class FileDialog : Dialog
 
     /// <summary>
     ///     Gets or Sets the selected path in the dialog. This is the result that should be used if
-    ///     <see cref="AllowsMultipleSelection"/> is off and <see cref="Canceled"/> is true.
+    ///     <see cref="AllowsMultipleSelection"/> is off and <see cref="CancelSearch"/> is true.
     /// </summary>
     public string Path
     {

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

@@ -36,7 +36,7 @@ public enum OpenMode
 ///     </para>
 ///     <para>
 ///         To use, create an instance of <see cref="OpenDialog"/>, and pass it to
-///         <see cref="Application.Run(Func{Exception, bool})"/>. This will run the dialog modally, and when this returns,
+///         <see cref="Application.Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/>. This will run the dialog modally, and when this returns,
 ///         the list of files will be available on the <see cref="FilePaths"/> property.
 ///     </para>
 ///     <para>To select more than one file, users can use the spacebar, or control-t.</para>

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

@@ -17,7 +17,7 @@ namespace Terminal.Gui;
 /// <remarks>
 ///     <para>
 ///         To use, create an instance of <see cref="SaveDialog"/>, and pass it to
-///         <see cref="Application.Run(Func{Exception, bool})"/>. This will run the dialog modally, and when this returns,
+///         <see cref="Application.Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/>. This will run the dialog modally, and when this returns,
 ///         the <see cref="FileName"/>property will contain the selected file name or null if the user canceled.
 ///     </para>
 /// </remarks>

+ 3 - 3
Terminal.Gui/Views/Toplevel.cs

@@ -9,7 +9,7 @@ namespace Terminal.Gui;
 /// <remarks>
 ///     <para>
 ///         Toplevels can run as modal (popup) views, started by calling
-///         <see cref="Application.Run(Toplevel, Func{Exception,bool})"/>. They return control to the caller when
+///         <see cref="Application.Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/>. They return control to the caller when
 ///         <see cref="Application.RequestStop(Toplevel)"/> has been called (which sets the <see cref="Toplevel.Running"/>
 ///         property to <c>false</c>).
 ///     </para>
@@ -17,7 +17,7 @@ namespace Terminal.Gui;
 ///         A Toplevel is created when an application initializes Terminal.Gui by calling <see cref="Application.Init"/>.
 ///         The application Toplevel can be accessed via <see cref="Application.Top"/>. Additional Toplevels can be created
 ///         and run (e.g. <see cref="Dialog"/>s. To run a Toplevel, create the <see cref="Toplevel"/> and call
-///         <see cref="Application.Run(Toplevel, Func{Exception,bool})"/>.
+///         <see cref="Application.Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/>.
 ///     </para>
 /// </remarks>
 public partial class Toplevel : View
@@ -452,7 +452,7 @@ public partial class Toplevel : View
     /// <inheritdoc/>
     public override void Remove (View view)
     {
-        if (this is Toplevel Toplevel && Toplevel.MenuBar is { })
+        if (this is Toplevel { MenuBar: { } })
         {
             RemoveMenuStatusBar (view);
         }

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

@@ -143,7 +143,7 @@ public class Wizard : Dialog
     ///             <description>Add the Wizard to a containing view with <see cref="View.Add(View)"/>.</description>
     ///         </item>
     ///     </list>
-    ///     If a non-Modal Wizard is added to the application after <see cref="Application.Run(Func{Exception, bool})"/> has
+    ///     If a non-Modal Wizard is added to the application after <see cref="Application.Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/> has
     ///     been called the first step must be explicitly set by setting <see cref="CurrentStep"/> to
     ///     <see cref="GetNextStep()"/>:
     ///     <code>

+ 47 - 30
UICatalog/Scenario.cs

@@ -77,18 +77,6 @@ public class Scenario : IDisposable
     public string TopLevelColorScheme = "Base";
     private bool _disposedValue;
 
-    /// <summary>
-    ///     The Toplevel for the <see cref="Scenario"/>. This should be set to <see cref="Terminal.Gui.Application.Top"/>.
-    /// </summary>
-    public Toplevel Top { get; set; }
-
-    /// <summary>
-    ///     The Window for the <see cref="Scenario"/>. This should be set to <see cref="Terminal.Gui.Application.Top"/> in
-    ///     most cases.
-    /// </summary>
-    public Window Win { get; set; }
-
-
     /// <summary>
     ///     Helper function to get the list of categories a <see cref="Scenario"/> belongs to (defined in
     ///     <see cref="ScenarioCategory"/>)
@@ -128,17 +116,9 @@ public class Scenario : IDisposable
         return objects.OrderBy (s => s.GetName ()).ToList ();
     }
 
-
-    public virtual void Main ()
-    {
-        Init ();
-        Setup ();
-        Run ();
-    }
-
-
     /// <summary>
-    ///     Helper that calls <see cref="Application.Init"/> and creates the default <see cref="Terminal.Gui.Window"/> implementation with a frame and label
+    ///     Helper that calls <see cref="Application.Init"/> and creates the default <see cref="Terminal.Gui.Window"/>
+    ///     implementation with a frame and label
     ///     showing the name of the <see cref="Scenario"/> and logic to exit back to the Scenario picker UI. Override
     ///     <see cref="Init"/> to provide any <see cref="Terminal.Gui.Toplevel"/> behavior needed.
     /// </summary>
@@ -152,6 +132,7 @@ public class Scenario : IDisposable
     ///         creating any views or calling other Terminal.Gui APIs.
     ///     </para>
     /// </remarks>
+    [ObsoleteAttribute ("This method is obsolete and will be removed in v2. Use Main instead.", false)]
     public virtual void Init ()
     {
         Application.Init ();
@@ -161,7 +142,7 @@ public class Scenario : IDisposable
 
         Top = new ();
 
-        Win = new Window
+        Win = new()
         {
             Title = $"{Application.QuitKey} to Quit - Scenario: {GetName ()}",
             X = 0,
@@ -173,6 +154,25 @@ public class Scenario : IDisposable
         Top.Add (Win);
     }
 
+    /// <summary>
+    ///     Called by UI Catalog to run the <see cref="Scenario"/>. This is the main entry point for the <see cref="Scenario"/>
+    ///     .
+    /// </summary>
+    /// <remarks>
+    ///     <para>
+    ///         Scenario developers are encouraged to override this method as the primary way of authoring a new
+    ///         scenario.
+    ///     </para>
+    ///     <para>
+    ///         The base implementation calls <see cref="Init"/>, <see cref="Setup"/>, and <see cref="Run"/>.
+    ///     </para>
+    public virtual void Main ()
+    {
+        Init ();
+        Setup ();
+        Run ();
+    }
+
     /// <summary>
     ///     Runs the <see cref="Scenario"/>. Override to start the <see cref="Scenario"/> using a <see cref="Toplevel"/>
     ///     different than `Top`.
@@ -181,6 +181,7 @@ public class Scenario : IDisposable
     ///     Overrides that do not call the base.<see cref="Run"/>, must call <see cref="Application.Shutdown"/> before
     ///     returning.
     /// </remarks>
+    [ObsoleteAttribute ("This method is obsolete and will be removed in v2. Use Main instead.", false)]
     public virtual void Run ()
     {
         // Must explicitly call Application.Shutdown method to shutdown.
@@ -189,12 +190,27 @@ public class Scenario : IDisposable
 
     /// <summary>Override this to implement the <see cref="Scenario"/> setup logic (create controls, etc...).</summary>
     /// <remarks>This is typically the best place to put scenario logic code.</remarks>
+    [ObsoleteAttribute ("This method is obsolete and will be removed in v2. Use Main instead.", false)]
     public virtual void Setup () { }
 
+    /// <summary>
+    ///     The Toplevel for the <see cref="Scenario"/>. This should be set to <see cref="Terminal.Gui.Application.Top"/>.
+    /// </summary>
+    //[ObsoleteAttribute ("This property is obsolete and will be removed in v2. Use Main instead.", false)]
+    public Toplevel Top { get; set; }
+
     /// <summary>Gets the Scenario Name + Description with the Description padded based on the longest known Scenario name.</summary>
     /// <returns></returns>
     public override string ToString () { return $"{GetName ().PadRight (_maxScenarioNameLen)}{GetDescription ()}"; }
-    
+
+    /// <summary>
+    ///     The Window for the <see cref="Scenario"/>. This should be set to <see cref="Terminal.Gui.Application.Top"/> in
+    ///     most cases.
+    /// </summary>
+    //[ObsoleteAttribute ("This property is obsolete and will be removed in v2. Use Main instead.", false)]
+    public Window Win { get; set; }
+
+#region IDispose
     public void Dispose ()
     {
         // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
@@ -215,6 +231,7 @@ public class Scenario : IDisposable
             _disposedValue = true;
         }
     }
+#endregion IDispose
 
     /// <summary>Returns a list of all Categories set by all of the <see cref="Scenario"/>s defined in the project.</summary>
     internal static List<string> GetAllCategories ()
@@ -250,9 +267,6 @@ public class Scenario : IDisposable
     {
         public ScenarioCategory (string Name) { this.Name = Name; }
 
-        /// <summary>Category Name</summary>
-        public string Name { get; set; }
-
         /// <summary>Static helper function to get the <see cref="Scenario"/> Categories given a Type</summary>
         /// <param name="t"></param>
         /// <returns>list of category names</returns>
@@ -269,6 +283,9 @@ public class Scenario : IDisposable
         /// <param name="t"></param>
         /// <returns>Name of the category</returns>
         public static string GetName (Type t) { return ((ScenarioCategory)GetCustomAttributes (t) [0]).Name; }
+
+        /// <summary>Category Name</summary>
+        public string Name { get; set; }
     }
 
     /// <summary>Defines the metadata (Name and Description) for a <see cref="Scenario"/></summary>
@@ -284,9 +301,6 @@ public class Scenario : IDisposable
         /// <summary><see cref="Scenario"/> Description</summary>
         public string Description { get; set; }
 
-        /// <summary><see cref="Scenario"/> Name</summary>
-        public string Name { get; set; }
-
         /// <summary>Static helper function to get the <see cref="Scenario"/> Description given a Type</summary>
         /// <param name="t"></param>
         /// <returns></returns>
@@ -296,5 +310,8 @@ public class Scenario : IDisposable
         /// <param name="t"></param>
         /// <returns></returns>
         public static string GetName (Type t) { return ((ScenarioMetadata)GetCustomAttributes (t) [0]).Name; }
+
+        /// <summary><see cref="Scenario"/> Name</summary>
+        public string Name { get; set; }
     }
 }

+ 10 - 5
UnitTests/Application/ApplicationTests.cs

@@ -974,15 +974,20 @@ public class ApplicationTests
                                      Assert.NotNull (Application.Top);
                                      Application.RequestStop ();
                                  };
-        Application.Run (null, driver);
+        var top = Application.Run (null, driver);
 #if DEBUG_IDISPOSABLE
-        Assert.False (Application.Top.WasDisposed);
+        Assert.Equal(top, Application.Top);
+        Assert.False (top.WasDisposed);
         var exception = Record.Exception (() => Application.Shutdown ());
         Assert.NotNull (exception);
-        Assert.False (Application.Top.WasDisposed);
+        Assert.False (top.WasDisposed);
+#endif
+
         // It's up to caller to dispose it
-        Application.Top.Dispose ();
-        Assert.True (Application.Top.WasDisposed);
+        top.Dispose ();
+
+#if DEBUG_IDISPOSABLE
+        Assert.True (top.WasDisposed);
 #endif
         Assert.NotNull (Application.Top);
 

+ 2 - 2
UnitTests/Application/SynchronizatonContextTests.cs

@@ -46,7 +46,7 @@ public class SyncrhonizationContextTests
                  );
 
         // blocks here until the RequestStop is processed at the end of the test
-        Application.Run ();
+        Application.Run ().Dispose ();
         Assert.True (success);
     }
 
@@ -79,7 +79,7 @@ public class SyncrhonizationContextTests
                  );
 
         // blocks here until the RequestStop is processed at the end of the test
-        Application.Run ();
+        Application.Run ().Dispose ();
         Assert.True (success);
     }
 }

+ 1 - 2
UnitTests/Dialogs/DialogTests.cs

@@ -1126,8 +1126,7 @@ public class DialogTests
                          }
                      };
 
-        Run ();
-        Top.Dispose ();
+        Run ().Dispose ();
         Shutdown ();
 
         Assert.Equal (4, iterations);

+ 9 - 9
UnitTests/Dialogs/MessageBoxTests.cs

@@ -41,7 +41,7 @@ public class MessageBoxTests
                                              break;
                                      }
                                  };
-        Application.Run ();
+        Application.Run ().Dispose ();
 
         Assert.Equal (1, result);
     }
@@ -77,7 +77,7 @@ public class MessageBoxTests
                                              break;
                                      }
                                  };
-        Application.Run ();
+        Application.Run ().Dispose ();
 
         Assert.Equal (-1, result);
     }
@@ -115,7 +115,7 @@ public class MessageBoxTests
                                              break;
                                      }
                                  };
-        Application.Run ();
+        Application.Run ().Dispose ();
 
         Assert.Equal (1, result);
     }
@@ -152,7 +152,7 @@ public class MessageBoxTests
                                      }
                                  };
 
-        Application.Run ();
+        Application.Run ().Dispose ();
     }
 
     [Theory]
@@ -233,7 +233,7 @@ public class MessageBoxTests
                                      }
                                  };
 
-        Application.Run ();
+        Application.Run ().Dispose ();
     }
 
     [Fact]
@@ -604,7 +604,7 @@ ffffffffffffffffffff
                                      }
                                  };
 
-        Application.Run ();
+        Application.Run ().Dispose ();
     }
 
     [Fact]
@@ -655,7 +655,7 @@ ffffffffffffffffffff
                                      }
                                  };
 
-        Application.Run ();
+        Application.Run ().Dispose ();
     }
 
     [Fact]
@@ -756,7 +756,7 @@ ffffffffffffffffffff
                                      }
                                  };
 
-        Application.Run ();
+        Application.Run ().Dispose ();
     }
 
     [Theory]
@@ -905,6 +905,6 @@ ffffffffffffffffffff
                                      }
                                  };
 
-        Application.Run ();
+        Application.Run ().Dispose ();
     }
 }

+ 27 - 32
UnitTests/UICatalog/ScenarioTests.cs

@@ -53,29 +53,28 @@ public class ScenarioTests
             uint abortTime = 500;
 
             // If the scenario doesn't close within 500ms, this will force it to quit
-            Func<bool> forceCloseCallback = () =>
-                                            {
-                                                if (Application.Top.Running && FakeConsole.MockKeyPresses.Count == 0)
-                                                {
-                                                    Application.RequestStop ();
-
-                                                    // See #2474 for why this is commented out
-                                                    Assert.Fail (
-                                                                 $"'{
-                                                                     scenario.GetName ()
-                                                                 }' failed to Quit with {
-                                                                     Application.QuitKey
-                                                                 } after {
-                                                                     abortTime
-                                                                 }ms. Force quit."
-                                                                );
-                                                }
-
-                                                return false;
-                                            };
+            bool ForceCloseCallback ()
+            {
+                if (Application.Top.Running && FakeConsole.MockKeyPresses.Count == 0)
+                {
+                    Application.RequestStop ();
+
+                    // See #2474 for why this is commented out
+                    Assert.Fail (
+                                 $"'{
+                                     scenario.GetName ()
+                                 }' failed to Quit with {
+                                     Application.QuitKey
+                                 } after {
+                                     abortTime
+                                 }ms. Force quit.");
+                }
+
+                return false;
+            }
 
             //output.WriteLine ($"  Add timeout to force quit after {abortTime}ms");
-            _ = Application.AddTimeout (TimeSpan.FromMilliseconds (abortTime), forceCloseCallback);
+            _ = Application.AddTimeout (TimeSpan.FromMilliseconds (abortTime), ForceCloseCallback);
 
             Application.Iteration += (s, a) =>
                                      {
@@ -87,9 +86,7 @@ public class ScenarioTests
                                          }
                                      };
 
-            scenario.Init ();
-            scenario.Setup ();
-            scenario.Run ();
+            scenario.Main ();
             scenario.Dispose ();
 
             Application.Shutdown ();
@@ -135,7 +132,7 @@ public class ScenarioTests
 
         Application.Init (new FakeDriver ());
 
-        Toplevel Top = new Toplevel ();
+        Toplevel top = new Toplevel ();
 
         _viewClasses = GetAllViewClassesCollection ()
                        .OrderBy (t => t.Name)
@@ -321,9 +318,9 @@ public class ScenarioTests
 
         _hRadioGroup.SelectedItemChanged += (s, selected) => DimPosChanged (_curView);
 
-        Top.Add (_leftPane, _settingsPane, _hostPane);
+        top.Add (_leftPane, _settingsPane, _hostPane);
 
-        Top.LayoutSubviews ();
+        top.LayoutSubviews ();
 
         _curView = CreateClass (_viewClasses.First ().Value);
 
@@ -348,11 +345,11 @@ public class ScenarioTests
                                      }
                                  };
 
-        Application.Run (Top);
+        Application.Run (top);
 
         Assert.Equal (_viewClasses.Count, iterations);
 
-        Top.Dispose ();
+        top.Dispose ();
         Application.Shutdown ();
 
         void DimPosChanged (View view)
@@ -631,9 +628,7 @@ public class ScenarioTests
                                        Assert.Equal (KeyCode.CtrlMask | KeyCode.Q, args.KeyCode);
                                    };
 
-        generic.Init ();
-        generic.Setup ();
-        generic.Run ();
+        generic.Main ();
 
         Assert.Equal (0, abortCount);
 

+ 1 - 1
UnitTests/Views/StatusBarTests.cs

@@ -175,7 +175,7 @@ CTRL-O Open {
                                      iteration++;
                                  };
 
-        Application.Run ();
+        Application.Run ().Dispose ();
     }
 
     [Fact]

+ 5 - 3
UnitTests/Views/ToplevelTests.cs

@@ -1839,10 +1839,10 @@ public class ToplevelTests
                                     BorderStyle = LineStyle.Single
                                 };
                                 Assert.Equal (testWindow, Application.Current);
-                                Application.Current.DrawContentComplete += testWindow_DrawContentComplete;
+                                Application.Current.DrawContentComplete += OnDrawContentComplete;
                                 top.Add (viewAddedToTop);
 
-                                void testWindow_DrawContentComplete (object sender, DrawEventArgs e)
+                                void OnDrawContentComplete (object sender, DrawEventArgs e)
                                 {
                                     Assert.Equal (new Rectangle (1, 3, 18, 16), viewAddedToTop.Frame);
 
@@ -1857,7 +1857,7 @@ public class ToplevelTests
                                     View.Driver.AddStr ("Three");
                                     Application.Driver.Clip = savedClip;
 
-                                    Application.Current.DrawContentComplete -= testWindow_DrawContentComplete;
+                                    Application.Current.DrawContentComplete -= OnDrawContentComplete;
                                 }
                             };
         RunState rsTestWindow = Application.Begin (testWindow);
@@ -1936,6 +1936,8 @@ public class ToplevelTests
         Application.End (rsTop);
     }
 
+    private void OnDrawContentComplete (object sender, DrawEventArgs e) { throw new NotImplementedException (); }
+
     [Fact]
     [AutoInitShutdown]
     public void Activating_MenuBar_By_Alt_Key_Does_Not_Throw ()