Dialog.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. namespace Terminal.Gui.Views;
  2. /// <summary>
  3. /// A <see cref="Toplevel.Modal"/> <see cref="Window"/>. Supports a simple API for adding <see cref="Button"/>s
  4. /// across the bottom. By default, the <see cref="Dialog"/> is centered and used the <see cref="Schemes.Dialog"/>
  5. /// scheme.
  6. /// </summary>
  7. /// <remarks>
  8. /// <para>
  9. /// To run the <see cref="Dialog"/> modally, create the <see cref="Dialog"/>, and pass it to
  10. /// <see cref="IApplication.Run(Toplevel, Func{Exception, bool})"/>. This will execute the dialog until
  11. /// it terminates via the <see cref="Application.QuitKey"/> (`Esc` by default),
  12. /// or when one of the views or buttons added to the dialog calls
  13. /// <see cref="Application.RequestStop"/>.
  14. /// </para>
  15. /// <para>
  16. /// <b>Phase 2:</b> <see cref="Dialog"/> now implements <see cref="IRunnable{TResult}"/> with
  17. /// <c>int?</c> as the result type, returning the index of the clicked button. The <see cref="Result"/>
  18. /// property replaces the need for manual result tracking. A result of <see langword="null"/> indicates
  19. /// the dialog was canceled (ESC pressed, window closed without clicking a button).
  20. /// </para>
  21. /// </remarks>
  22. public class Dialog : Window, IRunnable<int?>
  23. {
  24. /// <summary>
  25. /// Initializes a new instance of the <see cref="Dialog"/> class with no <see cref="Button"/>s.
  26. /// </summary>
  27. /// <remarks>
  28. /// By default, <see cref="View.X"/>, <see cref="View.Y"/>, <see cref="View.Width"/>, and <see cref="View.Height"/> are
  29. /// set
  30. /// such that the <see cref="Dialog"/> will be centered in, and no larger than 90% of <see cref="IApplication.TopRunnable"/>, if
  31. /// there is one. Otherwise,
  32. /// it will be bound by the screen dimensions.
  33. /// </remarks>
  34. public Dialog ()
  35. {
  36. Arrangement = ViewArrangement.Movable | ViewArrangement.Overlapped;
  37. base.ShadowStyle = DefaultShadow;
  38. BorderStyle = DefaultBorderStyle;
  39. X = Pos.Center ();
  40. Y = Pos.Center ();
  41. Width = Dim.Auto (DimAutoStyle.Auto, Dim.Percent (DefaultMinimumWidth), Dim.Percent (90));
  42. Height = Dim.Auto (DimAutoStyle.Auto, Dim.Percent (DefaultMinimumHeight), Dim.Percent (90));
  43. SchemeName = SchemeManager.SchemesToSchemeName (Schemes.Dialog);
  44. Modal = true;
  45. ButtonAlignment = DefaultButtonAlignment;
  46. ButtonAlignmentModes = DefaultButtonAlignmentModes;
  47. }
  48. private readonly List<Button> _buttons = [];
  49. private bool _canceled;
  50. /// <summary>
  51. /// Adds a <see cref="Button"/> to the <see cref="Dialog"/>, its layout will be controlled by the
  52. /// <see cref="Dialog"/>
  53. /// </summary>
  54. /// <param name="button">Button to add.</param>
  55. public void AddButton (Button button)
  56. {
  57. // Use a distinct GroupId so users can use Pos.Align for other views in the Dialog
  58. button.X = Pos.Align (ButtonAlignment, ButtonAlignmentModes, GetHashCode ());
  59. button.Y = Pos.AnchorEnd ();
  60. _buttons.Add (button);
  61. Add (button);
  62. }
  63. // TODO: Update button.X = Pos.Justify when alignment changes
  64. /// <summary>Determines how the <see cref="Dialog"/> <see cref="Button"/>s are aligned along the bottom of the dialog.</summary>
  65. public Alignment ButtonAlignment { get; set; }
  66. /// <summary>
  67. /// Gets or sets the alignment modes for the dialog's buttons.
  68. /// </summary>
  69. public AlignmentModes ButtonAlignmentModes { get; set; }
  70. /// <summary>Optional buttons to lay out at the bottom of the dialog.</summary>
  71. public Button [] Buttons
  72. {
  73. get => _buttons.ToArray ();
  74. init
  75. {
  76. foreach (Button b in value)
  77. {
  78. AddButton (b);
  79. }
  80. }
  81. }
  82. /// <summary>Gets a value indicating whether the <see cref="Dialog"/> was canceled.</summary>
  83. /// <remarks>
  84. /// <para>The default value is <see langword="true"/>.</para>
  85. /// <para>
  86. /// <b>Deprecated:</b> Use <see cref="Result"/> instead. This property is maintained for backward
  87. /// compatibility. A <see langword="null"/> <see cref="Result"/> indicates the dialog was canceled.
  88. /// </para>
  89. /// </remarks>
  90. public bool Canceled
  91. {
  92. get { return _canceled; }
  93. set
  94. {
  95. #if DEBUG_IDISPOSABLE
  96. if (EnableDebugIDisposableAsserts && WasDisposed)
  97. {
  98. throw new ObjectDisposedException (GetType ().FullName);
  99. }
  100. #endif
  101. _canceled = value;
  102. }
  103. }
  104. /// <summary>
  105. /// Gets or sets the result data extracted when the dialog was accepted, or <see langword="null"/> if not accepted.
  106. /// </summary>
  107. /// <remarks>
  108. /// <para>
  109. /// Returns the zero-based index of the button that was clicked, or <see langword="null"/> if the
  110. /// dialog was canceled (ESC pressed, window closed without clicking a button).
  111. /// </para>
  112. /// <para>
  113. /// This property is automatically set in <see cref="OnIsRunningChanging"/> when the dialog is
  114. /// closing. The result is extracted by finding which button has focus when the dialog stops.
  115. /// </para>
  116. /// </remarks>
  117. public int? Result { get; set; }
  118. /// <summary>
  119. /// Defines the default border styling for <see cref="Dialog"/>. Can be configured via
  120. /// <see cref="ConfigurationManager"/>.
  121. /// </summary>
  122. [ConfigurationProperty (Scope = typeof (ThemeScope))]
  123. public new static LineStyle DefaultBorderStyle { get; set; } = LineStyle.Heavy;
  124. /// <summary>The default <see cref="Alignment"/> for <see cref="Dialog"/>.</summary>
  125. /// <remarks>This property can be set in a Theme.</remarks>
  126. [ConfigurationProperty (Scope = typeof (ThemeScope))]
  127. public static Alignment DefaultButtonAlignment { get; set; } = Alignment.End;
  128. /// <summary>The default <see cref="AlignmentModes"/> for <see cref="Dialog"/>.</summary>
  129. /// <remarks>This property can be set in a Theme.</remarks>
  130. [ConfigurationProperty (Scope = typeof (ThemeScope))]
  131. public static AlignmentModes DefaultButtonAlignmentModes { get; set; } = AlignmentModes.StartToEnd | AlignmentModes.AddSpaceBetweenItems;
  132. /// <summary>
  133. /// Defines the default minimum Dialog height, as a percentage of the container width. Can be configured via
  134. /// <see cref="ConfigurationManager"/>.
  135. /// </summary>
  136. [ConfigurationProperty (Scope = typeof (ThemeScope))]
  137. public static int DefaultMinimumHeight { get; set; } = 80;
  138. /// <summary>
  139. /// Defines the default minimum Dialog width, as a percentage of the container width. Can be configured via
  140. /// <see cref="ConfigurationManager"/>.
  141. /// </summary>
  142. [ConfigurationProperty (Scope = typeof (ThemeScope))]
  143. public static int DefaultMinimumWidth { get; set; } = 80;
  144. /// <summary>
  145. /// Gets or sets whether all <see cref="Window"/>s are shown with a shadow effect by default.
  146. /// </summary>
  147. [ConfigurationProperty (Scope = typeof (ThemeScope))]
  148. public new static ShadowStyle DefaultShadow { get; set; } = ShadowStyle.Transparent;
  149. // Dialogs are Modal and Focus is indicated by their Border. The following code ensures the
  150. // Text of the dialog (e.g. for a MessageBox) is always drawn using the Normal Attribute.
  151. private bool _drawingText;
  152. /// <inheritdoc/>
  153. protected override bool OnDrawingText ()
  154. {
  155. _drawingText = true;
  156. return false;
  157. }
  158. /// <inheritdoc/>
  159. protected override void OnDrewText ()
  160. {
  161. _drawingText = false;
  162. }
  163. /// <inheritdoc />
  164. protected override bool OnGettingAttributeForRole (in VisualRole role, ref Attribute currentAttribute)
  165. {
  166. if (_drawingText && role is VisualRole.Focus && Border?.Thickness != Thickness.Empty)
  167. {
  168. currentAttribute = GetScheme ().Normal;
  169. return true;
  170. }
  171. return false;
  172. }
  173. #region IRunnable<int> Implementation
  174. /// <summary>
  175. /// Called when the dialog is about to stop running. Extracts the button result before the dialog is removed
  176. /// from the runnable stack.
  177. /// </summary>
  178. /// <param name="oldIsRunning">The current value of IsRunning.</param>
  179. /// <param name="newIsRunning">The new value of IsRunning (true = starting, false = stopping).</param>
  180. /// <returns><see langword="true"/> to cancel; <see langword="false"/> to proceed.</returns>
  181. /// <remarks>
  182. /// This method is called by the IRunnable infrastructure when the dialog is stopping. It extracts
  183. /// which button was clicked (if any) before views are disposed.
  184. /// </remarks>
  185. protected virtual bool OnIsRunningChanging (bool oldIsRunning, bool newIsRunning)
  186. {
  187. if (!newIsRunning && oldIsRunning) // Stopping
  188. {
  189. // Extract result BEFORE disposal - find which button has focus or was last clicked
  190. Result = null; // Default: canceled (null = no button clicked)
  191. for (var i = 0; i < _buttons.Count; i++)
  192. {
  193. if (_buttons [i].HasFocus)
  194. {
  195. Result = i;
  196. _canceled = false;
  197. break;
  198. }
  199. }
  200. // If no button has focus, check if any button was the last focused view
  201. if (Result is null && MostFocused is Button btn && _buttons.Contains (btn))
  202. {
  203. Result = _buttons.IndexOf (btn);
  204. _canceled = false;
  205. }
  206. // Update legacy Canceled property for backward compatibility
  207. if (Result is null)
  208. {
  209. _canceled = true;
  210. }
  211. }
  212. else if (newIsRunning) // Starting
  213. {
  214. // Clear result when starting
  215. Result = null;
  216. _canceled = true; // Default to canceled until a button is clicked
  217. }
  218. // Call base implementation (Toplevel.IRunnable.RaiseIsRunningChanging)
  219. return ((IRunnable)this).RaiseIsRunningChanging (oldIsRunning, newIsRunning);
  220. }
  221. // Explicitly implement IRunnable<int> to override the behavior from Toplevel's IRunnable
  222. bool IRunnable.RaiseIsRunningChanging (bool oldIsRunning, bool newIsRunning)
  223. {
  224. // Call our virtual method so subclasses can override
  225. return OnIsRunningChanging (oldIsRunning, newIsRunning);
  226. }
  227. #endregion
  228. }