Wizard.cs 21 KB

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