Wizard.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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 <see cref="Dialog.Result"/> indicates the wizard was
  106. /// finished rather than canceled. Since <see cref="Wizard"/> inherits from <see cref="Dialog"/> which
  107. /// implements <see cref="IRunnable{TResult}"/> with <c>int?</c> result type, the <see cref="Dialog.Result"/>
  108. /// property contains the button index. The Finish button is added as the last button.
  109. /// </para>
  110. /// <para>
  111. /// Returns <see langword="true"/> if <see cref="Dialog.Result"/> is not <see langword="null"/> and equals
  112. /// the index of the Next/Finish button, <see langword="false"/> otherwise (canceled or Back button pressed).
  113. /// </para>
  114. /// </remarks>
  115. public bool WasFinished => Result is { } && _finishedPressed;
  116. /// <summary>Gets or sets the currently active <see cref="WizardStep"/>.</summary>
  117. public WizardStep? CurrentStep
  118. {
  119. get => _currentStep;
  120. set => GoToStep (value);
  121. }
  122. /// <summary>
  123. /// Determines whether the <see cref="Wizard"/> is displayed as modal pop-up or not. The default is
  124. /// <see langword="true"/>. The Wizard will be shown with a frame and title and will behave like any
  125. /// <see cref="Toplevel"/> window. If set to <c>false</c> the Wizard will have no frame and will behave like any
  126. /// embedded <see cref="View"/>. To use Wizard as an embedded View
  127. /// <list type="number">
  128. /// <item>
  129. /// <description>Set <see cref="Modal"/> to <c>false</c>.</description>
  130. /// </item>
  131. /// <item>
  132. /// <description>Add the Wizard to a containing view with <see cref="View.Add(View)"/>.</description>
  133. /// </item>
  134. /// </list>
  135. /// If a non-Modal Wizard is added to the application after
  136. /// <see cref="IApplication.Run(Toplevel, Func{Exception, bool})"/> has
  137. /// been called the first step must be explicitly set by setting <see cref="CurrentStep"/> to
  138. /// <see cref="GetNextStep()"/>:
  139. /// <code>
  140. /// wizard.CurrentStep = wizard.GetNextStep();
  141. /// </code>
  142. /// </summary>
  143. public new bool Modal
  144. {
  145. get => base.Modal;
  146. set
  147. {
  148. base.Modal = value;
  149. foreach (WizardStep step in _steps)
  150. {
  151. SizeStep (step);
  152. }
  153. if (base.Modal)
  154. {
  155. SchemeName = "Dialog";
  156. BorderStyle = LineStyle.Rounded;
  157. }
  158. else
  159. {
  160. CanFocus = true;
  161. BorderStyle = LineStyle.None;
  162. }
  163. }
  164. }
  165. /// <summary>
  166. /// If the <see cref="CurrentStep"/> is the last step in the wizard, this button causes the <see cref="Finished"/>
  167. /// event to be fired and the wizard to close. If the step is not the last step, the <see cref="MovingNext"/> event
  168. /// will be fired and the wizard will move next step.
  169. /// </summary>
  170. /// <remarks>
  171. /// Use the <see cref="MovingNext"></see> and <see cref="Finished"></see> events to be notified when the user
  172. /// attempts go to the next step or finish the wizard.
  173. /// </remarks>
  174. public Button NextFinishButton { get; }
  175. /// <summary>
  176. /// Adds a step to the wizard. The Next and Back buttons navigate through the added steps in the order they were
  177. /// added.
  178. /// </summary>
  179. /// <param name="newStep"></param>
  180. /// <remarks>The "Next..." button of the last step added will read "Finish" (unless changed from default).</remarks>
  181. public void AddStep (WizardStep newStep)
  182. {
  183. SizeStep (newStep);
  184. newStep.EnabledChanged += (s, e) => UpdateButtonsAndTitle ();
  185. newStep.TitleChanged += (s, e) => UpdateButtonsAndTitle ();
  186. _steps.AddLast (newStep);
  187. Add (newStep);
  188. UpdateButtonsAndTitle ();
  189. }
  190. /// <summary>
  191. /// Raised when the user has cancelled the <see cref="Wizard"/> by pressing the Esc key. To prevent a modal (
  192. /// <see cref="Wizard.Modal"/> is <c>true</c>) Wizard from closing, cancel the event by setting
  193. /// <see cref="WizardButtonEventArgs.Cancel"/> to <c>true</c> before returning from the event handler.
  194. /// </summary>
  195. public event EventHandler<WizardButtonEventArgs>? Cancelled;
  196. /// <summary>
  197. /// Raised when the Next/Finish button in the <see cref="Wizard"/> is clicked. The Next/Finish button is always
  198. /// the last button in the array of Buttons passed to the <see cref="Wizard"/> constructor, if any. This event is only
  199. /// raised if the <see cref="CurrentStep"/> is the last Step in the Wizard flow (otherwise the <see cref="Finished"/>
  200. /// event is raised).
  201. /// </summary>
  202. public event EventHandler<WizardButtonEventArgs>? Finished;
  203. /// <summary>Returns the first enabled step in the Wizard</summary>
  204. /// <returns>The last enabled step</returns>
  205. public WizardStep? GetFirstStep () { return _steps.FirstOrDefault (s => s.Enabled); }
  206. /// <summary>Returns the last enabled step in the Wizard</summary>
  207. /// <returns>The last enabled step</returns>
  208. public WizardStep? GetLastStep () { return _steps.LastOrDefault (s => s.Enabled); }
  209. /// <summary>
  210. /// Returns the next enabled <see cref="WizardStep"/> after the current step. Takes into account steps which are
  211. /// disabled. If <see cref="CurrentStep"/> is <c>null</c> returns the first enabled step.
  212. /// </summary>
  213. /// <returns>
  214. /// The next step after the current step, if there is one; otherwise returns <c>null</c>, which indicates either
  215. /// there are no enabled steps or the current step is the last enabled step.
  216. /// </returns>
  217. public WizardStep? GetNextStep ()
  218. {
  219. LinkedListNode<WizardStep>? step = null;
  220. if (CurrentStep is null)
  221. {
  222. // Get first step, assume it is next
  223. step = _steps.First;
  224. }
  225. else
  226. {
  227. // Get the step after current
  228. step = _steps.Find (CurrentStep);
  229. if (step is { })
  230. {
  231. step = step.Next;
  232. }
  233. }
  234. // step now points to the potential next step
  235. while (step is { })
  236. {
  237. if (step.Value.Enabled)
  238. {
  239. return step.Value;
  240. }
  241. step = step.Next;
  242. }
  243. return null;
  244. }
  245. /// <summary>
  246. /// Returns the first enabled <see cref="WizardStep"/> before the current step. Takes into account steps which are
  247. /// disabled. If <see cref="CurrentStep"/> is <c>null</c> returns the last enabled step.
  248. /// </summary>
  249. /// <returns>
  250. /// The first step ahead of the current step, if there is one; otherwise returns <c>null</c>, which indicates
  251. /// either there are no enabled steps or the current step is the first enabled step.
  252. /// </returns>
  253. public WizardStep? GetPreviousStep ()
  254. {
  255. LinkedListNode<WizardStep>? step = null;
  256. if (CurrentStep is null)
  257. {
  258. // Get last step, assume it is previous
  259. step = _steps.Last;
  260. }
  261. else
  262. {
  263. // Get the step before current
  264. step = _steps.Find (CurrentStep);
  265. if (step is { })
  266. {
  267. step = step.Previous;
  268. }
  269. }
  270. // step now points to the potential previous step
  271. while (step is { })
  272. {
  273. if (step.Value.Enabled)
  274. {
  275. return step.Value;
  276. }
  277. step = step.Previous;
  278. }
  279. return null;
  280. }
  281. /// <summary>
  282. /// Causes the wizard to move to the previous enabled step (or first step if <see cref="CurrentStep"/> is not set).
  283. /// If there is no previous step, does nothing.
  284. /// </summary>
  285. /// <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>
  286. public bool GoBack ()
  287. {
  288. WizardStep? previous = GetPreviousStep ();
  289. if (previous is { })
  290. {
  291. return GoToStep (previous);
  292. }
  293. return false;
  294. }
  295. /// <summary>
  296. /// Causes the wizard to move to the next enabled step (or last step if <see cref="CurrentStep"/> is not set). If
  297. /// there is no previous step, does nothing.
  298. /// </summary>
  299. /// <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>
  300. public bool GoNext ()
  301. {
  302. WizardStep? nextStep = GetNextStep ();
  303. if (nextStep is { })
  304. {
  305. return GoToStep (nextStep);
  306. }
  307. return false;
  308. }
  309. /// <summary>Changes to the specified <see cref="WizardStep"/>.</summary>
  310. /// <param name="newStep">The step to go to.</param>
  311. /// <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>
  312. public bool GoToStep (WizardStep? newStep)
  313. {
  314. if (OnStepChanging (_currentStep, newStep) || newStep is { Enabled: false })
  315. {
  316. return false;
  317. }
  318. // Hide all but the new step
  319. foreach (WizardStep step in _steps)
  320. {
  321. step.Visible = step == newStep;
  322. step.ShowHide ();
  323. }
  324. WizardStep? oldStep = _currentStep;
  325. _currentStep = newStep;
  326. UpdateButtonsAndTitle ();
  327. // Set focus on the contentview
  328. newStep?.SubViews.ToArray () [0].SetFocus ();
  329. if (OnStepChanged (oldStep, _currentStep))
  330. {
  331. // For correctness, we do this, but it's meaningless because there's nothing to cancel
  332. return false;
  333. }
  334. return true;
  335. }
  336. /// <summary>
  337. /// Raised when the Back button in the <see cref="Wizard"/> is clicked. The Back button is always the first button
  338. /// in the array of Buttons passed to the <see cref="Wizard"/> constructor, if any.
  339. /// </summary>
  340. public event EventHandler<WizardButtonEventArgs>? MovingBack;
  341. /// <summary>
  342. /// Raised when the Next/Finish button in the <see cref="Wizard"/> is clicked (or the user presses Enter). The
  343. /// Next/Finish button is always the last button in the array of Buttons passed to the <see cref="Wizard"/>
  344. /// constructor, if any. This event is only raised if the <see cref="CurrentStep"/> is the last Step in the Wizard flow
  345. /// (otherwise the <see cref="Finished"/> event is raised).
  346. /// </summary>
  347. public event EventHandler<WizardButtonEventArgs>? MovingNext;
  348. /// <summary>
  349. /// <see cref="Wizard"/> is derived from <see cref="Dialog"/> and Dialog causes <c>Esc</c> to call
  350. /// <see cref="IApplication.RequestStop(Toplevel)"/>, closing the Dialog. Wizard overrides
  351. /// <see cref="OnKeyDownNotHandled"/> to instead fire the <see cref="Cancelled"/> event when Wizard is being used as a
  352. /// non-modal (see <see cref="Wizard.Modal"/>).
  353. /// </summary>
  354. /// <param name="key"></param>
  355. /// <returns></returns>
  356. protected override bool OnKeyDownNotHandled (Key key)
  357. {
  358. //// BUGBUG: Why is this not handled by a key binding???
  359. if (!Modal)
  360. {
  361. if (key == Key.Esc)
  362. {
  363. var args = new WizardButtonEventArgs ();
  364. Cancelled?.Invoke (this, args);
  365. return false;
  366. }
  367. }
  368. return false;
  369. }
  370. /// <summary>
  371. /// Called when the <see cref="Wizard"/> has completed transition to a new <see cref="WizardStep"/>. Fires the
  372. /// <see cref="StepChanged"/> event.
  373. /// </summary>
  374. /// <param name="oldStep">The step the Wizard changed from</param>
  375. /// <param name="newStep">The step the Wizard has changed to</param>
  376. /// <returns>True if the change is to be cancelled.</returns>
  377. public virtual bool OnStepChanged (WizardStep? oldStep, WizardStep? newStep)
  378. {
  379. var args = new StepChangeEventArgs (oldStep, newStep);
  380. StepChanged?.Invoke (this, args);
  381. return args.Cancel;
  382. }
  383. /// <summary>
  384. /// Called when the <see cref="Wizard"/> is about to transition to another <see cref="WizardStep"/>. Fires the
  385. /// <see cref="StepChanging"/> event.
  386. /// </summary>
  387. /// <param name="oldStep">The step the Wizard is about to change from</param>
  388. /// <param name="newStep">The step the Wizard is about to change to</param>
  389. /// <returns>True if the change is to be cancelled.</returns>
  390. public virtual bool OnStepChanging (WizardStep? oldStep, WizardStep? newStep)
  391. {
  392. var args = new StepChangeEventArgs (oldStep, newStep);
  393. StepChanging?.Invoke (this, args);
  394. return args.Cancel;
  395. }
  396. /// <summary>This event is raised after the <see cref="Wizard"/> has changed the <see cref="CurrentStep"/>.</summary>
  397. public event EventHandler<StepChangeEventArgs>? StepChanged;
  398. /// <summary>
  399. /// This event is raised when the current <see cref="CurrentStep"/>) is about to change. Use
  400. /// <see cref="StepChangeEventArgs.Cancel"/> to abort the transition.
  401. /// </summary>
  402. public event EventHandler<StepChangeEventArgs>? StepChanging;
  403. private void BackBtn_Accepting (object? sender, CommandEventArgs e)
  404. {
  405. var args = new WizardButtonEventArgs ();
  406. MovingBack?.Invoke (this, args);
  407. if (!args.Cancel)
  408. {
  409. e.Handled = GoBack ();
  410. }
  411. }
  412. private void NextFinishBtn_Accepting (object? sender, CommandEventArgs e)
  413. {
  414. if (CurrentStep == GetLastStep ())
  415. {
  416. var args = new WizardButtonEventArgs ();
  417. Finished?.Invoke (this, args);
  418. if (!args.Cancel)
  419. {
  420. _finishedPressed = true;
  421. if (IsCurrentTop)
  422. {
  423. Application.RequestStop (this);
  424. e.Handled = true;
  425. }
  426. // Wizard was created as a non-modal (just added to another View).
  427. // Do nothing
  428. }
  429. }
  430. else
  431. {
  432. var args = new WizardButtonEventArgs ();
  433. MovingNext?.Invoke (this, args);
  434. if (!args.Cancel)
  435. {
  436. e.Handled = GoNext ();
  437. }
  438. }
  439. }
  440. private void SizeStep (WizardStep step)
  441. {
  442. if (Modal)
  443. {
  444. // If we're modal, then we expand the WizardStep so that the top and side
  445. // borders and not visible. The bottom border is the separator above the buttons.
  446. step.X = step.Y = 0;
  447. step.Height = Dim.Fill (
  448. Dim.Func (
  449. v => IsInitialized
  450. ? SubViews.First (view => view.Y.Has<PosAnchorEnd> (out _)).Frame.Height + 1
  451. : 1)); // for button frame (+1 for lineView)
  452. step.Width = Dim.Fill ();
  453. }
  454. else
  455. {
  456. // If we're not a modal, then we show the border around the WizardStep
  457. step.X = step.Y = 0;
  458. step.Height = Dim.Fill (
  459. Dim.Func (
  460. v => IsInitialized
  461. ? SubViews.First (view => view.Y.Has<PosAnchorEnd> (out _)).Frame.Height + 1
  462. : 2)); // for button frame (+1 for lineView)
  463. step.Width = Dim.Fill ();
  464. }
  465. }
  466. private void UpdateButtonsAndTitle ()
  467. {
  468. if (CurrentStep is null)
  469. {
  470. return;
  471. }
  472. Title = $"{_wizardTitle}{(_steps.Count > 0 ? " - " + CurrentStep.Title : string.Empty)}";
  473. // Configure the Back button
  474. BackButton.Text = CurrentStep.BackButtonText != string.Empty
  475. ? CurrentStep.BackButtonText
  476. : Strings.wzBack; // "_Back";
  477. BackButton.Visible = CurrentStep != GetFirstStep ();
  478. // Configure the Next/Finished button
  479. if (CurrentStep == GetLastStep ())
  480. {
  481. NextFinishButton.Text = CurrentStep.NextButtonText != string.Empty
  482. ? CurrentStep.NextButtonText
  483. : Strings.wzFinish; // "Fi_nish";
  484. }
  485. else
  486. {
  487. NextFinishButton.Text = CurrentStep.NextButtonText != string.Empty
  488. ? CurrentStep.NextButtonText
  489. : Strings.wzNext; // "_Next...";
  490. }
  491. SizeStep (CurrentStep);
  492. SetNeedsLayout ();
  493. }
  494. private void Wizard_Closing (object? sender, ToplevelClosingEventArgs obj)
  495. {
  496. if (!_finishedPressed)
  497. {
  498. var args = new WizardButtonEventArgs ();
  499. Cancelled?.Invoke (this, args);
  500. }
  501. }
  502. private void Wizard_Loaded (object? sender, EventArgs args)
  503. {
  504. CurrentStep = GetFirstStep ();
  505. // gets the first step if CurrentStep == null
  506. }
  507. private void Wizard_TitleChanged (object? sender, EventArgs<string> e)
  508. {
  509. if (string.IsNullOrEmpty (_wizardTitle))
  510. {
  511. _wizardTitle = e.Value;
  512. }
  513. }
  514. }