Wizard.cs 18 KB

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