ComboBox.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  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 System.Text;
  11. namespace Terminal.Gui;
  12. /// <summary>
  13. /// Provides a drop-down list of items the user can select from.
  14. /// </summary>
  15. public class ComboBox : View {
  16. class ComboListView : ListView {
  17. int _highlighted = -1;
  18. bool _isFocusing;
  19. ComboBox _container;
  20. bool _hideDropdownListOnClick;
  21. public ComboListView (ComboBox container, bool hideDropdownListOnClick) => SetInitialProperties (container, hideDropdownListOnClick);
  22. public ComboListView (ComboBox container, Rect rect, IList source, bool hideDropdownListOnClick) : base (rect, source) => SetInitialProperties (container, hideDropdownListOnClick);
  23. public ComboListView (ComboBox container, IList source, bool hideDropdownListOnClick) : base (source) => SetInitialProperties (container, hideDropdownListOnClick);
  24. void SetInitialProperties (ComboBox container, bool hideDropdownListOnClick)
  25. {
  26. _container = container ?? throw new ArgumentNullException (nameof (container), "ComboBox container cannot be null.");
  27. HideDropdownListOnClick = hideDropdownListOnClick;
  28. AddCommand (Command.LineUp, () => _container.MoveUpList ());
  29. }
  30. public bool HideDropdownListOnClick {
  31. get => _hideDropdownListOnClick;
  32. set => _hideDropdownListOnClick = WantContinuousButtonPressed = value;
  33. }
  34. public override bool MouseEvent (MouseEvent me)
  35. {
  36. bool res = false;
  37. bool isMousePositionValid = IsMousePositionValid (me);
  38. if (isMousePositionValid) {
  39. res = base.MouseEvent (me);
  40. }
  41. if (HideDropdownListOnClick && me.Flags == MouseFlags.Button1Clicked) {
  42. if (!isMousePositionValid && !_isFocusing) {
  43. _container._isShow = false;
  44. _container.HideList ();
  45. } else if (isMousePositionValid) {
  46. OnOpenSelectedItem ();
  47. } else {
  48. _isFocusing = false;
  49. }
  50. return true;
  51. } else if (me.Flags == MouseFlags.ReportMousePosition && HideDropdownListOnClick) {
  52. if (isMousePositionValid) {
  53. _highlighted = Math.Min (TopItem + me.Y, Source.Count);
  54. SetNeedsDisplay ();
  55. }
  56. _isFocusing = false;
  57. return true;
  58. }
  59. return res;
  60. }
  61. bool IsMousePositionValid (MouseEvent me)
  62. {
  63. if (me.X >= 0 && me.X < Frame.Width && me.Y >= 0 && me.Y < Frame.Height) {
  64. return true;
  65. }
  66. return false;
  67. }
  68. public override void OnDrawContent (Rect contentArea)
  69. {
  70. var current = ColorScheme.Focus;
  71. Driver.SetAttribute (current);
  72. Move (0, 0);
  73. var f = Frame;
  74. int item = TopItem;
  75. bool focused = HasFocus;
  76. int col = AllowsMarking ? 2 : 0;
  77. int start = LeftItem;
  78. for (int row = 0; row < f.Height; row++, item++) {
  79. bool isSelected = item == _container.SelectedItem;
  80. bool isHighlighted = _hideDropdownListOnClick && item == _highlighted;
  81. Attribute newcolor;
  82. if (isHighlighted || isSelected && !_hideDropdownListOnClick) {
  83. newcolor = focused ? ColorScheme.Focus : ColorScheme.HotNormal;
  84. } else if (isSelected && _hideDropdownListOnClick) {
  85. newcolor = focused ? ColorScheme.HotFocus : ColorScheme.HotNormal;
  86. } else {
  87. newcolor = focused ? GetNormalColor () : GetNormalColor ();
  88. }
  89. if (newcolor != current) {
  90. Driver.SetAttribute (newcolor);
  91. current = newcolor;
  92. }
  93. Move (0, row);
  94. if (Source == null || item >= Source.Count) {
  95. for (int c = 0; c < f.Width; c++) {
  96. Driver.AddRune ((Rune)' ');
  97. }
  98. } else {
  99. var rowEventArgs = new ListViewRowEventArgs (item);
  100. OnRowRender (rowEventArgs);
  101. if (rowEventArgs.RowAttribute != null && current != rowEventArgs.RowAttribute) {
  102. current = (Attribute)rowEventArgs.RowAttribute;
  103. Driver.SetAttribute (current);
  104. }
  105. if (AllowsMarking) {
  106. Driver.AddRune (Source.IsMarked (item) ? AllowsMultipleSelection ? Glyphs.Checked : Glyphs.Selected : AllowsMultipleSelection ? Glyphs.UnChecked : Glyphs.UnSelected);
  107. Driver.AddRune ((Rune)' ');
  108. }
  109. Source.Render (this, Driver, isSelected, item, col, row, f.Width - col, start);
  110. }
  111. }
  112. }
  113. public override bool OnEnter (View view)
  114. {
  115. if (_hideDropdownListOnClick) {
  116. _isFocusing = true;
  117. _highlighted = _container.SelectedItem;
  118. Application.GrabMouse (this);
  119. }
  120. return base.OnEnter (view);
  121. }
  122. public override bool OnLeave (View view)
  123. {
  124. if (_hideDropdownListOnClick) {
  125. _isFocusing = false;
  126. _highlighted = _container.SelectedItem;
  127. Application.UngrabMouse ();
  128. }
  129. return base.OnLeave (view);
  130. }
  131. public override bool OnSelectedChanged ()
  132. {
  133. bool res = base.OnSelectedChanged ();
  134. _highlighted = SelectedItem;
  135. return res;
  136. }
  137. }
  138. IListDataSource _source;
  139. /// <summary>
  140. /// Gets or sets the <see cref="IListDataSource"/> backing this <see cref="ComboBox"/>, enabling custom rendering.
  141. /// </summary>
  142. /// <value>The source.</value>
  143. /// <remarks>
  144. /// Use <see cref="SetSource"/> to set a new <see cref="IList"/> source.
  145. /// </remarks>
  146. public IListDataSource Source {
  147. get => _source;
  148. set {
  149. _source = value;
  150. // Only need to refresh list if its been added to a container view
  151. if (SuperView != null && SuperView.Subviews.Contains (this)) {
  152. SelectedItem = -1;
  153. _search.Text = "";
  154. Search_Changed (this, new TextChangedEventArgs (""));
  155. SetNeedsDisplay ();
  156. }
  157. }
  158. }
  159. /// <summary>
  160. /// Sets the source of the <see cref="ComboBox"/> to an <see cref="IList"/>.
  161. /// </summary>
  162. /// <value>An object implementing the IList interface.</value>
  163. /// <remarks>
  164. /// Use the <see cref="Source"/> property to set a new <see cref="IListDataSource"/> source and use custome rendering.
  165. /// </remarks>
  166. public void SetSource (IList source)
  167. {
  168. if (source == null) {
  169. Source = null;
  170. } else {
  171. _listview.SetSource (source);
  172. Source = _listview.Source;
  173. }
  174. }
  175. /// <summary>
  176. /// This event is raised when the selected item in the <see cref="ComboBox"/> has changed.
  177. /// </summary>
  178. public event EventHandler<ListViewItemEventArgs> SelectedItemChanged;
  179. /// <summary>
  180. /// This event is raised when the drop-down list is expanded.
  181. /// </summary>
  182. public event EventHandler Expanded;
  183. /// <summary>
  184. /// This event is raised when the drop-down list is collapsed.
  185. /// </summary>
  186. public event EventHandler Collapsed;
  187. /// <summary>
  188. /// This event is raised when the user Double Clicks on an item or presses ENTER to open the selected item.
  189. /// </summary>
  190. public event EventHandler<ListViewItemEventArgs> OpenSelectedItem;
  191. readonly IList _searchset = new List<object> ();
  192. string _text = "";
  193. readonly TextField _search;
  194. readonly ComboListView _listview;
  195. bool _autoHide = true;
  196. readonly int _minimumHeight = 2;
  197. /// <summary>
  198. /// Public constructor
  199. /// </summary>
  200. public ComboBox () : this (string.Empty) { }
  201. /// <summary>
  202. /// Public constructor
  203. /// </summary>
  204. /// <param name="text"></param>
  205. public ComboBox (string text) : base ()
  206. {
  207. _search = new TextField ("");
  208. _listview = new ComboListView (this, HideDropdownListOnClick) { CanFocus = true, TabStop = false };
  209. SetInitialProperties ();
  210. Text = text;
  211. }
  212. /// <summary>
  213. /// Public constructor
  214. /// </summary>
  215. /// <param name="rect"></param>
  216. /// <param name="source"></param>
  217. public ComboBox (Rect rect, IList source) : base (rect)
  218. {
  219. _search = new TextField ("") { Width = rect.Width };
  220. _listview = new ComboListView (this, rect, source, HideDropdownListOnClick) { ColorScheme = Colors.ColorSchemes ["Base"] };
  221. SetInitialProperties ();
  222. SetSource (source);
  223. }
  224. /// <summary>
  225. /// Initialize with the source.
  226. /// </summary>
  227. /// <param name="source">The source.</param>
  228. public ComboBox (IList source) : this (string.Empty)
  229. {
  230. _search = new TextField ("");
  231. _listview = new ComboListView (this, source, HideDropdownListOnClick) { ColorScheme = Colors.ColorSchemes ["Base"] };
  232. SetInitialProperties ();
  233. SetSource (source);
  234. }
  235. void SetInitialProperties ()
  236. {
  237. _search.TextChanged += Search_Changed;
  238. _listview.Y = Pos.Bottom (_search);
  239. _listview.OpenSelectedItem += (object sender, ListViewItemEventArgs a) => Selected ();
  240. Add (_search, _listview);
  241. // On resize
  242. LayoutComplete += (object sender, LayoutEventArgs a) => {
  243. if (Bounds.Height < _minimumHeight && (Height == null || Height is Dim.DimAbsolute)) {
  244. Height = _minimumHeight;
  245. }
  246. if (!_autoHide && Bounds.Width > 0 && _search.Frame.Width != Bounds.Width ||
  247. _autoHide && Bounds.Width > 0 && _search.Frame.Width != Bounds.Width - 1) {
  248. _search.Width = _listview.Width = _autoHide ? Bounds.Width - 1 : Bounds.Width;
  249. _listview.Height = CalculatetHeight ();
  250. _search.SetRelativeLayout (Bounds);
  251. _listview.SetRelativeLayout (Bounds);
  252. }
  253. };
  254. _listview.SelectedItemChanged += (object sender, ListViewItemEventArgs e) => {
  255. if (!HideDropdownListOnClick && _searchset.Count > 0) {
  256. SetValue (_searchset [_listview.SelectedItem]);
  257. }
  258. };
  259. Added += (s, e) => {
  260. // Determine if this view is hosted inside a dialog and is the only control
  261. for (var view = SuperView; view != null; view = view.SuperView) {
  262. if (view is Dialog && SuperView != null && SuperView.Subviews.Count == 1 && SuperView.Subviews [0] == this) {
  263. _autoHide = false;
  264. break;
  265. }
  266. }
  267. SetNeedsLayout ();
  268. SetNeedsDisplay ();
  269. Search_Changed (this, new TextChangedEventArgs (Text));
  270. };
  271. // Things this view knows how to do
  272. AddCommand (Command.Accept, () => ActivateSelected ());
  273. AddCommand (Command.ToggleExpandCollapse, () => ExpandCollapse ());
  274. AddCommand (Command.Expand, () => Expand ());
  275. AddCommand (Command.Collapse, () => Collapse ());
  276. AddCommand (Command.LineDown, () => MoveDown ());
  277. AddCommand (Command.LineUp, () => MoveUp ());
  278. AddCommand (Command.PageDown, () => PageDown ());
  279. AddCommand (Command.PageUp, () => PageUp ());
  280. AddCommand (Command.TopHome, () => MoveHome ());
  281. AddCommand (Command.BottomEnd, () => MoveEnd ());
  282. AddCommand (Command.Cancel, () => CancelSelected ());
  283. AddCommand (Command.UnixEmulation, () => UnixEmulation ());
  284. // Default keybindings for this view
  285. KeyBindings.Add (KeyCode.Enter, Command.Accept);
  286. KeyBindings.Add (KeyCode.F4, Command.ToggleExpandCollapse);
  287. KeyBindings.Add (KeyCode.CursorDown, Command.LineDown);
  288. KeyBindings.Add (KeyCode.CursorUp, Command.LineUp);
  289. KeyBindings.Add (KeyCode.PageDown, Command.PageDown);
  290. KeyBindings.Add (KeyCode.PageUp, Command.PageUp);
  291. KeyBindings.Add (KeyCode.Home, Command.TopHome);
  292. KeyBindings.Add (KeyCode.End, Command.BottomEnd);
  293. KeyBindings.Add (KeyCode.Esc, Command.Cancel);
  294. KeyBindings.Add (KeyCode.U | KeyCode.CtrlMask, Command.UnixEmulation);
  295. }
  296. bool _isShow = false;
  297. int _selectedItem = -1;
  298. int _lastSelectedItem = -1;
  299. bool _hideDropdownListOnClick;
  300. /// <summary>
  301. /// Gets the index of the currently selected item in the <see cref="Source"/>
  302. /// </summary>
  303. /// <value>The selected item or -1 none selected.</value>
  304. public int SelectedItem {
  305. get => _selectedItem;
  306. set {
  307. if (_selectedItem != value && (value == -1
  308. || _source != null && value > -1 && value < _source.Count)) {
  309. _selectedItem = _lastSelectedItem = value;
  310. if (_selectedItem != -1) {
  311. SetValue (_source.ToList () [_selectedItem].ToString (), true);
  312. } else {
  313. SetValue ("", true);
  314. }
  315. OnSelectedChanged ();
  316. }
  317. }
  318. }
  319. /// <summary>
  320. /// Gets the drop down list state, expanded or collapsed.
  321. /// </summary>
  322. public bool IsShow => _isShow;
  323. ///<inheritdoc/>
  324. public new ColorScheme ColorScheme {
  325. get => base.ColorScheme;
  326. set {
  327. _listview.ColorScheme = value;
  328. base.ColorScheme = value;
  329. SetNeedsDisplay ();
  330. }
  331. }
  332. /// <summary>
  333. ///If set to true its not allow any changes in the text.
  334. /// </summary>
  335. public bool ReadOnly {
  336. get => _search.ReadOnly;
  337. set {
  338. _search.ReadOnly = value;
  339. if (_search.ReadOnly) {
  340. if (_search.ColorScheme != null) {
  341. _search.ColorScheme = new ColorScheme (_search.ColorScheme) {
  342. Normal = _search.ColorScheme.Focus
  343. };
  344. }
  345. }
  346. }
  347. }
  348. /// <summary>
  349. /// Gets or sets if the drop-down list can be hide with a button click event.
  350. /// </summary>
  351. public bool HideDropdownListOnClick {
  352. get => _hideDropdownListOnClick;
  353. set => _hideDropdownListOnClick = _listview.HideDropdownListOnClick = value;
  354. }
  355. ///<inheritdoc/>
  356. public override bool MouseEvent (MouseEvent me)
  357. {
  358. if (me.X == Bounds.Right - 1 && me.Y == Bounds.Top && me.Flags == MouseFlags.Button1Pressed
  359. && _autoHide) {
  360. if (_isShow) {
  361. _isShow = false;
  362. HideList ();
  363. } else {
  364. SetSearchSet ();
  365. _isShow = true;
  366. ShowList ();
  367. FocusSelectedItem ();
  368. }
  369. return true;
  370. } else if (me.Flags == MouseFlags.Button1Pressed) {
  371. if (!_search.HasFocus) {
  372. _search.SetFocus ();
  373. }
  374. return true;
  375. }
  376. return false;
  377. }
  378. void FocusSelectedItem ()
  379. {
  380. _listview.SelectedItem = SelectedItem > -1 ? SelectedItem : 0;
  381. _listview.TabStop = true;
  382. _listview.SetFocus ();
  383. OnExpanded ();
  384. }
  385. /// <summary>
  386. /// Virtual method which invokes the <see cref="Expanded"/> event.
  387. /// </summary>
  388. public virtual void OnExpanded () => Expanded?.Invoke (this, EventArgs.Empty);
  389. /// <summary>
  390. /// Virtual method which invokes the <see cref="Collapsed"/> event.
  391. /// </summary>
  392. public virtual void OnCollapsed () => Collapsed?.Invoke (this, EventArgs.Empty);
  393. ///<inheritdoc/>
  394. public override bool OnEnter (View view)
  395. {
  396. if (!_search.HasFocus && !_listview.HasFocus) {
  397. _search.SetFocus ();
  398. }
  399. _search.CursorPosition = _search.Text.GetRuneCount ();
  400. return base.OnEnter (view);
  401. }
  402. ///<inheritdoc/>
  403. public override bool OnLeave (View view)
  404. {
  405. if (_source?.Count > 0 && _selectedItem > -1 && _selectedItem < _source.Count - 1
  406. && _text != _source.ToList () [_selectedItem].ToString ()) {
  407. SetValue (_source.ToList () [_selectedItem].ToString ());
  408. }
  409. if (_autoHide && _isShow && view != this && view != _search && view != _listview) {
  410. _isShow = false;
  411. HideList ();
  412. } else if (_listview.TabStop) {
  413. _listview.TabStop = false;
  414. }
  415. return base.OnLeave (view);
  416. }
  417. /// <summary>
  418. /// Invokes the SelectedChanged event if it is defined.
  419. /// </summary>
  420. /// <returns></returns>
  421. public virtual bool OnSelectedChanged ()
  422. {
  423. // Note: Cannot rely on "listview.SelectedItem != lastSelectedItem" because the list is dynamic.
  424. // So we cannot optimize. Ie: Don't call if not changed
  425. SelectedItemChanged?.Invoke (this, new ListViewItemEventArgs (SelectedItem, _search.Text));
  426. return true;
  427. }
  428. /// <summary>
  429. /// Invokes the OnOpenSelectedItem event if it is defined.
  430. /// </summary>
  431. /// <returns></returns>
  432. public virtual bool OnOpenSelectedItem ()
  433. {
  434. string value = _search.Text;
  435. _lastSelectedItem = SelectedItem;
  436. OpenSelectedItem?.Invoke (this, new ListViewItemEventArgs (SelectedItem, value));
  437. return true;
  438. }
  439. ///<inheritdoc/>
  440. public override void OnDrawContent (Rect contentArea)
  441. {
  442. base.OnDrawContent (contentArea);
  443. if (!_autoHide) {
  444. return;
  445. }
  446. Driver.SetAttribute (ColorScheme.Focus);
  447. Move (Bounds.Right - 1, 0);
  448. Driver.AddRune (Glyphs.DownArrow);
  449. }
  450. bool UnixEmulation ()
  451. {
  452. // Unix emulation
  453. Reset ();
  454. return true;
  455. }
  456. bool CancelSelected ()
  457. {
  458. _search.SetFocus ();
  459. if (ReadOnly || HideDropdownListOnClick) {
  460. SelectedItem = _lastSelectedItem;
  461. if (SelectedItem > -1 && _listview.Source?.Count > 0) {
  462. _search.Text = _text = _listview.Source.ToList () [SelectedItem].ToString ();
  463. }
  464. } else if (!ReadOnly) {
  465. _search.Text = _text = "";
  466. _selectedItem = _lastSelectedItem;
  467. OnSelectedChanged ();
  468. }
  469. return Collapse ();
  470. }
  471. bool? MoveEnd ()
  472. {
  473. if (!_isShow && _search.HasFocus) {
  474. return null;
  475. }
  476. if (HasItems ()) {
  477. _listview.MoveEnd ();
  478. }
  479. return true;
  480. }
  481. bool? MoveHome ()
  482. {
  483. if (!_isShow && _search.HasFocus) {
  484. return null;
  485. }
  486. if (HasItems ()) {
  487. _listview.MoveHome ();
  488. }
  489. return true;
  490. }
  491. bool PageUp ()
  492. {
  493. if (HasItems ()) {
  494. _listview.MovePageUp ();
  495. }
  496. return true;
  497. }
  498. bool PageDown ()
  499. {
  500. if (HasItems ()) {
  501. _listview.MovePageDown ();
  502. }
  503. return true;
  504. }
  505. bool? MoveUp ()
  506. {
  507. if (HasItems ()) {
  508. _listview.MoveUp ();
  509. }
  510. return true;
  511. }
  512. bool? MoveUpList ()
  513. {
  514. if (_listview.HasFocus && _listview.SelectedItem == 0 && _searchset?.Count > 0) // jump back to search
  515. {
  516. _search.CursorPosition = _search.Text.GetRuneCount ();
  517. _search.SetFocus ();
  518. } else {
  519. MoveUp ();
  520. }
  521. return true;
  522. }
  523. bool? MoveDown ()
  524. {
  525. if (_search.HasFocus) {
  526. // jump to list
  527. if (_searchset?.Count > 0) {
  528. _listview.TabStop = true;
  529. _listview.SetFocus ();
  530. if (_listview.SelectedItem > -1) {
  531. SetValue (_searchset [_listview.SelectedItem]);
  532. } else {
  533. _listview.SelectedItem = 0;
  534. }
  535. } else {
  536. _listview.TabStop = false;
  537. SuperView?.FocusNext ();
  538. }
  539. return true;
  540. }
  541. return null;
  542. }
  543. /// <summary>
  544. /// Toggles the expand/collapse state of the sublist in the combo box
  545. /// </summary>
  546. /// <returns></returns>
  547. bool ExpandCollapse ()
  548. {
  549. if (_search.HasFocus || _listview.HasFocus) {
  550. if (!_isShow) {
  551. return Expand ();
  552. } else {
  553. return Collapse ();
  554. }
  555. }
  556. return false;
  557. }
  558. bool ActivateSelected ()
  559. {
  560. if (HasItems ()) {
  561. Selected ();
  562. return true;
  563. }
  564. return false;
  565. }
  566. bool HasItems () => Source?.Count > 0;
  567. /// <summary>
  568. /// Collapses the drop down list. Returns true if the state chagned or false
  569. /// if it was already collapsed and no action was taken
  570. /// </summary>
  571. public virtual bool Collapse ()
  572. {
  573. if (!_isShow) {
  574. return false;
  575. }
  576. _isShow = false;
  577. HideList ();
  578. return true;
  579. }
  580. /// <summary>
  581. /// Expands the drop down list. Returns true if the state chagned or false
  582. /// if it was already expanded and no action was taken
  583. /// </summary>
  584. public virtual bool Expand ()
  585. {
  586. if (_isShow) {
  587. return false;
  588. }
  589. SetSearchSet ();
  590. _isShow = true;
  591. ShowList ();
  592. FocusSelectedItem ();
  593. return true;
  594. }
  595. /// <summary>
  596. /// The currently selected list item
  597. /// </summary>
  598. public new string Text {
  599. get => _text;
  600. set => SetSearchText (value);
  601. }
  602. /// <summary>
  603. /// Current search text
  604. /// </summary>
  605. public string SearchText {
  606. get => _search.Text;
  607. set => SetSearchText (value);
  608. }
  609. void SetValue (object text, bool isFromSelectedItem = false)
  610. {
  611. _search.TextChanged -= Search_Changed;
  612. this._text = _search.Text = text.ToString ();
  613. _search.CursorPosition = 0;
  614. _search.TextChanged += Search_Changed;
  615. if (!isFromSelectedItem) {
  616. _selectedItem = GetSelectedItemFromSource (this._text);
  617. OnSelectedChanged ();
  618. }
  619. }
  620. void Selected ()
  621. {
  622. _isShow = false;
  623. _listview.TabStop = false;
  624. if (_listview.Source.Count == 0 || (_searchset?.Count ?? 0) == 0) {
  625. _text = "";
  626. HideList ();
  627. _isShow = false;
  628. return;
  629. }
  630. SetValue (_listview.SelectedItem > -1 ? _searchset [_listview.SelectedItem] : _text);
  631. _search.CursorPosition = _search.Text.GetColumns ();
  632. Search_Changed (this, new TextChangedEventArgs (_search.Text));
  633. OnOpenSelectedItem ();
  634. Reset (keepSearchText: true);
  635. HideList ();
  636. _isShow = false;
  637. }
  638. private int GetSelectedItemFromSource (string searchText)
  639. {
  640. if (_source is null) {
  641. return -1;
  642. }
  643. for (int i = 0; i < _searchset.Count; i++) {
  644. if (_searchset [i].ToString () == searchText) {
  645. return i;
  646. }
  647. }
  648. return -1;
  649. }
  650. /// <summary>
  651. /// Reset to full original list
  652. /// </summary>
  653. void Reset (bool keepSearchText = false)
  654. {
  655. if (!keepSearchText) {
  656. SetSearchText (string.Empty);
  657. }
  658. ResetSearchSet ();
  659. _listview.SetSource (_searchset);
  660. _listview.Height = CalculatetHeight ();
  661. if (Subviews.Count > 0 && HasFocus) {
  662. _search.SetFocus ();
  663. }
  664. }
  665. void SetSearchText (string value) => _search.Text = _text = value;
  666. void ResetSearchSet (bool noCopy = false)
  667. {
  668. _searchset.Clear ();
  669. if (_autoHide || noCopy) {
  670. return;
  671. }
  672. SetSearchSet ();
  673. }
  674. void SetSearchSet ()
  675. {
  676. if (Source == null) { return; }
  677. // force deep copy
  678. foreach (object item in Source.ToList ()) {
  679. _searchset.Add (item);
  680. }
  681. }
  682. private void Search_Changed (object sender, TextChangedEventArgs e)
  683. {
  684. if (_source is null) { // Object initialization
  685. return;
  686. }
  687. if (string.IsNullOrEmpty (_search.Text) && string.IsNullOrEmpty (e.OldValue)) {
  688. ResetSearchSet ();
  689. } else if (_search.Text != e.OldValue) {
  690. if (_search.Text.Length < e.OldValue.Length) {
  691. _selectedItem = -1;
  692. }
  693. _isShow = true;
  694. ResetSearchSet (noCopy: true);
  695. foreach (object item in _source.ToList ()) {
  696. // Iterate to preserver object type and force deep copy
  697. if (item.ToString ().StartsWith (_search.Text, StringComparison.CurrentCultureIgnoreCase)) {
  698. _searchset.Add (item);
  699. }
  700. }
  701. }
  702. if (HasFocus) {
  703. ShowList ();
  704. } else if (_autoHide) {
  705. _isShow = false;
  706. HideList ();
  707. }
  708. }
  709. /// <summary>
  710. /// Show the search list
  711. /// </summary>
  712. ///
  713. /// Consider making public
  714. void ShowList ()
  715. {
  716. _listview.SetSource (_searchset);
  717. _listview.Clear (); // Ensure list shrinks in Dialog as you type
  718. _listview.Height = CalculatetHeight ();
  719. SuperView?.BringSubviewToFront (this);
  720. }
  721. /// <summary>
  722. /// Hide the search list
  723. /// </summary>
  724. ///
  725. /// Consider making public
  726. void HideList ()
  727. {
  728. if (_lastSelectedItem != _selectedItem) {
  729. OnOpenSelectedItem ();
  730. }
  731. var rect = _listview.BoundsToScreen (_listview.IsInitialized ? _listview.Bounds : Rect.Empty);
  732. Reset (keepSearchText: true);
  733. _listview.Clear (rect);
  734. _listview.TabStop = false;
  735. SuperView?.SendSubviewToBack (this);
  736. SuperView?.SetNeedsDisplay (rect);
  737. OnCollapsed ();
  738. }
  739. /// <summary>
  740. /// Internal height of dynamic search list
  741. /// </summary>
  742. /// <returns></returns>
  743. int CalculatetHeight ()
  744. {
  745. if (!IsInitialized || Bounds.Height == 0) {
  746. return 0;
  747. }
  748. return Math.Min (Math.Max (Bounds.Height - 1, _minimumHeight - 1), _searchset?.Count > 0 ? _searchset.Count : _isShow ? Math.Max (Bounds.Height - 1, _minimumHeight - 1) : 0);
  749. }
  750. }