Wizard.cs 20 KB

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