Wizard.cs 20 KB

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