Wizard.cs 20 KB

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