| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606 |
- namespace Terminal.Gui.Views;
- /// <summary>
- /// Toplevel views are used for both an application's main view (filling the entire screen and for modal (pop-up)
- /// views such as <see cref="Dialog"/>, <see cref="MessageBox"/>, and <see cref="Wizard"/>).
- /// </summary>
- /// <remarks>
- /// <para>
- /// Toplevel views can run as modal (popup) views, started by calling
- /// <see cref="IApplication.Run(Toplevel, Func{Exception, bool})"/>. They return control to the caller when
- /// <see cref="IApplication.RequestStop(Toplevel)"/> has been called (which sets the <see cref="Toplevel.Running"/>
- /// property to <c>false</c>).
- /// </para>
- /// <para>
- /// A Toplevel is created when an application initializes Terminal.Gui by calling <see cref="IApplication.Init"/>.
- /// The application Toplevel can be accessed via <see cref="IApplication.Current"/>. 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="IApplication.Run(Toplevel, Func{Exception, bool})"/>.
- /// </para>
- /// <para>
- /// Toplevel implements <see cref="IRunnable"/> to support the runnable session lifecycle with proper event handling
- /// following the Cancellable Work Pattern (CWP).
- /// </para>
- /// </remarks>
- public partial class Toplevel : View, IRunnable
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="Toplevel"/> class,
- /// defaulting to full screen. The <see cref="View.Width"/> and <see cref="View.Height"/> properties will be set to the
- /// dimensions of the terminal using <see cref="Dim.Fill(Dim)"/>.
- /// </summary>
- public Toplevel ()
- {
- CanFocus = true;
- TabStop = TabBehavior.TabGroup;
- Arrangement = ViewArrangement.Overlapped;
- Width = Dim.Fill ();
- Height = Dim.Fill ();
- SchemeName = SchemeManager.SchemesToSchemeName (Schemes.Toplevel);
- MouseClick += Toplevel_MouseClick;
- }
- #region Keyboard & Mouse
- // TODO: IRunnable: Re-implement - Modal means IRunnable, ViewArrangement.Overlapped where modalView.Z > allOtherViews.Max (v = v.Z), and exclusive key/mouse input.
- /// <summary>
- /// Determines whether the <see cref="Toplevel"/> is modal or not. If set to <c>false</c> (the default):
- /// <list type="bullet">
- /// <item>
- /// <description><see cref="View.OnKeyDown"/> events will propagate keys upwards.</description>
- /// </item>
- /// <item>
- /// <description>The Toplevel will act as an embedded view (not a modal/pop-up).</description>
- /// </item>
- /// </list>
- /// If set to <c>true</c>:
- /// <list type="bullet">
- /// <item>
- /// <description><see cref="View.OnKeyDown"/> events will NOT propagate keys upwards.</description>
- /// </item>
- /// <item>
- /// <description>The Toplevel will and look like a modal (pop-up) (e.g. see <see cref="Dialog"/>.</description>
- /// </item>
- /// </list>
- /// </summary>
- public bool Modal { get; set; }
- private void Toplevel_MouseClick (object? sender, MouseEventArgs e) { e.Handled = InvokeCommand (Command.HotKey) == true; }
- #endregion
- #region SubViews
- // TODO: Deprecate - Any view can host a menubar in v2
- /// <summary>Gets the latest <see cref="MenuBar"/> added into this Toplevel.</summary>
- public MenuBar? MenuBar => (MenuBar?)SubViews?.LastOrDefault (s => s is MenuBar);
- //// TODO: Deprecate - Any view can host a statusbar in v2
- ///// <summary>Gets the latest <see cref="StatusBar"/> added into this Toplevel.</summary>
- //public StatusBar? StatusBar => (StatusBar?)SubViews?.LastOrDefault (s => s is StatusBar);
- #endregion
- #region Life Cycle
- // TODO: IRunnable: Re-implement as a property on IRunnable
- /// <summary>Gets or sets whether the main loop for this <see cref="Toplevel"/> is running or not.</summary>
- /// <remarks>Setting this property directly is discouraged. Use <see cref="IApplication.RequestStop()"/> instead.</remarks>
- public bool Running { get; set; }
- // TODO: IRunnable: Re-implement in IRunnable
- /// <summary>
- /// <see langword="true"/> if was already loaded by the <see cref="IApplication.Begin(Toplevel)"/>
- /// <see langword="false"/>, otherwise.
- /// </summary>
- public bool IsLoaded { get; private set; }
- /// <summary>Invoked when the Toplevel <see cref="SessionToken"/> active.</summary>
- /// <remarks>
- /// <para>
- /// <b>Obsolete:</b> Use <see cref="IRunnable.Activated"/> instead. This event is maintained for backward
- /// compatibility and will be raised alongside the new <see cref="IRunnable.Activated"/> event.
- /// </para>
- /// </remarks>
- [Obsolete ("Use IRunnable.Activated instead. This event is maintained for backward compatibility.")]
- public event EventHandler<ToplevelEventArgs>? Activate;
- /// <summary>Invoked when the Toplevel<see cref="SessionToken"/> ceases to be active.</summary>
- /// <remarks>
- /// <para>
- /// <b>Obsolete:</b> Use <see cref="IRunnable.Deactivated"/> instead. This event is maintained for backward
- /// compatibility and will be raised alongside the new <see cref="IRunnable.Deactivated"/> event.
- /// </para>
- /// </remarks>
- [Obsolete ("Use IRunnable.Deactivated instead. This event is maintained for backward compatibility.")]
- public event EventHandler<ToplevelEventArgs>? Deactivate;
- /// <summary>Invoked when the Toplevel's <see cref="SessionToken"/> is closed by <see cref="IApplication.End(SessionToken)"/>.</summary>
- /// <remarks>
- /// <para>
- /// <b>Obsolete:</b> This event is maintained for backward compatibility. The IRunnable architecture
- /// combines this functionality into the <see cref="IRunnable.Stopped"/> event.
- /// </para>
- /// </remarks>
- [Obsolete ("Use IRunnable.Stopped instead. This event is maintained for backward compatibility.")]
- public event EventHandler<ToplevelEventArgs>? Closed;
- /// <summary>
- /// Invoked when the Toplevel's <see cref="SessionToken"/> is being closed by
- /// <see cref="IApplication.RequestStop(Toplevel)"/>.
- /// </summary>
- /// <remarks>
- /// <para>
- /// <b>Obsolete:</b> Use <see cref="IRunnable.Stopping"/> instead. This event is maintained for backward
- /// compatibility and will be raised alongside the new <see cref="IRunnable.Stopping"/> event.
- /// </para>
- /// </remarks>
- [Obsolete ("Use IRunnable.Stopping instead. This event is maintained for backward compatibility.")]
- public event EventHandler<ToplevelClosingEventArgs>? Closing;
- /// <summary>
- /// Invoked when the <see cref="Toplevel"/> <see cref="SessionToken"/> has begun to be loaded. A Loaded event handler
- /// is a good place to finalize initialization before calling Run.
- /// </summary>
- /// <remarks>
- /// <para>
- /// <b>Obsolete:</b> Use <see cref="View.Initialized"/> instead. The Loaded event conceptually maps to
- /// the Initialized event from the ISupportInitialize pattern, which is now part of IRunnable.
- /// </para>
- /// </remarks>
- [Obsolete ("Use View.Initialized instead. The Loaded event maps to the Initialized event from ISupportInitialize.")]
- public event EventHandler? Loaded;
- /// <summary>
- /// Called from <see cref="IApplication.Begin(Toplevel)"/> before the <see cref="Toplevel"/> redraws for the first
- /// time.
- /// </summary>
- /// <remarks>
- /// Overrides must call base.OnLoaded() to ensure any Toplevel subviews are initialized properly and the
- /// <see cref="Loaded"/> event is raised.
- /// </remarks>
- public virtual void OnLoaded ()
- {
- IsLoaded = true;
- foreach (var view in SubViews.Where (v => v is Toplevel))
- {
- var tl = (Toplevel)view;
- tl.OnLoaded ();
- }
- Loaded?.Invoke (this, EventArgs.Empty);
- }
- /// <summary>
- /// Invoked when the <see cref="Toplevel"/> main loop has started it's first iteration. Subscribe to this event to
- /// perform tasks when the <see cref="Toplevel"/> has been laid out and focus has been set. changes.
- /// <para>
- /// A Ready event handler is a good place to finalize initialization after calling
- /// <see cref="IApplication.Run(Toplevel, Func{Exception, bool})"/> on this <see cref="Toplevel"/>.
- /// </para>
- /// </summary>
- /// <remarks>
- /// <para>
- /// <b>Obsolete:</b> Use <see cref="View.Initialized"/> instead. The Ready event is similar to Initialized
- /// but was fired later in the lifecycle. The IRunnable architecture consolidates these into Initialized.
- /// </para>
- /// </remarks>
- [Obsolete ("Use View.Initialized instead. The Ready event is consolidated into the Initialized event.")]
- public event EventHandler? Ready;
- /// <summary>
- /// Stops and closes this <see cref="Toplevel"/>. If this Toplevel is the top-most Toplevel,
- /// <see cref="IApplication.RequestStop(Toplevel)"/> will be called, causing the application to exit.
- /// </summary>
- public virtual void RequestStop ()
- {
- App?.RequestStop (App?.Current);
- }
- /// <summary>
- /// Invoked when the Toplevel <see cref="SessionToken"/> has been unloaded. A Unloaded event handler is a good place
- /// to dispose objects after calling <see cref="IApplication.End(SessionToken)"/>.
- /// </summary>
- /// <remarks>
- /// <para>
- /// <b>Obsolete:</b> Use <see cref="IRunnable.Stopped"/> instead. The Unloaded event is consolidated into
- /// the Stopped event in the IRunnable architecture.
- /// </para>
- /// </remarks>
- [Obsolete ("Use IRunnable.Stopped instead. The Unloaded event is consolidated into the Stopped event.")]
- public event EventHandler? Unloaded;
- internal virtual void OnActivate (Toplevel deactivated) { Activate?.Invoke (this, new (deactivated)); }
- internal virtual void OnClosed (Toplevel top) { Closed?.Invoke (this, new (top)); }
- internal virtual bool OnClosing (ToplevelClosingEventArgs ev)
- {
- Closing?.Invoke (this, ev);
- return ev.Cancel;
- }
- internal virtual void OnDeactivate (Toplevel activated) { Deactivate?.Invoke (this, new (activated)); }
- /// <summary>
- /// Called from run loop after the <see cref="Toplevel"/> has entered the first iteration
- /// of the loop.
- /// </summary>
- internal virtual void OnReady ()
- {
- foreach (var view in SubViews.Where (v => v is Toplevel))
- {
- var tl = (Toplevel)view;
- tl.OnReady ();
- }
- Ready?.Invoke (this, EventArgs.Empty);
- }
- /// <summary>Called from <see cref="IApplication.End(SessionToken)"/> before the <see cref="Toplevel"/> is disposed.</summary>
- internal virtual void OnUnloaded ()
- {
- foreach (var view in SubViews.Where (v => v is Toplevel))
- {
- var tl = (Toplevel)view;
- tl.OnUnloaded ();
- }
- Unloaded?.Invoke (this, EventArgs.Empty);
- }
- #endregion
- #region IRunnable Implementation
- // Note: Running property is already defined above in the Life Cycle region (line 86)
- // Note: Initializing and Initialized events are inherited from View (ISupportInitialize pattern)
- /// <inheritdoc/>
- public event EventHandler<System.ComponentModel.CancelEventArgs>? Stopping;
- /// <inheritdoc/>
- public event EventHandler? Stopped;
- /// <inheritdoc/>
- public event EventHandler<RunnableActivatingEventArgs>? Activating;
- /// <inheritdoc/>
- public event EventHandler<RunnableEventArgs>? Activated;
- /// <inheritdoc/>
- public event EventHandler<RunnableDeactivatingEventArgs>? Deactivating;
- /// <inheritdoc/>
- public event EventHandler<RunnableEventArgs>? Deactivated;
- /// <inheritdoc/>
- public virtual void RaiseStoppingEvent ()
- {
- // CWP Phase 1: Pre-notification via virtual method (can cancel)
- if (OnStopping ())
- {
- return; // Stopping canceled
- }
- // CWP Phase 2: Event notification (can cancel)
- var args = new System.ComponentModel.CancelEventArgs ();
- Stopping?.Invoke (this, args);
- if (args.Cancel)
- {
- return; // Stopping canceled
- }
- // CWP Phase 3: Perform the work (stop the session)
- Running = false;
- // CWP Phase 4: Post-notification via virtual method
- OnStopped ();
- // CWP Phase 5: Post-notification event
- Stopped?.Invoke (this, EventArgs.Empty);
- }
- /// <inheritdoc/>
- public virtual bool RaiseActivatingEvent (IRunnable? deactivated)
- {
- // CWP Phase 1: Pre-notification via virtual method (can cancel)
- if (OnActivating (deactivated))
- {
- return true; // Activation canceled
- }
- // CWP Phase 2: Event notification (can cancel)
- var args = new RunnableActivatingEventArgs (this, deactivated);
- Activating?.Invoke (this, args);
- if (args.Cancel)
- {
- return true; // Activation canceled
- }
- // CWP Phase 3: Work is done by Application (setting Current)
- // CWP Phase 4 & 5: Call post-notification methods
- OnActivated (deactivated);
- return false; // Activation succeeded
- }
- /// <inheritdoc/>
- public virtual void RaiseActivatedEvent (IRunnable? deactivated)
- {
- Activated?.Invoke (this, new RunnableEventArgs (this));
- }
- /// <inheritdoc/>
- public virtual bool RaiseDeactivatingEvent (IRunnable? activated)
- {
- // CWP Phase 1: Pre-notification via virtual method (can cancel)
- if (OnDeactivating (activated))
- {
- return true; // Deactivation canceled
- }
- // CWP Phase 2: Event notification (can cancel)
- var args = new RunnableDeactivatingEventArgs (this, activated);
- Deactivating?.Invoke (this, args);
- if (args.Cancel)
- {
- return true; // Deactivation canceled
- }
- // CWP Phase 3: Work is done by Application (changing Current)
- // CWP Phase 4 & 5: Call post-notification methods
- OnDeactivated (activated);
- return false; // Deactivation succeeded
- }
- /// <inheritdoc/>
- public virtual void RaiseDeactivatedEvent (IRunnable? activated)
- {
- Deactivated?.Invoke (this, new RunnableEventArgs (this));
- }
- /// <summary>
- /// Called before <see cref="Stopping"/> event. Override to cancel stopping.
- /// </summary>
- /// <returns><see langword="true"/> to cancel; <see langword="false"/> to proceed.</returns>
- /// <remarks>
- /// <para>
- /// This is the first phase of the Cancellable Work Pattern for stopping.
- /// Default implementation calls the legacy <see cref="OnClosing"/> method for backward compatibility.
- /// </para>
- /// </remarks>
- protected virtual bool OnStopping ()
- {
- // For backward compatibility, delegate to legacy OnClosing method
- var ev = new ToplevelClosingEventArgs (this);
- return OnClosing (ev);
- }
- /// <summary>
- /// Called after session has stopped. Override for post-stop cleanup.
- /// </summary>
- /// <remarks>
- /// Default implementation does nothing. For backward compatibility, the legacy <see cref="Closed"/>
- /// event is raised by Application.End().
- /// </remarks>
- protected virtual void OnStopped ()
- {
- // Default: do nothing
- // Note: Legacy Closed event is raised by Application.End()
- }
- /// <summary>
- /// Called before <see cref="Activating"/> event. Override to cancel activation.
- /// </summary>
- /// <param name="deactivated">The previously active runnable being deactivated, or null if none.</param>
- /// <returns><see langword="true"/> to cancel; <see langword="false"/> to proceed.</returns>
- /// <remarks>
- /// Default implementation returns false (allow activation). For backward compatibility,
- /// the legacy <see cref="OnActivate"/> method is called after activation succeeds.
- /// </remarks>
- protected virtual bool OnActivating (IRunnable? deactivated)
- {
- return false; // Default: allow activation
- }
- /// <summary>
- /// Called after activation succeeds. Override for post-activation logic.
- /// </summary>
- /// <param name="deactivated">The previously active runnable that was deactivated, or null if none.</param>
- /// <remarks>
- /// Default implementation raises the <see cref="Activated"/> event and calls the legacy
- /// <see cref="OnActivate"/> method for backward compatibility.
- /// </remarks>
- protected virtual void OnActivated (IRunnable? deactivated)
- {
- RaiseActivatedEvent (deactivated);
- // For backward compatibility, call legacy OnActivate if deactivated is a Toplevel
- if (deactivated is Toplevel tl)
- {
- OnActivate (tl);
- }
- else
- {
- // If not a Toplevel, still raise the legacy Activate event with null
- Activate?.Invoke (this, new ToplevelEventArgs (null));
- }
- }
- /// <summary>
- /// Called before <see cref="Deactivating"/> event. Override to cancel deactivation.
- /// </summary>
- /// <param name="activated">The newly activated runnable, or null if none.</param>
- /// <returns><see langword="true"/> to cancel; <see langword="false"/> to proceed.</returns>
- /// <remarks>
- /// Default implementation returns false (allow deactivation).
- /// </remarks>
- protected virtual bool OnDeactivating (IRunnable? activated)
- {
- return false; // Default: allow deactivation
- }
- /// <summary>
- /// Called after deactivation succeeds. Override for post-deactivation logic.
- /// </summary>
- /// <param name="activated">The newly activated runnable, or null if none.</param>
- /// <remarks>
- /// Default implementation raises the <see cref="Deactivated"/> event and calls the legacy
- /// <see cref="OnDeactivate"/> method for backward compatibility.
- /// </remarks>
- protected virtual void OnDeactivated (IRunnable? activated)
- {
- RaiseDeactivatedEvent (activated);
- // For backward compatibility, call legacy OnDeactivate if activated is a Toplevel
- if (activated is Toplevel tl)
- {
- OnDeactivate (tl);
- }
- else
- {
- // If not a Toplevel, still raise the legacy Deactivate event with null
- Deactivate?.Invoke (this, new ToplevelEventArgs (null));
- }
- }
- #endregion
- #region Size / Position Management
- // TODO: Make cancelable?
- internal void OnSizeChanging (SizeChangedEventArgs size) { SizeChanging?.Invoke (this, size); }
- /// <summary>
- /// Adjusts the location and size of <paramref name="top"/> within this Toplevel. Virtual method enabling
- /// implementation of specific positions for inherited <see cref="Toplevel"/> views.
- /// </summary>
- /// <param name="top">The Toplevel to adjust.</param>
- public virtual void PositionToplevel (Toplevel? top)
- {
- if (top is null)
- {
- return;
- }
- View? superView = GetLocationEnsuringFullVisibility (
- top,
- top.Frame.X,
- top.Frame.Y,
- out int nx,
- out int ny
- //,
- // out StatusBar? sb
- );
- if (superView is null)
- {
- return;
- }
- //var layoutSubViews = false;
- var maxWidth = 0;
- if (superView.Margin is { } && superView == top.SuperView)
- {
- maxWidth -= superView.GetAdornmentsThickness ().Left + superView.GetAdornmentsThickness ().Right;
- }
- // BUGBUG: The && true is a temp hack
- if ((superView != top || top?.SuperView is { } || (top != App?.Current && top!.Modal) || (top == App?.Current && top?.SuperView is null))
- && (top!.Frame.X + top.Frame.Width > maxWidth || ny > top.Frame.Y))
- {
- if (top?.X is null or PosAbsolute && top?.Frame.X != nx)
- {
- top!.X = nx;
- //layoutSubViews = true;
- }
- if (top?.Y is null or PosAbsolute && top?.Frame.Y != ny)
- {
- top!.Y = ny;
- //layoutSubViews = true;
- }
- }
- //if (superView.IsLayoutNeeded () || layoutSubViews)
- //{
- // superView.LayoutSubViews ();
- //}
- //if (IsLayoutNeeded ())
- //{
- // LayoutSubViews ();
- //}
- }
- /// <summary>Invoked when the terminal has been resized. The new <see cref="Size"/> of the terminal is provided.</summary>
- public event EventHandler<SizeChangedEventArgs>? SizeChanging;
- #endregion
- }
- /// <summary>
- /// Implements the <see cref="IEqualityComparer{T}"/> for comparing two <see cref="Toplevel"/>s used by
- /// <see cref="StackExtensions"/>.
- /// </summary>
- public class ToplevelEqualityComparer : IEqualityComparer<Toplevel>
- {
- /// <summary>Determines whether the specified objects are equal.</summary>
- /// <param name="x">The first object of type <see cref="Toplevel"/> to compare.</param>
- /// <param name="y">The second object of type <see cref="Toplevel"/> to compare.</param>
- /// <returns><see langword="true"/> if the specified objects are equal; otherwise, <see langword="false"/>.</returns>
- public bool Equals (Toplevel? x, Toplevel? y)
- {
- if (y is null && x is null)
- {
- return true;
- }
- if (x is null || y is null)
- {
- return false;
- }
- if (x.Id == y.Id)
- {
- return true;
- }
- return false;
- }
- /// <summary>Returns a hash code for the specified object.</summary>
- /// <param name="obj">The <see cref="Toplevel"/> for which a hash code is to be returned.</param>
- /// <returns>A hash code for the specified object.</returns>
- /// <exception cref="ArgumentNullException">
- /// The type of <paramref name="obj"/> is a reference type and
- /// <paramref name="obj"/> is <see langword="null"/>.
- /// </exception>
- public int GetHashCode (Toplevel obj)
- {
- if (obj is null)
- {
- throw new ArgumentNullException ();
- }
- var hCode = 0;
- if (int.TryParse (obj.Id, out int result))
- {
- hCode = result;
- }
- return hCode.GetHashCode ();
- }
- }
|