ComboBox.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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. }
  136. private bool isShow = false;
  137. private int selectedItem = -1;
  138. /// <summary>
  139. /// Gets the index of the currently selected item in the <see cref="Source"/>
  140. /// </summary>
  141. /// <value>The selected item or -1 none selected.</value>
  142. public int SelectedItem {
  143. get => selectedItem;
  144. set {
  145. if (selectedItem != value && (value == -1
  146. || (source != null && value > -1 && value < source.Count))) {
  147. selectedItem = value;
  148. if (selectedItem != -1) {
  149. SetValue (source.ToList () [selectedItem].ToString (), true);
  150. } else {
  151. SetValue ("", true);
  152. }
  153. OnSelectedChanged ();
  154. }
  155. }
  156. }
  157. ///<inheritdoc/>
  158. public new ColorScheme ColorScheme {
  159. get {
  160. return base.ColorScheme;
  161. }
  162. set {
  163. listview.ColorScheme = value;
  164. base.ColorScheme = value;
  165. SetNeedsDisplay ();
  166. }
  167. }
  168. /// <summary>
  169. ///If set to true its not allow any changes in the text.
  170. /// </summary>
  171. public bool ReadOnly {
  172. get => search.ReadOnly;
  173. set {
  174. search.ReadOnly = value;
  175. if (search.ReadOnly) {
  176. if (search.ColorScheme != null) {
  177. search.ColorScheme.Normal = search.ColorScheme.Focus;
  178. }
  179. }
  180. }
  181. }
  182. ///<inheritdoc/>
  183. public override bool MouseEvent (MouseEvent me)
  184. {
  185. if (me.X == Bounds.Right - 1 && me.Y == Bounds.Top && me.Flags == MouseFlags.Button1Pressed
  186. && autoHide) {
  187. if (isShow) {
  188. isShow = false;
  189. HideList ();
  190. } else {
  191. SetSearchSet ();
  192. isShow = true;
  193. ShowList ();
  194. FocusSelectedItem ();
  195. }
  196. return true;
  197. } else if (me.Flags == MouseFlags.Button1Pressed) {
  198. if (!search.HasFocus) {
  199. search.SetFocus ();
  200. }
  201. return true;
  202. }
  203. return false;
  204. }
  205. private void FocusSelectedItem ()
  206. {
  207. listview.SelectedItem = SelectedItem > -1 ? SelectedItem : 0;
  208. if (SelectedItem > -1) {
  209. listview.TabStop = true;
  210. listview.SetFocus ();
  211. }
  212. }
  213. ///<inheritdoc/>
  214. public override bool OnEnter (View view)
  215. {
  216. if (!search.HasFocus && !listview.HasFocus) {
  217. search.SetFocus ();
  218. }
  219. search.CursorPosition = search.Text.RuneCount;
  220. return base.OnEnter (view);
  221. }
  222. ///<inheritdoc/>
  223. public override bool OnLeave (View view)
  224. {
  225. if (source?.Count > 0 && selectedItem > -1 && selectedItem < source.Count - 1
  226. && text != source.ToList () [selectedItem].ToString ()) {
  227. SetValue (source.ToList () [selectedItem].ToString ());
  228. }
  229. if (autoHide && isShow && view != this && view != search && view != listview) {
  230. isShow = false;
  231. HideList ();
  232. } else if (listview.TabStop) {
  233. listview.TabStop = false;
  234. }
  235. return base.OnLeave (view);
  236. }
  237. /// <summary>
  238. /// Invokes the SelectedChanged event if it is defined.
  239. /// </summary>
  240. /// <returns></returns>
  241. public virtual bool OnSelectedChanged ()
  242. {
  243. // Note: Cannot rely on "listview.SelectedItem != lastSelectedItem" because the list is dynamic.
  244. // So we cannot optimize. Ie: Don't call if not changed
  245. SelectedItemChanged?.Invoke (new ListViewItemEventArgs (SelectedItem, search.Text));
  246. return true;
  247. }
  248. /// <summary>
  249. /// Invokes the OnOpenSelectedItem event if it is defined.
  250. /// </summary>
  251. /// <returns></returns>
  252. public virtual bool OnOpenSelectedItem ()
  253. {
  254. var value = search.Text;
  255. OpenSelectedItem?.Invoke (new ListViewItemEventArgs (SelectedItem, value));
  256. return true;
  257. }
  258. ///<inheritdoc/>
  259. public override void Redraw (Rect bounds)
  260. {
  261. base.Redraw (bounds);
  262. if (!autoHide) {
  263. return;
  264. }
  265. Move (Bounds.Right - 1, 0);
  266. Driver.AddRune (Driver.DownArrow);
  267. }
  268. ///<inheritdoc/>
  269. public override bool ProcessKey (KeyEvent e)
  270. {
  271. if (e.Key == Key.Enter && listview.SelectedItem > -1) {
  272. Selected ();
  273. return true;
  274. }
  275. if (e.Key == Key.F4 && (search.HasFocus || listview.HasFocus)) {
  276. if (!isShow) {
  277. SetSearchSet ();
  278. isShow = true;
  279. ShowList ();
  280. FocusSelectedItem ();
  281. } else {
  282. isShow = false;
  283. HideList ();
  284. }
  285. return true;
  286. }
  287. if (e.Key == Key.CursorDown && search.HasFocus) { // jump to list
  288. if (searchset?.Count > 0) {
  289. listview.TabStop = true;
  290. listview.SetFocus ();
  291. SetValue (searchset [listview.SelectedItem]);
  292. return true;
  293. } else {
  294. listview.TabStop = false;
  295. SuperView.FocusNext ();
  296. }
  297. }
  298. if (e.Key == Key.CursorUp && search.HasFocus) { // stop odd behavior on KeyUp when search has focus
  299. return true;
  300. }
  301. if (e.Key == Key.CursorUp && listview.HasFocus && listview.SelectedItem == 0 && searchset?.Count > 0) // jump back to search
  302. {
  303. search.CursorPosition = search.Text.RuneCount;
  304. search.SetFocus ();
  305. return true;
  306. }
  307. if (e.Key == Key.PageDown) {
  308. if (listview.SelectedItem != -1) {
  309. listview.MovePageDown ();
  310. }
  311. return true;
  312. }
  313. if (e.Key == Key.PageUp) {
  314. if (listview.SelectedItem != -1) {
  315. listview.MovePageUp ();
  316. }
  317. return true;
  318. }
  319. if (e.Key == Key.Home) {
  320. if (listview.SelectedItem != -1) {
  321. listview.MoveHome ();
  322. }
  323. return true;
  324. }
  325. if (e.Key == Key.End) {
  326. if (listview.SelectedItem != -1) {
  327. listview.MoveEnd ();
  328. }
  329. return true;
  330. }
  331. if (e.Key == Key.Esc) {
  332. search.SetFocus ();
  333. search.Text = text = "";
  334. OnSelectedChanged ();
  335. return true;
  336. }
  337. // Unix emulation
  338. if (e.Key == (Key.U | Key.CtrlMask)) {
  339. Reset ();
  340. return true;
  341. }
  342. return base.ProcessKey (e);
  343. }
  344. /// <summary>
  345. /// The currently selected list item
  346. /// </summary>
  347. public new ustring Text {
  348. get {
  349. return text;
  350. }
  351. set {
  352. search.Text = text = value;
  353. }
  354. }
  355. private void SetValue (object text, bool isFromSelectedItem = false)
  356. {
  357. search.TextChanged -= Search_Changed;
  358. this.text = search.Text = text.ToString ();
  359. search.CursorPosition = 0;
  360. search.TextChanged += Search_Changed;
  361. if (!isFromSelectedItem) {
  362. selectedItem = GetSelectedItemFromSource (this.text);
  363. OnSelectedChanged ();
  364. }
  365. }
  366. private void Selected ()
  367. {
  368. isShow = false;
  369. listview.TabStop = false;
  370. if (listview.Source.Count == 0 || (searchset?.Count ?? 0) == 0) {
  371. text = "";
  372. HideList ();
  373. return;
  374. }
  375. SetValue (searchset [listview.SelectedItem]);
  376. search.CursorPosition = search.Text.RuneCount;
  377. Search_Changed (search.Text);
  378. OnOpenSelectedItem ();
  379. Reset (keepSearchText: true);
  380. HideList ();
  381. }
  382. private int GetSelectedItemFromSource (ustring value)
  383. {
  384. if (source == null) {
  385. return -1;
  386. }
  387. for (int i = 0; i < source.Count; i++) {
  388. if (source.ToList () [i].ToString () == value) {
  389. return i;
  390. }
  391. }
  392. return -1;
  393. }
  394. /// <summary>
  395. /// Reset to full original list
  396. /// </summary>
  397. private void Reset (bool keepSearchText = false)
  398. {
  399. if (!keepSearchText) {
  400. search.Text = text = "";
  401. }
  402. ResetSearchSet ();
  403. listview.SetSource (searchset);
  404. listview.Height = CalculatetHeight ();
  405. if (Subviews.Count > 0) {
  406. search.SetFocus ();
  407. }
  408. }
  409. private void ResetSearchSet (bool noCopy = false)
  410. {
  411. searchset.Clear ();
  412. if (autoHide || noCopy)
  413. return;
  414. SetSearchSet ();
  415. }
  416. private void SetSearchSet ()
  417. {
  418. // force deep copy
  419. foreach (var item in Source.ToList ()) {
  420. searchset.Add (item);
  421. }
  422. }
  423. private void Search_Changed (ustring text)
  424. {
  425. if (source == null) { // Object initialization
  426. return;
  427. }
  428. if (ustring.IsNullOrEmpty (search.Text) && ustring.IsNullOrEmpty (text)) {
  429. ResetSearchSet ();
  430. } else if (search.Text != text) {
  431. isShow = true;
  432. ResetSearchSet (noCopy: true);
  433. foreach (var item in source.ToList ()) { // Iterate to preserver object type and force deep copy
  434. if (item.ToString ().StartsWith (search.Text.ToString (), StringComparison.CurrentCultureIgnoreCase)) {
  435. searchset.Add (item);
  436. }
  437. }
  438. }
  439. ShowList ();
  440. }
  441. /// <summary>
  442. /// Show the search list
  443. /// </summary>
  444. ///
  445. /// Consider making public
  446. private void ShowList ()
  447. {
  448. listview.SetSource (searchset);
  449. listview.Clear (); // Ensure list shrinks in Dialog as you type
  450. listview.Height = CalculatetHeight ();
  451. this.SuperView?.BringSubviewToFront (this);
  452. }
  453. /// <summary>
  454. /// Hide the search list
  455. /// </summary>
  456. ///
  457. /// Consider making public
  458. private void HideList ()
  459. {
  460. var rect = listview.ViewToScreen (listview.Bounds);
  461. Reset (SelectedItem > -1);
  462. listview.Clear (rect);
  463. listview.TabStop = false;
  464. SuperView?.SendSubviewToBack (this);
  465. SuperView?.SetNeedsDisplay (rect);
  466. }
  467. /// <summary>
  468. /// Internal height of dynamic search list
  469. /// </summary>
  470. /// <returns></returns>
  471. private int CalculatetHeight ()
  472. {
  473. if (Bounds.Height == 0)
  474. return 0;
  475. return Math.Min (Math.Max (Bounds.Height - 1, minimumHeight - 1), searchset?.Count > 0 ? searchset.Count : isShow ? Math.Max (Bounds.Height - 1, minimumHeight - 1) : 0);
  476. }
  477. }
  478. }