Dialog.cs 11 KB

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