ComboBox.cs 15 KB

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