Wizard.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. namespace Terminal.Gui.Views;
  2. /// <summary>
  3. /// Provides navigation and a user interface (UI) to collect related data across multiple steps. Each step (
  4. /// <see cref="WizardStep"/>) can host arbitrary <see cref="View"/>s, much like a <see cref="Dialog"/>. Each step also
  5. /// has a pane for help text. Along the bottom of the Wizard view are customizable buttons enabling the user to
  6. /// navigate forward and backward through the Wizard.
  7. /// </summary>
  8. /// <remarks>
  9. /// <para>
  10. /// The Wizard can be displayed either as a modal (pop-up) <see cref="Window"/> (like <see cref="Dialog"/>) or as
  11. /// an embedded <see cref="View"/>. By default, <see cref="Wizard.Modal"/> is <c>true</c>. In this case launch the
  12. /// Wizard with <c>Application.Run(wizard)</c>. See <see cref="Wizard.Modal"/> for more details.
  13. /// </para>
  14. /// <para>
  15. /// <b>Phase 2:</b> Since <see cref="Wizard"/> inherits from <see cref="Dialog"/>, which implements
  16. /// <see cref="IRunnable{TResult}"/> with <c>int?</c> result type, the wizard automatically provides result
  17. /// tracking through <see cref="Dialog.Result"/>. Use the <see cref="WasFinished"/> property to check if the
  18. /// wizard was completed or canceled.
  19. /// </para>
  20. /// </remarks>
  21. /// <example>
  22. /// <code>
  23. /// using Terminal.Gui;
  24. /// using System.Text;
  25. ///
  26. /// Application.Init();
  27. ///
  28. /// var wizard = new Wizard ($"Setup Wizard");
  29. ///
  30. /// // Add 1st step
  31. /// var firstStep = new WizardStep ("End User License Agreement");
  32. /// wizard.AddStep(firstStep);
  33. /// firstStep.NextButtonText = "Accept!";
  34. /// firstStep.HelpText = "This is the End User License Agreement.";
  35. ///
  36. /// // Add 2nd step
  37. /// var secondStep = new WizardStep ("Second Step");
  38. /// wizard.AddStep(secondStep);
  39. /// secondStep.HelpText = "This is the help text for the Second Step.";
  40. /// var lbl = new Label () { Text = "Name:" };
  41. /// secondStep.Add(lbl);
  42. ///
  43. /// var name = new TextField { X = Pos.Right (lbl) + 1, Width = Dim.Fill () - 1 };
  44. /// secondStep.Add(name);
  45. ///
  46. /// wizard.Finished += (args) =>
  47. /// {
  48. /// MessageBox.Query("Wizard", $"Finished. The Name entered is '{name.Text}'", "Ok");
  49. /// Application.RequestStop();
  50. /// };
  51. ///
  52. /// Application.TopRunnable.Add (wizard);
  53. /// Application.Run ();
  54. /// Application.Shutdown ();
  55. /// </code>
  56. /// </example>
  57. public class Wizard : Dialog
  58. {
  59. private readonly LinkedList<WizardStep> _steps = new ();
  60. private WizardStep? _currentStep;
  61. private bool _finishedPressed;
  62. private string _wizardTitle = string.Empty;
  63. /// <summary>
  64. /// Initializes a new instance of the <see cref="Wizard"/> class.
  65. /// </summary>
  66. /// <remarks>
  67. /// The Wizard will be vertically and horizontally centered in the container. After initialization use <c>X</c>,
  68. /// <c>Y</c>, <c>Width</c>, and <c>Height</c> change size and position.
  69. /// </remarks>
  70. public Wizard ()
  71. {
  72. // TODO: LastEndRestStart will enable a "Quit" button to always appear at the far left
  73. ButtonAlignment = Alignment.Start;
  74. ButtonAlignmentModes |= AlignmentModes.IgnoreFirstOrLast;
  75. BorderStyle = LineStyle.Double;
  76. BackButton = new () { Text = Strings.wzBack };
  77. NextFinishButton = new ()
  78. {
  79. Text = Strings.wzFinish,
  80. IsDefault = true
  81. };
  82. // Add a horiz separator
  83. var separator = new Line { Orientation = Orientation.Horizontal, X = -1, Y = Pos.Top (BackButton) - 1, Length = Dim.Fill (-1) };
  84. base.Add (separator);
  85. AddButton (BackButton);
  86. AddButton (NextFinishButton);
  87. BackButton.Accepting += BackBtn_Accepting;
  88. NextFinishButton.Accepting += NextFinishBtn_Accepting;
  89. Loaded += Wizard_Loaded;
  90. Closing += Wizard_Closing;
  91. TitleChanged += Wizard_TitleChanged;
  92. SetNeedsLayout ();
  93. }
  94. /// <summary>
  95. /// If the <see cref="CurrentStep"/> is not the first step in the wizard, this button causes the
  96. /// <see cref="MovingBack"/> event to be fired and the wizard moves to the previous step.
  97. /// </summary>
  98. /// <remarks>Use the <see cref="MovingBack"></see> event to be notified when the user attempts to go back.</remarks>
  99. public Button BackButton { get; }
  100. /// <summary>
  101. /// Gets whether the wizard was completed (the Finish button was pressed and <see cref="Finished"/> event fired).
  102. /// </summary>
  103. /// <remarks>
  104. /// <para>
  105. /// This is a convenience property that checks if the wizard was successfully completed.
  106. /// Since <see cref="Wizard"/> inherits from <see cref="Dialog"/> which implements
  107. /// <see cref="IRunnable{TResult}"/> with <c>int?</c> result type, the <see cref="Dialog.Result"/>
  108. /// property contains the button index when a button is clicked.
  109. /// </para>
  110. /// <para>
  111. /// Returns <see langword="true"/> if both:
  112. /// <list type="bullet">
  113. /// <item><description><see cref="Dialog.Result"/> is not <see langword="null"/> (a button was clicked)</description></item>
  114. /// <item><description>The internal <c>_finishedPressed</c> flag is set (the Finish button was clicked and <see cref="Finished"/> event completed without cancellation)</description></item>
  115. /// </list>
  116. /// Returns <see langword="false"/> if the wizard was canceled (ESC pressed), the Back button was clicked, or the <see cref="Finished"/> event was canceled.
  117. /// </para>
  118. /// </remarks>
  119. public bool WasFinished => Result is { } && _finishedPressed;
  120. /// <summary>Gets or sets the currently active <see cref="WizardStep"/>.</summary>
  121. public WizardStep? CurrentStep
  122. {
  123. get => _currentStep;
  124. set => GoToStep (value);
  125. }
  126. /// <summary>
  127. /// Determines whether the <see cref="Wizard"/> is displayed as modal pop-up or not. The default is
  128. /// <see langword="true"/>. The Wizard will be shown with a frame and title and will behave like any
  129. /// <see cref="Toplevel"/> window. If set to <c>false</c> the Wizard will have no frame and will behave like any
  130. /// embedded <see cref="View"/>. To use Wizard as an embedded View
  131. /// <list type="number">
  132. /// <item>
  133. /// <description>Set <see cref="Modal"/> to <c>false</c>.</description>
  134. /// </item>
  135. /// <item>
  136. /// <description>Add the Wizard to a containing view with <see cref="View.Add(View)"/>.</description>
  137. /// </item>
  138. /// </list>
  139. /// If a non-Modal Wizard is added to the application after
  140. /// <see cref="IApplication.Run(Toplevel, Func{Exception, bool})"/> has
  141. /// been called the first step must be explicitly set by setting <see cref="CurrentStep"/> to
  142. /// <see cref="GetNextStep()"/>:
  143. /// <code>
  144. /// wizard.CurrentStep = wizard.GetNextStep();
  145. /// </code>
  146. /// </summary>
  147. public new bool Modal
  148. {
  149. get => base.Modal;
  150. set
  151. {
  152. base.Modal = value;
  153. foreach (WizardStep step in _steps)
  154. {
  155. SizeStep (step);
  156. }
  157. if (base.Modal)
  158. {
  159. SchemeName = "Dialog";
  160. BorderStyle = LineStyle.Rounded;
  161. }
  162. else
  163. {
  164. CanFocus = true;
  165. BorderStyle = LineStyle.None;
  166. }
  167. }
  168. }
  169. /// <summary>
  170. /// If the <see cref="CurrentStep"/> is the last step in the wizard, this button causes the <see cref="Finished"/>
  171. /// event to be fired and the wizard to close. If the step is not the last step, the <see cref="MovingNext"/> event
  172. /// will be fired and the wizard will move next step.
  173. /// </summary>
  174. /// <remarks>
  175. /// Use the <see cref="MovingNext"></see> and <see cref="Finished"></see> events to be notified when the user
  176. /// attempts go to the next step or finish the wizard.
  177. /// </remarks>
  178. public Button NextFinishButton { get; }
  179. /// <summary>
  180. /// Adds a step to the wizard. The Next and Back buttons navigate through the added steps in the order they were
  181. /// added.
  182. /// </summary>
  183. /// <param name="newStep"></param>
  184. /// <remarks>The "Next..." button of the last step added will read "Finish" (unless changed from default).</remarks>
  185. public void AddStep (WizardStep newStep)
  186. {
  187. SizeStep (newStep);
  188. newStep.EnabledChanged += (s, e) => UpdateButtonsAndTitle ();
  189. newStep.TitleChanged += (s, e) => UpdateButtonsAndTitle ();
  190. _steps.AddLast (newStep);
  191. Add (newStep);
  192. UpdateButtonsAndTitle ();
  193. }
  194. /// <summary>
  195. /// Raised when the user has cancelled the <see cref="Wizard"/> by pressing the Esc key. To prevent a modal (
  196. /// <see cref="Wizard.Modal"/> is <c>true</c>) Wizard from closing, cancel the event by setting
  197. /// <see cref="WizardButtonEventArgs.Cancel"/> to <c>true</c> before returning from the event handler.
  198. /// </summary>
  199. public event EventHandler<WizardButtonEventArgs>? Cancelled;
  200. /// <summary>
  201. /// Raised when the Next/Finish button in the <see cref="Wizard"/> is clicked. The Next/Finish button is always
  202. /// the last button in the array of Buttons passed to the <see cref="Wizard"/> constructor, if any. This event is only
  203. /// raised if the <see cref="CurrentStep"/> is the last Step in the Wizard flow (otherwise the <see cref="Finished"/>
  204. /// event is raised).
  205. /// </summary>
  206. public event EventHandler<WizardButtonEventArgs>? Finished;
  207. /// <summary>Returns the first enabled step in the Wizard</summary>
  208. /// <returns>The last enabled step</returns>
  209. public WizardStep? GetFirstStep () { return _steps.FirstOrDefault (s => s.Enabled); }
  210. /// <summary>Returns the last enabled step in the Wizard</summary>
  211. /// <returns>The last enabled step</returns>
  212. public WizardStep? GetLastStep () { return _steps.LastOrDefault (s => s.Enabled); }
  213. /// <summary>
  214. /// Returns the next enabled <see cref="WizardStep"/> after the current step. Takes into account steps which are
  215. /// disabled. If <see cref="CurrentStep"/> is <c>null</c> returns the first enabled step.
  216. /// </summary>
  217. /// <returns>
  218. /// The next step after the current step, if there is one; otherwise returns <c>null</c>, which indicates either
  219. /// there are no enabled steps or the current step is the last enabled step.
  220. /// </returns>
  221. public WizardStep? GetNextStep ()
  222. {
  223. LinkedListNode<WizardStep>? step = null;
  224. if (CurrentStep is null)
  225. {
  226. // Get first step, assume it is next
  227. step = _steps.First;
  228. }
  229. else
  230. {
  231. // Get the step after current
  232. step = _steps.Find (CurrentStep);
  233. if (step is { })
  234. {
  235. step = step.Next;
  236. }
  237. }
  238. // step now points to the potential next step
  239. while (step is { })
  240. {
  241. if (step.Value.Enabled)
  242. {
  243. return step.Value;
  244. }
  245. step = step.Next;
  246. }
  247. return null;
  248. }
  249. /// <summary>
  250. /// Returns the first enabled <see cref="WizardStep"/> before the current step. Takes into account steps which are
  251. /// disabled. If <see cref="CurrentStep"/> is <c>null</c> returns the last enabled step.
  252. /// </summary>
  253. /// <returns>
  254. /// The first step ahead of the current step, if there is one; otherwise returns <c>null</c>, which indicates
  255. /// either there are no enabled steps or the current step is the first enabled step.
  256. /// </returns>
  257. public WizardStep? GetPreviousStep ()
  258. {
  259. LinkedListNode<WizardStep>? step = null;
  260. if (CurrentStep is null)
  261. {
  262. // Get last step, assume it is previous
  263. step = _steps.Last;
  264. }
  265. else
  266. {
  267. // Get the step before current
  268. step = _steps.Find (CurrentStep);
  269. if (step is { })
  270. {
  271. step = step.Previous;
  272. }
  273. }
  274. // step now points to the potential previous step
  275. while (step is { })
  276. {
  277. if (step.Value.Enabled)
  278. {
  279. return step.Value;
  280. }
  281. step = step.Previous;
  282. }
  283. return null;
  284. }
  285. /// <summary>
  286. /// Causes the wizard to move to the previous enabled step (or first step if <see cref="CurrentStep"/> is not set).
  287. /// If there is no previous step, does nothing.
  288. /// </summary>
  289. /// <returns><see langword="true"/> if the transition to the step succeeded. <see langword="false"/> if the step was not found or the operation was cancelled.</returns>
  290. public bool GoBack ()
  291. {
  292. WizardStep? previous = GetPreviousStep ();
  293. if (previous is { })
  294. {
  295. return GoToStep (previous);
  296. }
  297. return false;
  298. }
  299. /// <summary>
  300. /// Causes the wizard to move to the next enabled step (or last step if <see cref="CurrentStep"/> is not set). If
  301. /// there is no previous step, does nothing.
  302. /// </summary>
  303. /// <returns><see langword="true"/> if the transition to the step succeeded. <see langword="false"/> if the step was not found or the operation was cancelled.</returns>
  304. public bool GoNext ()
  305. {
  306. WizardStep? nextStep = GetNextStep ();
  307. if (nextStep is { })
  308. {
  309. return GoToStep (nextStep);
  310. }
  311. return false;
  312. }
  313. /// <summary>Changes to the specified <see cref="WizardStep"/>.</summary>
  314. /// <param name="newStep">The step to go to.</param>
  315. /// <returns><see langword="true"/> if the transition to the step succeeded. <see langword="false"/> if the step was not found or the operation was cancelled.</returns>
  316. public bool GoToStep (WizardStep? newStep)
  317. {
  318. if (OnStepChanging (_currentStep, newStep) || newStep is { Enabled: false })
  319. {
  320. return false;
  321. }
  322. // Hide all but the new step
  323. foreach (WizardStep step in _steps)
  324. {
  325. step.Visible = step == newStep;
  326. step.ShowHide ();
  327. }
  328. WizardStep? oldStep = _currentStep;
  329. _currentStep = newStep;
  330. UpdateButtonsAndTitle ();
  331. // Set focus on the contentview
  332. newStep?.SubViews.ToArray () [0].SetFocus ();
  333. if (OnStepChanged (oldStep, _currentStep))
  334. {
  335. // For correctness, we do this, but it's meaningless because there's nothing to cancel
  336. return false;
  337. }
  338. return true;
  339. }
  340. /// <summary>
  341. /// Raised when the Back button in the <see cref="Wizard"/> is clicked. The Back button is always the first button
  342. /// in the array of Buttons passed to the <see cref="Wizard"/> constructor, if any.
  343. /// </summary>
  344. public event EventHandler<WizardButtonEventArgs>? MovingBack;
  345. /// <summary>
  346. /// Raised when the Next/Finish button in the <see cref="Wizard"/> is clicked (or the user presses Enter). The
  347. /// Next/Finish button is always the last button in the array of Buttons passed to the <see cref="Wizard"/>
  348. /// constructor, if any. This event is only raised if the <see cref="CurrentStep"/> is the last Step in the Wizard flow
  349. /// (otherwise the <see cref="Finished"/> event is raised).
  350. /// </summary>
  351. public event EventHandler<WizardButtonEventArgs>? MovingNext;
  352. /// <summary>
  353. /// <see cref="Wizard"/> is derived from <see cref="Dialog"/> and Dialog causes <c>Esc</c> to call
  354. /// <see cref="IApplication.RequestStop(Toplevel)"/>, closing the Dialog. Wizard overrides
  355. /// <see cref="OnKeyDownNotHandled"/> to instead fire the <see cref="Cancelled"/> event when Wizard is being used as a
  356. /// non-modal (see <see cref="Wizard.Modal"/>).
  357. /// </summary>
  358. /// <param name="key"></param>
  359. /// <returns></returns>
  360. protected override bool OnKeyDownNotHandled (Key key)
  361. {
  362. //// BUGBUG: Why is this not handled by a key binding???
  363. if (!Modal)
  364. {
  365. if (key == Key.Esc)
  366. {
  367. var args = new WizardButtonEventArgs ();
  368. Cancelled?.Invoke (this, args);
  369. return false;
  370. }
  371. }
  372. return false;
  373. }
  374. /// <summary>
  375. /// Called when the <see cref="Wizard"/> has completed transition to a new <see cref="WizardStep"/>. Fires the
  376. /// <see cref="StepChanged"/> event.
  377. /// </summary>
  378. /// <param name="oldStep">The step the Wizard changed from</param>
  379. /// <param name="newStep">The step the Wizard has changed to</param>
  380. /// <returns>True if the change is to be cancelled.</returns>
  381. public virtual bool OnStepChanged (WizardStep? oldStep, WizardStep? newStep)
  382. {
  383. var args = new StepChangeEventArgs (oldStep, newStep);
  384. StepChanged?.Invoke (this, args);
  385. return args.Cancel;
  386. }
  387. /// <summary>
  388. /// Called when the <see cref="Wizard"/> is about to transition to another <see cref="WizardStep"/>. Fires the
  389. /// <see cref="StepChanging"/> event.
  390. /// </summary>
  391. /// <param name="oldStep">The step the Wizard is about to change from</param>
  392. /// <param name="newStep">The step the Wizard is about to change to</param>
  393. /// <returns>True if the change is to be cancelled.</returns>
  394. public virtual bool OnStepChanging (WizardStep? oldStep, WizardStep? newStep)
  395. {
  396. var args = new StepChangeEventArgs (oldStep, newStep);
  397. StepChanging?.Invoke (this, args);
  398. return args.Cancel;
  399. }
  400. /// <summary>This event is raised after the <see cref="Wizard"/> has changed the <see cref="CurrentStep"/>.</summary>
  401. public event EventHandler<StepChangeEventArgs>? StepChanged;
  402. /// <summary>
  403. /// This event is raised when the current <see cref="CurrentStep"/>) is about to change. Use
  404. /// <see cref="StepChangeEventArgs.Cancel"/> to abort the transition.
  405. /// </summary>
  406. public event EventHandler<StepChangeEventArgs>? StepChanging;
  407. private void BackBtn_Accepting (object? sender, CommandEventArgs e)
  408. {
  409. var args = new WizardButtonEventArgs ();
  410. MovingBack?.Invoke (this, args);
  411. if (!args.Cancel)
  412. {
  413. e.Handled = GoBack ();
  414. }
  415. }
  416. private void NextFinishBtn_Accepting (object? sender, CommandEventArgs e)
  417. {
  418. if (CurrentStep == GetLastStep ())
  419. {
  420. var args = new WizardButtonEventArgs ();
  421. Finished?.Invoke (this, args);
  422. if (!args.Cancel)
  423. {
  424. _finishedPressed = true;
  425. if (IsCurrentTop)
  426. {
  427. (sender as View)?.App?.RequestStop (this);
  428. e.Handled = true;
  429. }
  430. // Wizard was created as a non-modal (just added to another View).
  431. // Do nothing
  432. }
  433. }
  434. else
  435. {
  436. var args = new WizardButtonEventArgs ();
  437. MovingNext?.Invoke (this, args);
  438. if (!args.Cancel)
  439. {
  440. e.Handled = GoNext ();
  441. }
  442. }
  443. }
  444. private void SizeStep (WizardStep step)
  445. {
  446. if (Modal)
  447. {
  448. // If we're modal, then we expand the WizardStep so that the top and side
  449. // borders and not visible. The bottom border is the separator above the buttons.
  450. step.X = step.Y = 0;
  451. step.Height = Dim.Fill (
  452. Dim.Func (
  453. v => IsInitialized
  454. ? SubViews.First (view => view.Y.Has<PosAnchorEnd> (out _)).Frame.Height + 1
  455. : 1)); // for button frame (+1 for lineView)
  456. step.Width = Dim.Fill ();
  457. }
  458. else
  459. {
  460. // If we're not a modal, then we show the border around the WizardStep
  461. step.X = step.Y = 0;
  462. step.Height = Dim.Fill (
  463. Dim.Func (
  464. v => IsInitialized
  465. ? SubViews.First (view => view.Y.Has<PosAnchorEnd> (out _)).Frame.Height + 1
  466. : 2)); // for button frame (+1 for lineView)
  467. step.Width = Dim.Fill ();
  468. }
  469. }
  470. private void UpdateButtonsAndTitle ()
  471. {
  472. if (CurrentStep is null)
  473. {
  474. return;
  475. }
  476. Title = $"{_wizardTitle}{(_steps.Count > 0 ? " - " + CurrentStep.Title : string.Empty)}";
  477. // Configure the Back button
  478. BackButton.Text = CurrentStep.BackButtonText != string.Empty
  479. ? CurrentStep.BackButtonText
  480. : Strings.wzBack; // "_Back";
  481. BackButton.Visible = CurrentStep != GetFirstStep ();
  482. // Configure the Next/Finished button
  483. if (CurrentStep == GetLastStep ())
  484. {
  485. NextFinishButton.Text = CurrentStep.NextButtonText != string.Empty
  486. ? CurrentStep.NextButtonText
  487. : Strings.wzFinish; // "Fi_nish";
  488. }
  489. else
  490. {
  491. NextFinishButton.Text = CurrentStep.NextButtonText != string.Empty
  492. ? CurrentStep.NextButtonText
  493. : Strings.wzNext; // "_Next...";
  494. }
  495. SizeStep (CurrentStep);
  496. SetNeedsLayout ();
  497. }
  498. private void Wizard_Closing (object? sender, ToplevelClosingEventArgs obj)
  499. {
  500. if (!_finishedPressed)
  501. {
  502. var args = new WizardButtonEventArgs ();
  503. Cancelled?.Invoke (this, args);
  504. }
  505. }
  506. private void Wizard_Loaded (object? sender, EventArgs args)
  507. {
  508. CurrentStep = GetFirstStep ();
  509. // gets the first step if CurrentStep == null
  510. }
  511. private void Wizard_TitleChanged (object? sender, EventArgs<string> e)
  512. {
  513. if (string.IsNullOrEmpty (_wizardTitle))
  514. {
  515. _wizardTitle = e.Value;
  516. }
  517. }
  518. }