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