Wizard.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. using Terminal.Gui.Resources;
  2. namespace Terminal.Gui;
  3. /// <summary>
  4. /// Provides navigation and a user interface (UI) to collect related data across multiple steps. Each step (
  5. /// <see cref="WizardStep"/>) can host arbitrary <see cref="View"/>s, much like a <see cref="Dialog"/>. Each step also
  6. /// has a pane for help text. Along the bottom of the Wizard view are customizable buttons enabling the user to
  7. /// navigate forward and backward through the Wizard.
  8. /// </summary>
  9. /// <remarks>
  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. /// </remarks>
  14. /// <example>
  15. /// <code>
  16. /// using Terminal.Gui;
  17. /// using System.Text;
  18. ///
  19. /// Application.Init();
  20. ///
  21. /// var wizard = new Wizard ($"Setup Wizard");
  22. ///
  23. /// // Add 1st step
  24. /// var firstStep = new WizardStep ("End User License Agreement");
  25. /// wizard.AddStep(firstStep);
  26. /// firstStep.NextButtonText = "Accept!";
  27. /// firstStep.HelpText = "This is the End User License Agreement.";
  28. ///
  29. /// // Add 2nd step
  30. /// var secondStep = new WizardStep ("Second Step");
  31. /// wizard.AddStep(secondStep);
  32. /// secondStep.HelpText = "This is the help text for the Second Step.";
  33. /// var lbl = new Label () { Text = "Name:" };
  34. /// secondStep.Add(lbl);
  35. ///
  36. /// var name = new TextField { X = Pos.Right (lbl) + 1, Width = Dim.Fill () - 1 };
  37. /// secondStep.Add(name);
  38. ///
  39. /// wizard.Finished += (args) =>
  40. /// {
  41. /// MessageBox.Query("Wizard", $"Finished. The Name entered is '{name.Text}'", "Ok");
  42. /// Application.RequestStop();
  43. /// };
  44. ///
  45. /// Application.Top.Add (wizard);
  46. /// Application.Run ();
  47. /// Application.Shutdown ();
  48. /// </code>
  49. /// </example>
  50. public class Wizard : Dialog
  51. {
  52. private readonly LinkedList<WizardStep> _steps = new ();
  53. private WizardStep _currentStep;
  54. private bool _finishedPressed;
  55. ///// <summary>
  56. ///// The title of the Wizard, shown at the top of the Wizard with " - currentStep.Title" appended.
  57. ///// </summary>
  58. ///// <remarks>
  59. ///// The Title is only displayed when the <see cref="Wizard"/> <see cref="Wizard.Modal"/> is set to <c>false</c>.
  60. ///// </remarks>
  61. //public new string Title {
  62. // get {
  63. // // The base (Dialog) Title holds the full title ("Wizard Title - Step Title")
  64. // return base.Title;
  65. // }
  66. // set {
  67. // wizardTitle = value;
  68. // base.Title = $"{wizardTitle}{(steps.Count > 0 && currentStep is { } ? " - " + currentStep.Title : string.Empty)}";
  69. // }
  70. //}
  71. private string _wizardTitle = string.Empty;
  72. /// <summary>
  73. /// Initializes a new instance of the <see cref="Wizard"/> class using <see cref="LayoutStyle.Computed"/>
  74. /// positioning.
  75. /// </summary>
  76. /// <remarks>
  77. /// The Wizard will be vertically and horizontally centered in the container. After initialization use <c>X</c>,
  78. /// <c>Y</c>, <c>Width</c>, and <c>Height</c> change size and position.
  79. /// </remarks>
  80. public Wizard ()
  81. {
  82. // Using Justify causes the Back and Next buttons to be hard justified against
  83. // the left and right edge
  84. ButtonAlignment = Alignment.Justified;
  85. BorderStyle = LineStyle.Double;
  86. //// Add a horiz separator
  87. var separator = new LineView (Orientation.Horizontal) { Y = Pos.AnchorEnd (2) };
  88. Add (separator);
  89. // BUGBUG: Space is to work around https://github.com/gui-cs/Terminal.Gui/issues/1812
  90. BackButton = new () { Text = Strings.wzBack };
  91. AddButton (BackButton);
  92. NextFinishButton = new () { Text = Strings.wzFinish };
  93. NextFinishButton.IsDefault = true;
  94. AddButton (NextFinishButton);
  95. BackButton.Accept += BackBtn_Clicked;
  96. NextFinishButton.Accept += NextfinishBtn_Clicked;
  97. Loaded += Wizard_Loaded;
  98. Closing += Wizard_Closing;
  99. TitleChanged += Wizard_TitleChanged;
  100. if (Modal)
  101. {
  102. KeyBindings.Clear (Command.QuitToplevel);
  103. KeyBindings.Add (Key.Esc, Command.QuitToplevel);
  104. }
  105. SetNeedsLayout ();
  106. }
  107. /// <summary>
  108. /// If the <see cref="CurrentStep"/> is not the first step in the wizard, this button causes the
  109. /// <see cref="MovingBack"/> event to be fired and the wizard moves to the previous step.
  110. /// </summary>
  111. /// <remarks>Use the <see cref="MovingBack"></see> event to be notified when the user attempts to go back.</remarks>
  112. public Button BackButton { get; }
  113. /// <summary>Gets or sets the currently active <see cref="WizardStep"/>.</summary>
  114. public WizardStep CurrentStep
  115. {
  116. get => _currentStep;
  117. set => GoToStep (value);
  118. }
  119. /// <summary>
  120. /// Determines whether the <see cref="Wizard"/> is displayed as modal pop-up or not. The default is
  121. /// <see langword="true"/>. The Wizard will be shown with a frame and title and will behave like any
  122. /// <see cref="Toplevel"/> window. If set to <c>false</c> the Wizard will have no frame and will behave like any
  123. /// embedded <see cref="View"/>. To use Wizard as an embedded View
  124. /// <list type="number">
  125. /// <item>
  126. /// <description>Set <see cref="Modal"/> to <c>false</c>.</description>
  127. /// </item>
  128. /// <item>
  129. /// <description>Add the Wizard to a containing view with <see cref="View.Add(View)"/>.</description>
  130. /// </item>
  131. /// </list>
  132. /// If a non-Modal Wizard is added to the application after <see cref="Application.Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/> has
  133. /// been called the first step must be explicitly set by setting <see cref="CurrentStep"/> to
  134. /// <see cref="GetNextStep()"/>:
  135. /// <code>
  136. /// wizard.CurrentStep = wizard.GetNextStep();
  137. /// </code>
  138. /// </summary>
  139. public new bool Modal
  140. {
  141. get => base.Modal;
  142. set
  143. {
  144. base.Modal = value;
  145. foreach (WizardStep step in _steps)
  146. {
  147. SizeStep (step);
  148. }
  149. if (base.Modal)
  150. {
  151. ColorScheme = Colors.ColorSchemes ["Dialog"];
  152. BorderStyle = LineStyle.Rounded;
  153. }
  154. else
  155. {
  156. if (SuperView is { })
  157. {
  158. ColorScheme = SuperView.ColorScheme;
  159. }
  160. else
  161. {
  162. ColorScheme = Colors.ColorSchemes ["Base"];
  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 pressin 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 wizad 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. public void GoBack ()
  290. {
  291. WizardStep previous = GetPreviousStep ();
  292. if (previous is { })
  293. {
  294. GoToStep (previous);
  295. }
  296. }
  297. /// <summary>
  298. /// Causes the wizad to move to the next enabled step (or last step if <see cref="CurrentStep"/> is not set). If
  299. /// there is no previous step, does nothing.
  300. /// </summary>
  301. public void GoNext ()
  302. {
  303. WizardStep nextStep = GetNextStep ();
  304. if (nextStep is { })
  305. {
  306. GoToStep (nextStep);
  307. }
  308. }
  309. /// <summary>Changes to the specified <see cref="WizardStep"/>.</summary>
  310. /// <param name="newStep">The step to go to.</param>
  311. /// <returns>True if the transition to the step succeeded. 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 { } && !newStep.Enabled))
  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 to the nav buttons
  328. if (BackButton.HasFocus)
  329. {
  330. BackButton.SetFocus ();
  331. }
  332. else
  333. {
  334. NextFinishButton.SetFocus ();
  335. }
  336. if (OnStepChanged (oldStep, _currentStep))
  337. {
  338. // For correctness we do this, but it's meaningless because there's nothing to cancel
  339. return false;
  340. }
  341. return true;
  342. }
  343. /// <summary>
  344. /// Raised when the Back button in the <see cref="Wizard"/> is clicked. The Back button is always the first button
  345. /// in the array of Buttons passed to the <see cref="Wizard"/> constructor, if any.
  346. /// </summary>
  347. public event EventHandler<WizardButtonEventArgs> MovingBack;
  348. /// <summary>
  349. /// Raised when the Next/Finish button in the <see cref="Wizard"/> is clicked (or the user presses Enter). The
  350. /// Next/Finish button is always the last button in the array of Buttons passed to the <see cref="Wizard"/>
  351. /// constructor, if any. This event is only raised if the <see cref="CurrentStep"/> is the last Step in the Wizard flow
  352. /// (otherwise the <see cref="Finished"/> event is raised).
  353. /// </summary>
  354. public event EventHandler<WizardButtonEventArgs> MovingNext;
  355. /// <summary>
  356. /// <see cref="Wizard"/> is derived from <see cref="Dialog"/> and Dialog causes <c>Esc</c> to call
  357. /// <see cref="Application.RequestStop(Toplevel)"/>, closing the Dialog. Wizard overrides
  358. /// <see cref="OnProcessKeyDown"/> to instead fire the <see cref="Cancelled"/> event when Wizard is being used as a
  359. /// non-modal (see <see cref="Wizard.Modal"/>.
  360. /// </summary>
  361. /// <param name="key"></param>
  362. /// <returns></returns>
  363. public override bool OnProcessKeyDown (Key key)
  364. {
  365. //// BUGBUG: Why is this not handled by a key binding???
  366. if (!Modal)
  367. {
  368. if (key == Key.Esc)
  369. {
  370. var args = new WizardButtonEventArgs ();
  371. Cancelled?.Invoke (this, args);
  372. return false;
  373. }
  374. }
  375. return false;
  376. }
  377. /// <summary>
  378. /// Called when the <see cref="Wizard"/> has completed transition to a new <see cref="WizardStep"/>. Fires the
  379. /// <see cref="StepChanged"/> event.
  380. /// </summary>
  381. /// <param name="oldStep">The step the Wizard changed from</param>
  382. /// <param name="newStep">The step the Wizard has changed to</param>
  383. /// <returns>True if the change is to be cancelled.</returns>
  384. public virtual bool OnStepChanged (WizardStep oldStep, WizardStep newStep)
  385. {
  386. var args = new StepChangeEventArgs (oldStep, newStep);
  387. StepChanged?.Invoke (this, args);
  388. return args.Cancel;
  389. }
  390. /// <summary>
  391. /// Called when the <see cref="Wizard"/> is about to transition to another <see cref="WizardStep"/>. Fires the
  392. /// <see cref="StepChanging"/> event.
  393. /// </summary>
  394. /// <param name="oldStep">The step the Wizard is about to change from</param>
  395. /// <param name="newStep">The step the Wizard is about to change to</param>
  396. /// <returns>True if the change is to be cancelled.</returns>
  397. public virtual bool OnStepChanging (WizardStep oldStep, WizardStep newStep)
  398. {
  399. var args = new StepChangeEventArgs (oldStep, newStep);
  400. StepChanging?.Invoke (this, args);
  401. return args.Cancel;
  402. }
  403. /// <summary>This event is raised after the <see cref="Wizard"/> has changed the <see cref="CurrentStep"/>.</summary>
  404. public event EventHandler<StepChangeEventArgs> StepChanged;
  405. /// <summary>
  406. /// This event is raised when the current <see cref="CurrentStep"/>) is about to change. Use
  407. /// <see cref="StepChangeEventArgs.Cancel"/> to abort the transition.
  408. /// </summary>
  409. public event EventHandler<StepChangeEventArgs> StepChanging;
  410. private void BackBtn_Clicked (object sender, EventArgs e)
  411. {
  412. var args = new WizardButtonEventArgs ();
  413. MovingBack?.Invoke (this, args);
  414. if (!args.Cancel)
  415. {
  416. GoBack ();
  417. }
  418. }
  419. private void NextfinishBtn_Clicked (object sender, EventArgs e)
  420. {
  421. if (CurrentStep == GetLastStep ())
  422. {
  423. var args = new WizardButtonEventArgs ();
  424. Finished?.Invoke (this, args);
  425. if (!args.Cancel)
  426. {
  427. _finishedPressed = true;
  428. if (IsCurrentTop)
  429. {
  430. Application.RequestStop (this);
  431. }
  432. // Wizard was created as a non-modal (just added to another View).
  433. // Do nothing
  434. }
  435. }
  436. else
  437. {
  438. var args = new WizardButtonEventArgs ();
  439. MovingNext?.Invoke (this, args);
  440. if (!args.Cancel)
  441. {
  442. GoNext ();
  443. }
  444. }
  445. }
  446. private void SizeStep (WizardStep step)
  447. {
  448. if (Modal)
  449. {
  450. // If we're modal, then we expand the WizardStep so that the top and side
  451. // borders and not visible. The bottom border is the separator above the buttons.
  452. step.X = step.Y = 0;
  453. step.Height = Dim.Fill (2); // for button frame
  454. step.Width = Dim.Fill ();
  455. }
  456. else
  457. {
  458. // If we're not a modal, then we show the border around the WizardStep
  459. step.X = step.Y = 0;
  460. step.Height = Dim.Fill (1); // for button frame
  461. step.Width = Dim.Fill ();
  462. }
  463. }
  464. private void UpdateButtonsAndTitle ()
  465. {
  466. if (CurrentStep is null)
  467. {
  468. return;
  469. }
  470. Title = $"{_wizardTitle}{(_steps.Count > 0 ? " - " + CurrentStep.Title : string.Empty)}";
  471. // Configure the Back button
  472. BackButton.Text = CurrentStep.BackButtonText != string.Empty
  473. ? CurrentStep.BackButtonText
  474. : Strings.wzBack; // "_Back";
  475. BackButton.Visible = CurrentStep != GetFirstStep ();
  476. // Configure the Next/Finished button
  477. if (CurrentStep == GetLastStep ())
  478. {
  479. NextFinishButton.Text = CurrentStep.NextButtonText != string.Empty
  480. ? CurrentStep.NextButtonText
  481. : Strings.wzFinish; // "Fi_nish";
  482. }
  483. else
  484. {
  485. NextFinishButton.Text = CurrentStep.NextButtonText != string.Empty
  486. ? CurrentStep.NextButtonText
  487. : Strings.wzNext; // "_Next...";
  488. }
  489. SizeStep (CurrentStep);
  490. SetNeedsLayout ();
  491. LayoutSubviews ();
  492. Draw ();
  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, StateEventArgs<string> e)
  508. {
  509. if (string.IsNullOrEmpty (_wizardTitle))
  510. {
  511. _wizardTitle = e.NewValue;
  512. }
  513. }
  514. }