ComboBox.cs 12 KB

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