ComboBox.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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. Search_Changed ("");
  31. SetNeedsDisplay ();
  32. }
  33. }
  34. }
  35. /// <summary>
  36. /// Sets the source of the <see cref="ComboBox"/> to an <see cref="IList"/>.
  37. /// </summary>
  38. /// <value>An object implementing the IList interface.</value>
  39. /// <remarks>
  40. /// Use the <see cref="Source"/> property to set a new <see cref="IListDataSource"/> source and use custome rendering.
  41. /// </remarks>
  42. public void SetSource (IList source)
  43. {
  44. if (source == null) {
  45. Source = null;
  46. } else {
  47. listview.SetSource (source);
  48. Source = listview.Source;
  49. }
  50. }
  51. /// <summary>
  52. /// This event is raised when the selected item in the <see cref="ComboBox"/> has changed.
  53. /// </summary>
  54. public Action<ListViewItemEventArgs> SelectedItemChanged;
  55. /// <summary>
  56. /// This event is raised when the user Double Clicks on an item or presses ENTER to open the selected item.
  57. /// </summary>
  58. public Action<ListViewItemEventArgs> OpenSelectedItem;
  59. IList searchset;
  60. ustring text = "";
  61. readonly TextField search;
  62. readonly ListView listview;
  63. bool autoHide = true;
  64. int dropDownHeight = 4;
  65. /// <summary>
  66. /// Public constructor
  67. /// </summary>
  68. public ComboBox () : base ()
  69. {
  70. search = new TextField ("");
  71. listview = new ListView () { LayoutStyle = LayoutStyle.Computed, CanFocus = true, TabStop = false };
  72. Initialize ();
  73. }
  74. /// <summary>
  75. /// Public constructor
  76. /// </summary>
  77. /// <param name="text"></param>
  78. public ComboBox (ustring text) : base ()
  79. {
  80. search = new TextField ("");
  81. listview = new ListView () { LayoutStyle = LayoutStyle.Computed, CanFocus = true, TabStop = false };
  82. Initialize ();
  83. Text = text;
  84. }
  85. /// <summary>
  86. /// Public constructor
  87. /// </summary>
  88. /// <param name="rect"></param>
  89. /// <param name="source"></param>
  90. public ComboBox (Rect rect, IList source) : base (rect)
  91. {
  92. search = new TextField ("") { Width = rect.Width };
  93. listview = new ListView (rect, source) { LayoutStyle = LayoutStyle.Computed, ColorScheme = Colors.Base };
  94. Initialize ();
  95. SetSource (source);
  96. }
  97. private void Initialize ()
  98. {
  99. if (Bounds.Height < dropDownHeight && Height is Dim.DimAbsolute) {
  100. Height = dropDownHeight;
  101. }
  102. search.TextChanged += Search_Changed;
  103. listview.Y = Pos.Bottom (search);
  104. listview.OpenSelectedItem += (ListViewItemEventArgs a) => Selected ();
  105. this.Add (search, listview);
  106. // On resize
  107. LayoutComplete += (LayoutEventArgs a) => {
  108. if (!autoHide && search.Frame.Width != Bounds.Width ||
  109. autoHide && search.Frame.Width != Bounds.Width - 1) {
  110. search.Width = listview.Width = autoHide ? Bounds.Width - 1 : Bounds.Width;
  111. listview.Height = CalculatetHeight ();
  112. search.SetRelativeLayout (Bounds);
  113. listview.SetRelativeLayout (Bounds);
  114. }
  115. };
  116. listview.SelectedItemChanged += (ListViewItemEventArgs e) => {
  117. if (searchset.Count > 0) {
  118. SetValue (searchset [listview.SelectedItem]);
  119. }
  120. };
  121. Added += (View v) => {
  122. // Determine if this view is hosted inside a dialog
  123. for (View view = this.SuperView; view != null; view = view.SuperView) {
  124. if (view is Dialog) {
  125. autoHide = false;
  126. break;
  127. }
  128. }
  129. SetNeedsLayout ();
  130. SetNeedsDisplay ();
  131. Search_Changed (Text);
  132. };
  133. }
  134. /// <summary>
  135. /// Gets the index of the currently selected item in the <see cref="Source"/>
  136. /// </summary>
  137. /// <value>The selected item or -1 none selected.</value>
  138. public int SelectedItem { private set; get; }
  139. /// <summary>
  140. /// Gets or Sets the list height when is drop down. Ensures at least the SelectedItem is shown.
  141. /// </summary>
  142. public int DropDownHeight {
  143. get { return dropDownHeight; }
  144. set {
  145. if (value < 1) {
  146. dropDownHeight = 1;
  147. } else {
  148. dropDownHeight = value;
  149. }
  150. }
  151. }
  152. bool isShow = false;
  153. ///<inheritdoc/>
  154. public new ColorScheme ColorScheme {
  155. get {
  156. return base.ColorScheme;
  157. }
  158. set {
  159. listview.ColorScheme = value;
  160. base.ColorScheme = value;
  161. SetNeedsDisplay ();
  162. }
  163. }
  164. ///<inheritdoc/>
  165. public override bool MouseEvent (MouseEvent me)
  166. {
  167. if (me.X == Bounds.Right - 1 && me.Y == Bounds.Top && me.Flags == MouseFlags.Button1Pressed
  168. && autoHide) {
  169. if (isShow) {
  170. isShow = false;
  171. HideList ();
  172. } else {
  173. SetSearchSet ();
  174. isShow = true;
  175. ShowList ();
  176. FocusSelectedItem ();
  177. }
  178. return true;
  179. } else if (me.Flags == MouseFlags.Button1Pressed) {
  180. if (!search.HasFocus) {
  181. SetFocus (search);
  182. }
  183. return true;
  184. }
  185. return false;
  186. }
  187. private void FocusSelectedItem ()
  188. {
  189. listview.SelectedItem = SelectedItem > -1 ? SelectedItem : 0;
  190. if (SelectedItem > -1) {
  191. listview.TabStop = true;
  192. this.SetFocus (listview);
  193. }
  194. }
  195. ///<inheritdoc/>
  196. public override bool OnEnter (View view)
  197. {
  198. if (!search.HasFocus && !listview.HasFocus) {
  199. SetFocus (search);
  200. }
  201. search.CursorPosition = search.Text.RuneCount;
  202. return true;
  203. }
  204. ///<inheritdoc/>
  205. public override bool OnLeave (View view)
  206. {
  207. if (autoHide && isShow && view != this && view != search && view != listview) {
  208. isShow = false;
  209. HideList ();
  210. } else if (listview.TabStop) {
  211. listview.TabStop = false;
  212. }
  213. return true;
  214. }
  215. /// <summary>
  216. /// Invokes the SelectedChanged event if it is defined.
  217. /// </summary>
  218. /// <returns></returns>
  219. public virtual bool OnSelectedChanged ()
  220. {
  221. // Note: Cannot rely on "listview.SelectedItem != lastSelectedItem" because the list is dynamic.
  222. // So we cannot optimize. Ie: Don't call if not changed
  223. SelectedItemChanged?.Invoke (new ListViewItemEventArgs(SelectedItem, search.Text));
  224. return true;
  225. }
  226. /// <summary>
  227. /// Invokes the OnOpenSelectedItem event if it is defined.
  228. /// </summary>
  229. /// <returns></returns>
  230. public virtual bool OnOpenSelectedItem ()
  231. {
  232. var value = search.Text;
  233. OpenSelectedItem?.Invoke (new ListViewItemEventArgs (SelectedItem, value));
  234. return true;
  235. }
  236. ///<inheritdoc/>
  237. public override void Redraw (Rect bounds)
  238. {
  239. base.Redraw (bounds);
  240. if (!autoHide) {
  241. return;
  242. }
  243. Move (Bounds.Right - 1, 0);
  244. Driver.AddRune (Driver.DownArrow);
  245. }
  246. ///<inheritdoc/>
  247. public override bool ProcessKey (KeyEvent e)
  248. {
  249. if (e.Key == Key.Enter && listview.SelectedItem > -1) {
  250. Selected ();
  251. return true;
  252. }
  253. if (e.Key == Key.F4 && (search.HasFocus || listview.HasFocus)) {
  254. if (!isShow) {
  255. SetSearchSet ();
  256. isShow = true;
  257. ShowList ();
  258. FocusSelectedItem ();
  259. } else {
  260. isShow = false;
  261. HideList ();
  262. }
  263. return true;
  264. }
  265. if (e.Key == Key.CursorDown && search.HasFocus) { // jump to list
  266. if (searchset.Count > 0) {
  267. listview.TabStop = true;
  268. this.SetFocus (listview);
  269. SetValue (searchset [listview.SelectedItem]);
  270. return true;
  271. } else {
  272. listview.TabStop = false;
  273. SuperView.FocusNext ();
  274. }
  275. }
  276. if (e.Key == Key.CursorUp && search.HasFocus) { // stop odd behavior on KeyUp when search has focus
  277. return true;
  278. }
  279. if (e.Key == Key.CursorUp && listview.HasFocus && listview.SelectedItem == 0 && searchset.Count > 0) // jump back to search
  280. {
  281. search.CursorPosition = search.Text.RuneCount;
  282. this.SetFocus (search);
  283. return true;
  284. }
  285. if(e.Key == Key.PageDown) {
  286. if (listview.SelectedItem != -1) {
  287. listview.MovePageDown ();
  288. }
  289. return true;
  290. }
  291. if (e.Key == Key.PageUp) {
  292. if (listview.SelectedItem != -1) {
  293. listview.MovePageUp ();
  294. }
  295. return true;
  296. }
  297. if (e.Key == Key.Home) {
  298. if (listview.SelectedItem != -1) {
  299. listview.MoveHome ();
  300. }
  301. return true;
  302. }
  303. if(e.Key == Key.End) {
  304. if(listview.SelectedItem != -1) {
  305. listview.MoveEnd ();
  306. }
  307. return true;
  308. }
  309. if (e.Key == Key.Esc) {
  310. this.SetFocus (search);
  311. search.Text = text = "";
  312. OnSelectedChanged ();
  313. return true;
  314. }
  315. // Unix emulation
  316. if (e.Key == Key.ControlU) {
  317. Reset ();
  318. return true;
  319. }
  320. return base.ProcessKey (e);
  321. }
  322. /// <summary>
  323. /// The currently selected list item
  324. /// </summary>
  325. public new ustring Text {
  326. get {
  327. return text;
  328. }
  329. set {
  330. search.Text = text = value;
  331. }
  332. }
  333. private void SetValue (object text)
  334. {
  335. search.TextChanged -= Search_Changed;
  336. this.text = search.Text = text.ToString();
  337. search.CursorPosition = 0;
  338. search.TextChanged += Search_Changed;
  339. SelectedItem = GetSelectedItemFromSource (this.text);
  340. OnSelectedChanged ();
  341. }
  342. private void Selected ()
  343. {
  344. isShow = false;
  345. listview.TabStop = false;
  346. if (listview.Source.Count == 0 || searchset.Count == 0) {
  347. text = "";
  348. return;
  349. }
  350. SetValue (searchset [listview.SelectedItem]);
  351. search.CursorPosition = search.Text.RuneCount;
  352. Search_Changed (search.Text);
  353. OnOpenSelectedItem ();
  354. Reset (keepSearchText: true);
  355. }
  356. private int GetSelectedItemFromSource (ustring value)
  357. {
  358. if (source == null) {
  359. return -1;
  360. }
  361. for (int i = 0; i < source.Count; i++) {
  362. if (source.ToList () [i].ToString () == value) {
  363. return i;
  364. }
  365. }
  366. return -1;
  367. }
  368. /// <summary>
  369. /// Reset to full original list
  370. /// </summary>
  371. private void Reset (bool keepSearchText = false)
  372. {
  373. if (!keepSearchText) {
  374. search.Text = text = "";
  375. }
  376. ResetSearchSet ();
  377. listview.SetSource (searchset);
  378. listview.Height = CalculatetHeight ();
  379. this.SetFocus (search);
  380. }
  381. private void ResetSearchSet (bool noCopy = false)
  382. {
  383. if (searchset == null) {
  384. searchset = new List<object> ();
  385. } else {
  386. searchset.Clear ();
  387. }
  388. if (autoHide || noCopy)
  389. return;
  390. SetSearchSet ();
  391. }
  392. private void SetSearchSet ()
  393. {
  394. // force deep copy
  395. foreach (var item in Source.ToList ()) {
  396. searchset.Add (item);
  397. }
  398. }
  399. private void Search_Changed (ustring text)
  400. {
  401. if (source == null) { // Object initialization
  402. return;
  403. }
  404. if (ustring.IsNullOrEmpty (search.Text) && ustring.IsNullOrEmpty (text)) {
  405. ResetSearchSet ();
  406. } else if (search.Text != text) {
  407. isShow = true;
  408. ResetSearchSet (noCopy: true);
  409. foreach (var item in source.ToList ()) { // Iterate to preserver object type and force deep copy
  410. if (item.ToString().StartsWith (search.Text.ToString(), StringComparison.CurrentCultureIgnoreCase)) {
  411. searchset.Add (item);
  412. }
  413. }
  414. }
  415. ShowList ();
  416. }
  417. /// <summary>
  418. /// Show the search list
  419. /// </summary>
  420. ///
  421. /// Consider making public
  422. private void ShowList ()
  423. {
  424. listview.SetSource (searchset);
  425. listview.Clear (); // Ensure list shrinks in Dialog as you type
  426. listview.Height = CalculatetHeight ();
  427. this.SuperView?.BringSubviewToFront (this);
  428. }
  429. /// <summary>
  430. /// Hide the search list
  431. /// </summary>
  432. ///
  433. /// Consider making public
  434. private void HideList ()
  435. {
  436. Reset (SelectedItem > -1);
  437. listview.TabStop = false;
  438. }
  439. /// <summary>
  440. /// Internal height of dynamic search list
  441. /// </summary>
  442. /// <returns></returns>
  443. private int CalculatetHeight ()
  444. {
  445. if (Bounds.Height == 0)
  446. return 0;
  447. return Math.Min (Math.Max(Bounds.Height - 1, dropDownHeight), searchset?.Count > 0 ? searchset.Count : isShow ? Math.Max (Bounds.Height - 1, dropDownHeight) : 0);
  448. }
  449. }
  450. }