ComboBox.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. //
  2. // ComboBox.cs: ComboBox control
  3. //
  4. // Authors:
  5. // Ross Ferguson ([email protected])
  6. //
  7. using System;
  8. using System.Collections;
  9. using System.Collections.Generic;
  10. using NStack;
  11. namespace Terminal.Gui {
  12. /// <summary>
  13. /// Provides a drop-down list of items the user can select from.
  14. /// </summary>
  15. public class ComboBox : View {
  16. IListDataSource source;
  17. /// <summary>
  18. /// Gets or sets the <see cref="IListDataSource"/> backing this <see cref="ComboBox"/>, enabling custom rendering.
  19. /// </summary>
  20. /// <value>The source.</value>
  21. /// <remarks>
  22. /// Use <see cref="SetSource"/> to set a new <see cref="IList"/> source.
  23. /// </remarks>
  24. public IListDataSource Source {
  25. get => source;
  26. set {
  27. source = value;
  28. // Only need to refresh list if its been added to a container view
  29. if (SuperView != null && SuperView.Subviews.Contains (this)) {
  30. SelectedItem = -1;
  31. search.Text = "";
  32. Search_Changed ("");
  33. SetNeedsDisplay ();
  34. }
  35. }
  36. }
  37. /// <summary>
  38. /// Sets the source of the <see cref="ComboBox"/> to an <see cref="IList"/>.
  39. /// </summary>
  40. /// <value>An object implementing the IList interface.</value>
  41. /// <remarks>
  42. /// Use the <see cref="Source"/> property to set a new <see cref="IListDataSource"/> source and use custome rendering.
  43. /// </remarks>
  44. public void SetSource (IList source)
  45. {
  46. if (source == null) {
  47. Source = null;
  48. } else {
  49. listview.SetSource (source);
  50. Source = listview.Source;
  51. }
  52. }
  53. /// <summary>
  54. /// This event is raised when the selected item in the <see cref="ComboBox"/> has changed.
  55. /// </summary>
  56. public event Action<ListViewItemEventArgs> SelectedItemChanged;
  57. /// <summary>
  58. /// This event is raised when the user Double Clicks on an item or presses ENTER to open the selected item.
  59. /// </summary>
  60. public event Action<ListViewItemEventArgs> OpenSelectedItem;
  61. readonly IList searchset = new List<object> ();
  62. ustring text = "";
  63. readonly TextField search;
  64. readonly ListView listview;
  65. bool autoHide = true;
  66. int minimumHeight = 2;
  67. /// <summary>
  68. /// Public constructor
  69. /// </summary>
  70. public ComboBox () : this (string.Empty)
  71. {
  72. }
  73. /// <summary>
  74. /// Public constructor
  75. /// </summary>
  76. /// <param name="text"></param>
  77. public ComboBox (ustring text) : base ()
  78. {
  79. search = new TextField ("");
  80. listview = new ListView () { LayoutStyle = LayoutStyle.Computed, CanFocus = true, TabStop = false };
  81. Initialize ();
  82. Text = text;
  83. }
  84. /// <summary>
  85. /// Public constructor
  86. /// </summary>
  87. /// <param name="rect"></param>
  88. /// <param name="source"></param>
  89. public ComboBox (Rect rect, IList source) : base (rect)
  90. {
  91. search = new TextField ("") { Width = rect.Width };
  92. listview = new ListView (rect, source) { LayoutStyle = LayoutStyle.Computed, ColorScheme = Colors.Base };
  93. Initialize ();
  94. SetSource (source);
  95. }
  96. private void Initialize ()
  97. {
  98. if (Bounds.Height < minimumHeight && (Height == null || Height is Dim.DimAbsolute)) {
  99. Height = minimumHeight;
  100. }
  101. search.TextChanged += Search_Changed;
  102. listview.Y = Pos.Bottom (search);
  103. listview.OpenSelectedItem += (ListViewItemEventArgs a) => Selected ();
  104. this.Add (search, listview);
  105. // On resize
  106. LayoutComplete += (LayoutEventArgs a) => {
  107. if ((!autoHide && Bounds.Width > 0 && search.Frame.Width != Bounds.Width) ||
  108. (autoHide && Bounds.Width > 0 && search.Frame.Width != Bounds.Width - 1)) {
  109. search.Width = listview.Width = autoHide ? Bounds.Width - 1 : Bounds.Width;
  110. listview.Height = CalculatetHeight ();
  111. search.SetRelativeLayout (Bounds);
  112. listview.SetRelativeLayout (Bounds);
  113. }
  114. };
  115. listview.SelectedItemChanged += (ListViewItemEventArgs e) => {
  116. if (searchset.Count > 0) {
  117. SetValue (searchset [listview.SelectedItem]);
  118. }
  119. };
  120. Added += (View v) => {
  121. // Determine if this view is hosted inside a dialog and is the only control
  122. for (View view = this.SuperView; view != null; view = view.SuperView) {
  123. if (view is Dialog && SuperView != null && SuperView.Subviews.Count == 1 && SuperView.Subviews [0] == this) {
  124. autoHide = false;
  125. break;
  126. }
  127. }
  128. SetNeedsLayout ();
  129. SetNeedsDisplay ();
  130. Search_Changed (Text);
  131. };
  132. // Things this view knows how to do
  133. AddCommand (Command.Accept, () => ActivateSelected ());
  134. AddCommand (Command.ToggleExpandCollapse, () => ExpandCollapse ());
  135. AddCommand (Command.Expand, () => Expand ());
  136. AddCommand (Command.Collapse, () => Collapse ());
  137. AddCommand (Command.LineDown, () => MoveDown ());
  138. AddCommand (Command.LineUp, () => MoveUp ());
  139. AddCommand (Command.PageDown, () => PageDown ());
  140. AddCommand (Command.PageUp, () => PageUp ());
  141. AddCommand (Command.TopHome, () => MoveHome ());
  142. AddCommand (Command.BottomEnd, () => MoveEnd ());
  143. AddCommand (Command.Cancel, () => CancelSelected ());
  144. AddCommand (Command.UnixEmulation, () => UnixEmulation ());
  145. // Default keybindings for this view
  146. AddKeyBinding (Key.Enter, Command.Accept);
  147. AddKeyBinding (Key.F4, Command.ToggleExpandCollapse);
  148. AddKeyBinding (Key.CursorDown, Command.LineDown);
  149. AddKeyBinding (Key.CursorUp, Command.LineUp);
  150. AddKeyBinding (Key.PageDown, Command.PageDown);
  151. AddKeyBinding (Key.PageUp, Command.PageUp);
  152. AddKeyBinding (Key.Home, Command.TopHome);
  153. AddKeyBinding (Key.End, Command.BottomEnd);
  154. AddKeyBinding (Key.Esc, Command.Cancel);
  155. AddKeyBinding (Key.U | Key.CtrlMask, Command.UnixEmulation);
  156. }
  157. private bool isShow = false;
  158. private int selectedItem = -1;
  159. /// <summary>
  160. /// Gets the index of the currently selected item in the <see cref="Source"/>
  161. /// </summary>
  162. /// <value>The selected item or -1 none selected.</value>
  163. public int SelectedItem {
  164. get => selectedItem;
  165. set {
  166. if (selectedItem != value && (value == -1
  167. || (source != null && value > -1 && value < source.Count))) {
  168. selectedItem = value;
  169. if (selectedItem != -1) {
  170. SetValue (source.ToList () [selectedItem].ToString (), true);
  171. } else {
  172. SetValue ("", true);
  173. }
  174. OnSelectedChanged ();
  175. }
  176. }
  177. }
  178. /// <summary>
  179. /// Gets the drop down list state, expanded or collapsed.
  180. /// </summary>
  181. public bool IsShow => isShow;
  182. ///<inheritdoc/>
  183. public new ColorScheme ColorScheme {
  184. get {
  185. return base.ColorScheme;
  186. }
  187. set {
  188. listview.ColorScheme = value;
  189. base.ColorScheme = value;
  190. SetNeedsDisplay ();
  191. }
  192. }
  193. /// <summary>
  194. ///If set to true its not allow any changes in the text.
  195. /// </summary>
  196. public bool ReadOnly {
  197. get => search.ReadOnly;
  198. set {
  199. search.ReadOnly = value;
  200. if (search.ReadOnly) {
  201. if (search.ColorScheme != null) {
  202. search.ColorScheme.Normal = search.ColorScheme.Focus;
  203. }
  204. }
  205. }
  206. }
  207. ///<inheritdoc/>
  208. public override bool MouseEvent (MouseEvent me)
  209. {
  210. if (me.X == Bounds.Right - 1 && me.Y == Bounds.Top && me.Flags == MouseFlags.Button1Pressed
  211. && autoHide) {
  212. if (isShow) {
  213. isShow = false;
  214. HideList ();
  215. } else {
  216. SetSearchSet ();
  217. isShow = true;
  218. ShowList ();
  219. FocusSelectedItem ();
  220. }
  221. return true;
  222. } else if (me.Flags == MouseFlags.Button1Pressed) {
  223. if (!search.HasFocus) {
  224. search.SetFocus ();
  225. }
  226. return true;
  227. }
  228. return false;
  229. }
  230. private void FocusSelectedItem ()
  231. {
  232. listview.SelectedItem = SelectedItem > -1 ? SelectedItem : 0;
  233. if (SelectedItem > -1) {
  234. listview.TabStop = true;
  235. listview.SetFocus ();
  236. }
  237. }
  238. ///<inheritdoc/>
  239. public override bool OnEnter (View view)
  240. {
  241. if (!search.HasFocus && !listview.HasFocus) {
  242. search.SetFocus ();
  243. }
  244. search.CursorPosition = search.Text.RuneCount;
  245. return base.OnEnter (view);
  246. }
  247. ///<inheritdoc/>
  248. public override bool OnLeave (View view)
  249. {
  250. if (source?.Count > 0 && selectedItem > -1 && selectedItem < source.Count - 1
  251. && text != source.ToList () [selectedItem].ToString ()) {
  252. SetValue (source.ToList () [selectedItem].ToString ());
  253. }
  254. if (autoHide && isShow && view != this && view != search && view != listview) {
  255. isShow = false;
  256. HideList ();
  257. } else if (listview.TabStop) {
  258. listview.TabStop = false;
  259. }
  260. return base.OnLeave (view);
  261. }
  262. /// <summary>
  263. /// Invokes the SelectedChanged event if it is defined.
  264. /// </summary>
  265. /// <returns></returns>
  266. public virtual bool OnSelectedChanged ()
  267. {
  268. // Note: Cannot rely on "listview.SelectedItem != lastSelectedItem" because the list is dynamic.
  269. // So we cannot optimize. Ie: Don't call if not changed
  270. SelectedItemChanged?.Invoke (new ListViewItemEventArgs (SelectedItem, search.Text));
  271. return true;
  272. }
  273. /// <summary>
  274. /// Invokes the OnOpenSelectedItem event if it is defined.
  275. /// </summary>
  276. /// <returns></returns>
  277. public virtual bool OnOpenSelectedItem ()
  278. {
  279. var value = search.Text;
  280. OpenSelectedItem?.Invoke (new ListViewItemEventArgs (SelectedItem, value));
  281. return true;
  282. }
  283. ///<inheritdoc/>
  284. public override void Redraw (Rect bounds)
  285. {
  286. base.Redraw (bounds);
  287. if (!autoHide) {
  288. return;
  289. }
  290. Move (Bounds.Right - 1, 0);
  291. Driver.AddRune (Driver.DownArrow);
  292. }
  293. ///<inheritdoc/>
  294. public override bool ProcessKey (KeyEvent e)
  295. {
  296. var result = InvokeKeybindings (e);
  297. if (result != null)
  298. return (bool)result;
  299. return base.ProcessKey (e);
  300. }
  301. bool UnixEmulation ()
  302. {
  303. // Unix emulation
  304. Reset ();
  305. return true;
  306. }
  307. bool CancelSelected ()
  308. {
  309. search.SetFocus ();
  310. search.Text = text = "";
  311. OnSelectedChanged ();
  312. Collapse ();
  313. return true;
  314. }
  315. bool? MoveEnd ()
  316. {
  317. if (!isShow && search.HasFocus) {
  318. return null;
  319. }
  320. if (HasItems ()) {
  321. listview.MoveEnd ();
  322. }
  323. return true;
  324. }
  325. bool? MoveHome ()
  326. {
  327. if (!isShow && search.HasFocus) {
  328. return null;
  329. }
  330. if (HasItems ()) {
  331. listview.MoveHome ();
  332. }
  333. return true;
  334. }
  335. bool PageUp ()
  336. {
  337. if (HasItems ()) {
  338. listview.MovePageUp ();
  339. }
  340. return true;
  341. }
  342. bool PageDown ()
  343. {
  344. if (HasItems ()) {
  345. listview.MovePageDown ();
  346. }
  347. return true;
  348. }
  349. bool? MoveUp ()
  350. {
  351. if (search.HasFocus) { // stop odd behavior on KeyUp when search has focus
  352. return true;
  353. }
  354. if (listview.HasFocus && listview.SelectedItem == 0 && searchset?.Count > 0) // jump back to search
  355. {
  356. search.CursorPosition = search.Text.RuneCount;
  357. search.SetFocus ();
  358. return true;
  359. }
  360. return null;
  361. }
  362. bool? MoveDown ()
  363. {
  364. if (search.HasFocus) { // jump to list
  365. if (searchset?.Count > 0) {
  366. listview.TabStop = true;
  367. listview.SetFocus ();
  368. SetValue (searchset [listview.SelectedItem]);
  369. } else {
  370. listview.TabStop = false;
  371. SuperView?.FocusNext ();
  372. }
  373. return true;
  374. }
  375. return null;
  376. }
  377. /// <summary>
  378. /// Toggles the expand/collapse state of the sublist in the combo box
  379. /// </summary>
  380. /// <returns></returns>
  381. bool ExpandCollapse ()
  382. {
  383. if (search.HasFocus || listview.HasFocus) {
  384. if (!isShow) {
  385. return Expand ();
  386. } else {
  387. return Collapse ();
  388. }
  389. }
  390. return false;
  391. }
  392. bool ActivateSelected ()
  393. {
  394. if (HasItems ()) {
  395. Selected ();
  396. return true;
  397. }
  398. return false;
  399. }
  400. bool HasItems ()
  401. {
  402. return Source?.Count > 0;
  403. }
  404. /// <summary>
  405. /// Collapses the drop down list. Returns true if the state chagned or false
  406. /// if it was already collapsed and no action was taken
  407. /// </summary>
  408. public virtual bool Collapse ()
  409. {
  410. if (!isShow) {
  411. return false;
  412. }
  413. isShow = false;
  414. HideList ();
  415. return true;
  416. }
  417. /// <summary>
  418. /// Expands the drop down list. Returns true if the state chagned or false
  419. /// if it was already expanded and no action was taken
  420. /// </summary>
  421. public virtual bool Expand ()
  422. {
  423. if (isShow) {
  424. return false;
  425. }
  426. SetSearchSet ();
  427. isShow = true;
  428. ShowList ();
  429. FocusSelectedItem ();
  430. return true;
  431. }
  432. /// <summary>
  433. /// The currently selected list item
  434. /// </summary>
  435. public new ustring Text {
  436. get {
  437. return text;
  438. }
  439. set {
  440. search.Text = text = value;
  441. }
  442. }
  443. private void SetValue (object text, bool isFromSelectedItem = false)
  444. {
  445. search.TextChanged -= Search_Changed;
  446. this.text = search.Text = text.ToString ();
  447. search.CursorPosition = 0;
  448. search.TextChanged += Search_Changed;
  449. if (!isFromSelectedItem) {
  450. selectedItem = GetSelectedItemFromSource (this.text);
  451. OnSelectedChanged ();
  452. }
  453. }
  454. private void Selected ()
  455. {
  456. isShow = false;
  457. listview.TabStop = false;
  458. if (listview.Source.Count == 0 || (searchset?.Count ?? 0) == 0) {
  459. text = "";
  460. HideList ();
  461. return;
  462. }
  463. SetValue (searchset [listview.SelectedItem]);
  464. search.CursorPosition = search.Text.RuneCount;
  465. Search_Changed (search.Text);
  466. OnOpenSelectedItem ();
  467. Reset (keepSearchText: true);
  468. HideList ();
  469. }
  470. private int GetSelectedItemFromSource (ustring value)
  471. {
  472. if (source == null) {
  473. return -1;
  474. }
  475. for (int i = 0; i < source.Count; i++) {
  476. if (source.ToList () [i].ToString () == value) {
  477. return i;
  478. }
  479. }
  480. return -1;
  481. }
  482. /// <summary>
  483. /// Reset to full original list
  484. /// </summary>
  485. private void Reset (bool keepSearchText = false)
  486. {
  487. if (!keepSearchText) {
  488. search.Text = text = "";
  489. }
  490. ResetSearchSet ();
  491. listview.SetSource (searchset);
  492. listview.Height = CalculatetHeight ();
  493. if (Subviews.Count > 0) {
  494. search.SetFocus ();
  495. }
  496. }
  497. private void ResetSearchSet (bool noCopy = false)
  498. {
  499. searchset.Clear ();
  500. if (autoHide || noCopy)
  501. return;
  502. SetSearchSet ();
  503. }
  504. private void SetSearchSet ()
  505. {
  506. if (Source == null) { return; }
  507. // force deep copy
  508. foreach (var item in Source.ToList ()) {
  509. searchset.Add (item);
  510. }
  511. }
  512. private void Search_Changed (ustring text)
  513. {
  514. if (source == null) { // Object initialization
  515. return;
  516. }
  517. if (ustring.IsNullOrEmpty (search.Text) && ustring.IsNullOrEmpty (text)) {
  518. ResetSearchSet ();
  519. } else if (search.Text != text) {
  520. isShow = true;
  521. ResetSearchSet (noCopy: true);
  522. foreach (var item in source.ToList ()) { // Iterate to preserver object type and force deep copy
  523. if (item.ToString ().StartsWith (search.Text.ToString (), StringComparison.CurrentCultureIgnoreCase)) {
  524. searchset.Add (item);
  525. }
  526. }
  527. }
  528. ShowList ();
  529. }
  530. /// <summary>
  531. /// Show the search list
  532. /// </summary>
  533. ///
  534. /// Consider making public
  535. private void ShowList ()
  536. {
  537. listview.SetSource (searchset);
  538. listview.Clear (); // Ensure list shrinks in Dialog as you type
  539. listview.Height = CalculatetHeight ();
  540. this.SuperView?.BringSubviewToFront (this);
  541. }
  542. /// <summary>
  543. /// Hide the search list
  544. /// </summary>
  545. ///
  546. /// Consider making public
  547. private void HideList ()
  548. {
  549. var rect = listview.ViewToScreen (listview.Bounds);
  550. Reset (SelectedItem > -1);
  551. listview.Clear (rect);
  552. listview.TabStop = false;
  553. SuperView?.SendSubviewToBack (this);
  554. SuperView?.SetNeedsDisplay (rect);
  555. }
  556. /// <summary>
  557. /// Internal height of dynamic search list
  558. /// </summary>
  559. /// <returns></returns>
  560. private int CalculatetHeight ()
  561. {
  562. if (Bounds.Height == 0)
  563. return 0;
  564. return Math.Min (Math.Max (Bounds.Height - 1, minimumHeight - 1), searchset?.Count > 0 ? searchset.Count : isShow ? Math.Max (Bounds.Height - 1, minimumHeight - 1) : 0);
  565. }
  566. }
  567. }