ComboBox.cs 12 KB

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