Wizard.cs 17 KB

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