Buttons.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Text;
  5. using JetBrains.Annotations;
  6. using Terminal.Gui;
  7. namespace UICatalog.Scenarios;
  8. [ScenarioMetadata ("Buttons", "Demonstrates all sorts of Buttons.")]
  9. [ScenarioCategory ("Controls")]
  10. [ScenarioCategory ("Layout")]
  11. public class Buttons : Scenario
  12. {
  13. public override void Main ()
  14. {
  15. Application.Init ();
  16. Window main = new ()
  17. {
  18. Title = GetQuitKeyAndName ()
  19. };
  20. // Add a label & text field so we can demo IsDefault
  21. var editLabel = new Label { X = 0, Y = 0, TabStop = true, Text = "TextField (to demo IsDefault):" };
  22. main.Add (editLabel);
  23. // Add a TextField using Absolute layout.
  24. var edit = new TextField { X = 31, Width = 15, HotKey = Key.Y.WithAlt };
  25. main.Add (edit);
  26. // This is the default button (IsDefault = true); if user presses ENTER in the TextField
  27. // the scenario will quit
  28. var defaultButton = new Button { X = Pos.Center (), Y = Pos.AnchorEnd (), IsDefault = true, Text = "_Quit" };
  29. defaultButton.Accept += (s, e) => Application.RequestStop ();
  30. main.Add (defaultButton);
  31. var swapButton = new Button
  32. {
  33. X = 50,
  34. Width = 45,
  35. Height = 3,
  36. Text = "S_wap Default (Size = 45, 3)",
  37. ColorScheme = Colors.ColorSchemes ["Error"]
  38. };
  39. swapButton.Accept += (s, e) =>
  40. {
  41. defaultButton.IsDefault = !defaultButton.IsDefault;
  42. swapButton.IsDefault = !swapButton.IsDefault;
  43. };
  44. main.Add (swapButton);
  45. static void DoMessage (Button button, string txt)
  46. {
  47. button.Accept += (s, e) =>
  48. {
  49. string btnText = button.Text;
  50. MessageBox.Query ("Message", $"Did you click {txt}?", "Yes", "No");
  51. };
  52. }
  53. var colorButtonsLabel = new Label { X = 0, Y = Pos.Bottom (swapButton) + 1, Text = "Color Buttons: " };
  54. main.Add (colorButtonsLabel);
  55. View prev = colorButtonsLabel;
  56. foreach (KeyValuePair<string, ColorScheme> colorScheme in Colors.ColorSchemes)
  57. {
  58. var colorButton = new Button
  59. {
  60. X = Pos.Right (prev),
  61. Y = Pos.Y (colorButtonsLabel),
  62. Text = $"_{colorScheme.Key}",
  63. ColorScheme = colorScheme.Value,
  64. };
  65. DoMessage (colorButton, colorButton.Text);
  66. main.Add (colorButton);
  67. prev = colorButton;
  68. }
  69. Button button;
  70. main.Add (
  71. button = new ()
  72. {
  73. X = 2,
  74. Y = Pos.Bottom (colorButtonsLabel) + 1,
  75. Text =
  76. "A super l_öng Button that will probably expose a bug in clipping or wrapping of text. Will it?"
  77. }
  78. );
  79. DoMessage (button, button.Text);
  80. // Note the 'N' in 'Newline' will be the hotkey
  81. main.Add (
  82. button = new () { X = 2, Y = Pos.Bottom (button) + 1, Height = 2, Text = "a Newline\nin the button" }
  83. );
  84. button.Accept += (s, e) => MessageBox.Query ("Message", "Question?", "Yes", "No");
  85. var textChanger = new Button { X = 2, Y = Pos.Bottom (button) + 1, Text = "Te_xt Changer" };
  86. main.Add (textChanger);
  87. textChanger.Accept += (s, e) => textChanger.Text += "!";
  88. main.Add (
  89. button = new ()
  90. {
  91. X = Pos.Right (textChanger) + 2,
  92. Y = Pos.Y (textChanger),
  93. Text = "Lets see if this will move as \"Text Changer\" grows"
  94. }
  95. );
  96. var removeButton = new Button
  97. {
  98. X = 2, Y = Pos.Bottom (button) + 1,
  99. ColorScheme = Colors.ColorSchemes ["Error"], Text = "Remove this button"
  100. };
  101. main.Add (removeButton);
  102. // This in interesting test case because `moveBtn` and below are laid out relative to this one!
  103. removeButton.Accept += (s, e) =>
  104. {
  105. removeButton.Visible = false;
  106. };
  107. var computedFrame = new FrameView
  108. {
  109. X = 0,
  110. Y = Pos.Bottom (removeButton) + 1,
  111. Width = Dim.Percent (50),
  112. Height = 6,
  113. Title = "Computed Layout"
  114. };
  115. main.Add (computedFrame);
  116. // Demonstrates how changing the View.Frame property can move Views
  117. var moveBtn = new Button
  118. {
  119. X = 0,
  120. Y = Pos.Center () - 1,
  121. Width = 30,
  122. ColorScheme = Colors.ColorSchemes ["Error"],
  123. Text = "Move This \u263b Button v_ia Pos"
  124. };
  125. moveBtn.Accept += (s, e) =>
  126. {
  127. moveBtn.X = moveBtn.Frame.X + 5;
  128. };
  129. computedFrame.Add (moveBtn);
  130. // Demonstrates how changing the View.Frame property can SIZE Views (#583)
  131. var sizeBtn = new Button
  132. {
  133. Y = Pos.Center () + 1,
  134. X = 0,
  135. Width = 30,
  136. Text = "Grow This \u263a Button _via Pos",
  137. ColorScheme = Colors.ColorSchemes ["Error"],
  138. };
  139. sizeBtn.Accept += (s, e) =>
  140. {
  141. sizeBtn.Width = sizeBtn.Frame.Width + 5;
  142. };
  143. computedFrame.Add (sizeBtn);
  144. var absoluteFrame = new FrameView
  145. {
  146. X = Pos.Right (computedFrame),
  147. Y = Pos.Bottom (removeButton) + 1,
  148. Width = Dim.Fill (),
  149. Height = 6,
  150. Title = "Absolute Layout"
  151. };
  152. main.Add (absoluteFrame);
  153. // Demonstrates how changing the View.Frame property can move Views
  154. var moveBtnA = new Button { ColorScheme = Colors.ColorSchemes ["Error"], Text = "Move This Button via Frame" };
  155. moveBtnA.Accept += (s, e) =>
  156. {
  157. moveBtnA.Frame = new (
  158. moveBtnA.Frame.X + 5,
  159. moveBtnA.Frame.Y,
  160. moveBtnA.Frame.Width,
  161. moveBtnA.Frame.Height
  162. );
  163. };
  164. absoluteFrame.Add (moveBtnA);
  165. // Demonstrates how changing the View.Frame property can SIZE Views (#583)
  166. var sizeBtnA = new Button
  167. {
  168. Y = 2, ColorScheme = Colors.ColorSchemes ["Error"], Text = " ~  s  gui.cs   master ↑_10 = Сохранить"
  169. };
  170. sizeBtnA.Accept += (s, e) =>
  171. {
  172. sizeBtnA.Frame = new (
  173. sizeBtnA.Frame.X,
  174. sizeBtnA.Frame.Y,
  175. sizeBtnA.Frame.Width + 5,
  176. sizeBtnA.Frame.Height
  177. );
  178. };
  179. absoluteFrame.Add (sizeBtnA);
  180. var label = new Label
  181. {
  182. X = 2, Y = Pos.Bottom (computedFrame) + 1,
  183. Text = "Text Alignment (changes the four buttons above): "
  184. };
  185. main.Add (label);
  186. var radioGroup = new RadioGroup
  187. {
  188. X = 4,
  189. Y = Pos.Bottom (label) + 1,
  190. SelectedItem = 2,
  191. RadioLabels = new [] { "Start", "End", "Center", "Fill" }
  192. };
  193. main.Add (radioGroup);
  194. // Demo changing hotkey
  195. string MoveHotkey (string txt)
  196. {
  197. // Remove the '_'
  198. List<Rune> runes = txt.ToRuneList ();
  199. int i = runes.IndexOf ((Rune)'_');
  200. var start = "";
  201. if (i > -1)
  202. {
  203. start = StringExtensions.ToString (runes.GetRange (0, i));
  204. }
  205. txt = start + StringExtensions.ToString (runes.GetRange (i + 1, runes.Count - (i + 1)));
  206. runes = txt.ToRuneList ();
  207. // Move over one or go to start
  208. i++;
  209. if (i >= runes.Count)
  210. {
  211. i = 0;
  212. }
  213. // Slip in the '_'
  214. start = StringExtensions.ToString (runes.GetRange (0, i));
  215. return start + '_' + StringExtensions.ToString (runes.GetRange (i, runes.Count - i));
  216. }
  217. var mhkb = "Click to Change th_is Button's Hotkey";
  218. var moveHotKeyBtn = new Button
  219. {
  220. X = 2,
  221. Y = Pos.Bottom (radioGroup) + 1,
  222. Width = Dim.Width (computedFrame) - 2,
  223. ColorScheme = Colors.ColorSchemes ["TopLevel"],
  224. Text = mhkb
  225. };
  226. moveHotKeyBtn.Accept += (s, e) => { moveHotKeyBtn.Text = MoveHotkey (moveHotKeyBtn.Text); };
  227. main.Add (moveHotKeyBtn);
  228. var muhkb = " ~  s  gui.cs   master ↑10 = Сохранить";
  229. var moveUnicodeHotKeyBtn = new Button
  230. {
  231. X = Pos.Left (absoluteFrame) + 1,
  232. Y = Pos.Bottom (radioGroup) + 1,
  233. Width = Dim.Width (absoluteFrame) - 2,
  234. ColorScheme = Colors.ColorSchemes ["TopLevel"],
  235. Text = muhkb
  236. };
  237. moveUnicodeHotKeyBtn.Accept += (s, e) => { moveUnicodeHotKeyBtn.Text = MoveHotkey (moveUnicodeHotKeyBtn.Text); };
  238. main.Add (moveUnicodeHotKeyBtn);
  239. radioGroup.SelectedItemChanged += (s, args) =>
  240. {
  241. switch (args.SelectedItem)
  242. {
  243. case 0:
  244. moveBtn.TextAlignment = Alignment.Start;
  245. sizeBtn.TextAlignment = Alignment.Start;
  246. moveBtnA.TextAlignment = Alignment.Start;
  247. sizeBtnA.TextAlignment = Alignment.Start;
  248. moveHotKeyBtn.TextAlignment = Alignment.Start;
  249. moveUnicodeHotKeyBtn.TextAlignment = Alignment.Start;
  250. break;
  251. case 1:
  252. moveBtn.TextAlignment = Alignment.End;
  253. sizeBtn.TextAlignment = Alignment.End;
  254. moveBtnA.TextAlignment = Alignment.End;
  255. sizeBtnA.TextAlignment = Alignment.End;
  256. moveHotKeyBtn.TextAlignment = Alignment.End;
  257. moveUnicodeHotKeyBtn.TextAlignment = Alignment.End;
  258. break;
  259. case 2:
  260. moveBtn.TextAlignment = Alignment.Center;
  261. sizeBtn.TextAlignment = Alignment.Center;
  262. moveBtnA.TextAlignment = Alignment.Center;
  263. sizeBtnA.TextAlignment = Alignment.Center;
  264. moveHotKeyBtn.TextAlignment = Alignment.Center;
  265. moveUnicodeHotKeyBtn.TextAlignment = Alignment.Center;
  266. break;
  267. case 3:
  268. moveBtn.TextAlignment = Alignment.Fill;
  269. sizeBtn.TextAlignment = Alignment.Fill;
  270. moveBtnA.TextAlignment = Alignment.Fill;
  271. sizeBtnA.TextAlignment = Alignment.Fill;
  272. moveHotKeyBtn.TextAlignment = Alignment.Fill;
  273. moveUnicodeHotKeyBtn.TextAlignment = Alignment.Fill;
  274. break;
  275. }
  276. };
  277. label = new ()
  278. {
  279. X = 0,
  280. Y = Pos.Bottom (moveUnicodeHotKeyBtn) + 1,
  281. Title = "_Numeric Up/Down (press-and-hold):",
  282. };
  283. var numericUpDown = new NumericUpDown<int>
  284. {
  285. Value = 69,
  286. X = Pos.Right (label) + 1,
  287. Y = Pos.Top (label),
  288. Width = 5,
  289. Height = 1
  290. };
  291. numericUpDown.ValueChanged += NumericUpDown_ValueChanged;
  292. void NumericUpDown_ValueChanged (object sender, EventArgs<int> e) { }
  293. main.Add (label, numericUpDown);
  294. label = new ()
  295. {
  296. X = 0,
  297. Y = Pos.Bottom (numericUpDown) + 1,
  298. Title = "_No Repeat:"
  299. };
  300. var noRepeatAcceptCount = 0;
  301. var noRepeatButton = new Button
  302. {
  303. X = Pos.Right (label) + 1,
  304. Y = Pos.Top (label),
  305. Title = $"Accept Cou_nt: {noRepeatAcceptCount}",
  306. WantContinuousButtonPressed = false
  307. };
  308. noRepeatButton.Accept += (s, e) => { noRepeatButton.Title = $"Accept Cou_nt: {++noRepeatAcceptCount}"; };
  309. main.Add (label, noRepeatButton);
  310. label = new ()
  311. {
  312. X = 0,
  313. Y = Pos.Bottom (label) + 1,
  314. Title = "_Repeat (press-and-hold):"
  315. };
  316. var acceptCount = 0;
  317. var repeatButton = new Button
  318. {
  319. X = Pos.Right (label) + 1,
  320. Y = Pos.Top (label),
  321. Title = $"Accept Co_unt: {acceptCount}",
  322. WantContinuousButtonPressed = true
  323. };
  324. repeatButton.Accept += (s, e) => { repeatButton.Title = $"Accept Co_unt: {++acceptCount}"; };
  325. var enableCB = new CheckBox
  326. {
  327. X = Pos.Right (repeatButton) + 1,
  328. Y = Pos.Top (repeatButton),
  329. Title = "Enabled",
  330. State = CheckState.Checked
  331. };
  332. enableCB.Toggle += (s, e) => { repeatButton.Enabled = !repeatButton.Enabled; };
  333. main.Add (label, repeatButton, enableCB);
  334. main.Ready += (s, e) => radioGroup.Refresh ();
  335. Application.Run (main);
  336. main.Dispose ();
  337. Application.Shutdown ();
  338. }
  339. /// <summary>
  340. /// Enables the user to increase or decrease a value by clicking on the up or down buttons.
  341. /// </summary>
  342. /// <remarks>
  343. /// Supports the following types: <see cref="int"/>, <see cref="long"/>, <see cref="float"/>, <see cref="double"/>, <see cref="decimal"/>.
  344. /// Supports only one digit of precision.
  345. /// </remarks>
  346. public class NumericUpDown<T> : View
  347. {
  348. private readonly Button _down;
  349. // TODO: Use a TextField instead of a Label
  350. private readonly View _number;
  351. private readonly Button _up;
  352. public NumericUpDown ()
  353. {
  354. Type type = typeof (T);
  355. if (!(type == typeof (int) || type == typeof (long) || type == typeof (float) || type == typeof (double) || type == typeof (decimal)))
  356. {
  357. throw new InvalidOperationException ("T must be a numeric type that supports addition and subtraction.");
  358. }
  359. Width = Dim.Auto (DimAutoStyle.Content); //Dim.Function (() => Digits + 2); // button + 3 for number + button
  360. Height = Dim.Auto (DimAutoStyle.Content);
  361. _down = new ()
  362. {
  363. Height = 1,
  364. Width = 1,
  365. NoPadding = true,
  366. NoDecorations = true,
  367. Title = $"{CM.Glyphs.DownArrow}",
  368. WantContinuousButtonPressed = true,
  369. CanFocus = false,
  370. ShadowStyle = ShadowStyle.None,
  371. };
  372. _number = new ()
  373. {
  374. Text = Value.ToString (),
  375. X = Pos.Right (_down),
  376. Y = Pos.Top (_down),
  377. Width = Dim.Func (() => Digits),
  378. Height = 1,
  379. TextAlignment = Alignment.Center,
  380. CanFocus = true
  381. };
  382. _up = new ()
  383. {
  384. X = Pos.AnchorEnd (),
  385. Y = Pos.Top (_number),
  386. Height = 1,
  387. Width = 1,
  388. NoPadding = true,
  389. NoDecorations = true,
  390. Title = $"{CM.Glyphs.UpArrow}",
  391. WantContinuousButtonPressed = true,
  392. CanFocus = false,
  393. ShadowStyle = ShadowStyle.None,
  394. };
  395. CanFocus = true;
  396. _down.Accept += OnDownButtonOnAccept;
  397. _up.Accept += OnUpButtonOnAccept;
  398. Add (_down, _number, _up);
  399. AddCommand (Command.ScrollUp, () =>
  400. {
  401. Value = (dynamic)Value + 1;
  402. _number.Text = Value.ToString ();
  403. return true;
  404. });
  405. AddCommand (Command.ScrollDown, () =>
  406. {
  407. Value = (dynamic)Value - 1;
  408. _number.Text = Value.ToString ();
  409. return true;
  410. });
  411. KeyBindings.Add (Key.CursorUp, Command.ScrollUp);
  412. KeyBindings.Add (Key.CursorDown, Command.ScrollDown);
  413. return;
  414. void OnDownButtonOnAccept (object s, HandledEventArgs e)
  415. {
  416. InvokeCommand (Command.ScrollDown);
  417. }
  418. void OnUpButtonOnAccept (object s, HandledEventArgs e)
  419. {
  420. InvokeCommand (Command.ScrollUp);
  421. }
  422. }
  423. private void _up_Enter (object sender, FocusEventArgs e)
  424. {
  425. throw new NotImplementedException ();
  426. }
  427. private T _value;
  428. /// <summary>
  429. /// The value that will be incremented or decremented.
  430. /// </summary>
  431. public T Value
  432. {
  433. get => _value;
  434. set
  435. {
  436. if (_value.Equals (value))
  437. {
  438. return;
  439. }
  440. T oldValue = value;
  441. CancelEventArgs<T> args = new (ref _value, ref value);
  442. ValueChanging?.Invoke (this, args);
  443. if (args.Cancel)
  444. {
  445. return;
  446. }
  447. _value = value;
  448. _number.Text = _value.ToString ()!;
  449. ValueChanged?.Invoke (this, new (in _value));
  450. }
  451. }
  452. /// <summary>
  453. /// Fired when the value is about to change. Set <see cref="CancelEventArgs{T}.Cancel"/> to true to prevent the change.
  454. /// </summary>
  455. [CanBeNull]
  456. public event EventHandler<CancelEventArgs<T>> ValueChanging;
  457. /// <summary>
  458. /// Fired when the value has changed.
  459. /// </summary>
  460. [CanBeNull]
  461. public event EventHandler<EventArgs<T>> ValueChanged;
  462. /// <summary>
  463. /// The number of digits to display. The <see cref="View.Viewport"/> will be resized to fit this number of characters plus the buttons. The default is 3.
  464. /// </summary>
  465. public int Digits { get; set; } = 3;
  466. }
  467. }