ComboBox.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  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) { LayoutStyle = LayoutStyle.Computed, 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) { LayoutStyle = LayoutStyle.Computed, ColorScheme = Colors.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) { LayoutStyle = LayoutStyle.Computed, ColorScheme = Colors.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.Normal = _search.ColorScheme.Focus;
  342. }
  343. }
  344. }
  345. }
  346. /// <summary>
  347. /// Gets or sets if the drop-down list can be hide with a button click event.
  348. /// </summary>
  349. public bool HideDropdownListOnClick {
  350. get => _hideDropdownListOnClick;
  351. set => _hideDropdownListOnClick = _listview.HideDropdownListOnClick = value;
  352. }
  353. ///<inheritdoc/>
  354. public override bool MouseEvent (MouseEvent me)
  355. {
  356. if (me.X == Bounds.Right - 1 && me.Y == Bounds.Top && me.Flags == MouseFlags.Button1Pressed
  357. && _autoHide) {
  358. if (_isShow) {
  359. _isShow = false;
  360. HideList ();
  361. } else {
  362. SetSearchSet ();
  363. _isShow = true;
  364. ShowList ();
  365. FocusSelectedItem ();
  366. }
  367. return true;
  368. } else if (me.Flags == MouseFlags.Button1Pressed) {
  369. if (!_search.HasFocus) {
  370. _search.SetFocus ();
  371. }
  372. return true;
  373. }
  374. return false;
  375. }
  376. void FocusSelectedItem ()
  377. {
  378. _listview.SelectedItem = SelectedItem > -1 ? SelectedItem : 0;
  379. _listview.TabStop = true;
  380. _listview.SetFocus ();
  381. OnExpanded ();
  382. }
  383. /// <summary>
  384. /// Virtual method which invokes the <see cref="Expanded"/> event.
  385. /// </summary>
  386. public virtual void OnExpanded () => Expanded?.Invoke (this, EventArgs.Empty);
  387. /// <summary>
  388. /// Virtual method which invokes the <see cref="Collapsed"/> event.
  389. /// </summary>
  390. public virtual void OnCollapsed () => Collapsed?.Invoke (this, EventArgs.Empty);
  391. ///<inheritdoc/>
  392. public override bool OnEnter (View view)
  393. {
  394. if (!_search.HasFocus && !_listview.HasFocus) {
  395. _search.SetFocus ();
  396. }
  397. _search.CursorPosition = _search.Text.GetRuneCount ();
  398. return base.OnEnter (view);
  399. }
  400. ///<inheritdoc/>
  401. public override bool OnLeave (View view)
  402. {
  403. if (_source?.Count > 0 && _selectedItem > -1 && _selectedItem < _source.Count - 1
  404. && _text != _source.ToList () [_selectedItem].ToString ()) {
  405. SetValue (_source.ToList () [_selectedItem].ToString ());
  406. }
  407. if (_autoHide && _isShow && view != this && view != _search && view != _listview) {
  408. _isShow = false;
  409. HideList ();
  410. } else if (_listview.TabStop) {
  411. _listview.TabStop = false;
  412. }
  413. return base.OnLeave (view);
  414. }
  415. /// <summary>
  416. /// Invokes the SelectedChanged event if it is defined.
  417. /// </summary>
  418. /// <returns></returns>
  419. public virtual bool OnSelectedChanged ()
  420. {
  421. // Note: Cannot rely on "listview.SelectedItem != lastSelectedItem" because the list is dynamic.
  422. // So we cannot optimize. Ie: Don't call if not changed
  423. SelectedItemChanged?.Invoke (this, new ListViewItemEventArgs (SelectedItem, _search.Text));
  424. return true;
  425. }
  426. /// <summary>
  427. /// Invokes the OnOpenSelectedItem event if it is defined.
  428. /// </summary>
  429. /// <returns></returns>
  430. public virtual bool OnOpenSelectedItem ()
  431. {
  432. string value = _search.Text;
  433. _lastSelectedItem = SelectedItem;
  434. OpenSelectedItem?.Invoke (this, new ListViewItemEventArgs (SelectedItem, value));
  435. return true;
  436. }
  437. ///<inheritdoc/>
  438. public override void OnDrawContent (Rect contentArea)
  439. {
  440. base.OnDrawContent (contentArea);
  441. if (!_autoHide) {
  442. return;
  443. }
  444. Driver.SetAttribute (ColorScheme.Focus);
  445. Move (Bounds.Right - 1, 0);
  446. Driver.AddRune (Glyphs.DownArrow);
  447. }
  448. bool UnixEmulation ()
  449. {
  450. // Unix emulation
  451. Reset ();
  452. return true;
  453. }
  454. bool CancelSelected ()
  455. {
  456. _search.SetFocus ();
  457. if (ReadOnly || HideDropdownListOnClick) {
  458. SelectedItem = _lastSelectedItem;
  459. if (SelectedItem > -1 && _listview.Source?.Count > 0) {
  460. _search.Text = _text = _listview.Source.ToList () [SelectedItem].ToString ();
  461. }
  462. } else if (!ReadOnly) {
  463. _search.Text = _text = "";
  464. _selectedItem = _lastSelectedItem;
  465. OnSelectedChanged ();
  466. }
  467. return Collapse ();
  468. }
  469. bool? MoveEnd ()
  470. {
  471. if (!_isShow && _search.HasFocus) {
  472. return null;
  473. }
  474. if (HasItems ()) {
  475. _listview.MoveEnd ();
  476. }
  477. return true;
  478. }
  479. bool? MoveHome ()
  480. {
  481. if (!_isShow && _search.HasFocus) {
  482. return null;
  483. }
  484. if (HasItems ()) {
  485. _listview.MoveHome ();
  486. }
  487. return true;
  488. }
  489. bool PageUp ()
  490. {
  491. if (HasItems ()) {
  492. _listview.MovePageUp ();
  493. }
  494. return true;
  495. }
  496. bool PageDown ()
  497. {
  498. if (HasItems ()) {
  499. _listview.MovePageDown ();
  500. }
  501. return true;
  502. }
  503. bool? MoveUp ()
  504. {
  505. if (HasItems ()) {
  506. _listview.MoveUp ();
  507. }
  508. return true;
  509. }
  510. bool? MoveUpList ()
  511. {
  512. if (_listview.HasFocus && _listview.SelectedItem == 0 && _searchset?.Count > 0) // jump back to search
  513. {
  514. _search.CursorPosition = _search.Text.GetRuneCount ();
  515. _search.SetFocus ();
  516. } else {
  517. MoveUp ();
  518. }
  519. return true;
  520. }
  521. bool? MoveDown ()
  522. {
  523. if (_search.HasFocus) {
  524. // jump to list
  525. if (_searchset?.Count > 0) {
  526. _listview.TabStop = true;
  527. _listview.SetFocus ();
  528. if (_listview.SelectedItem > -1) {
  529. SetValue (_searchset [_listview.SelectedItem]);
  530. } else {
  531. _listview.SelectedItem = 0;
  532. }
  533. } else {
  534. _listview.TabStop = false;
  535. SuperView?.FocusNext ();
  536. }
  537. return true;
  538. }
  539. return null;
  540. }
  541. /// <summary>
  542. /// Toggles the expand/collapse state of the sublist in the combo box
  543. /// </summary>
  544. /// <returns></returns>
  545. bool ExpandCollapse ()
  546. {
  547. if (_search.HasFocus || _listview.HasFocus) {
  548. if (!_isShow) {
  549. return Expand ();
  550. } else {
  551. return Collapse ();
  552. }
  553. }
  554. return false;
  555. }
  556. bool ActivateSelected ()
  557. {
  558. if (HasItems ()) {
  559. Selected ();
  560. return true;
  561. }
  562. return false;
  563. }
  564. bool HasItems () => Source?.Count > 0;
  565. /// <summary>
  566. /// Collapses the drop down list. Returns true if the state chagned or false
  567. /// if it was already collapsed and no action was taken
  568. /// </summary>
  569. public virtual bool Collapse ()
  570. {
  571. if (!_isShow) {
  572. return false;
  573. }
  574. _isShow = false;
  575. HideList ();
  576. return true;
  577. }
  578. /// <summary>
  579. /// Expands the drop down list. Returns true if the state chagned or false
  580. /// if it was already expanded and no action was taken
  581. /// </summary>
  582. public virtual bool Expand ()
  583. {
  584. if (_isShow) {
  585. return false;
  586. }
  587. SetSearchSet ();
  588. _isShow = true;
  589. ShowList ();
  590. FocusSelectedItem ();
  591. return true;
  592. }
  593. /// <summary>
  594. /// The currently selected list item
  595. /// </summary>
  596. public new string Text {
  597. get => _text;
  598. set => SetSearchText (value);
  599. }
  600. /// <summary>
  601. /// Current search text
  602. /// </summary>
  603. public string SearchText {
  604. get => _search.Text;
  605. set => SetSearchText (value);
  606. }
  607. void SetValue (object text, bool isFromSelectedItem = false)
  608. {
  609. _search.TextChanged -= Search_Changed;
  610. this._text = _search.Text = text.ToString ();
  611. _search.CursorPosition = 0;
  612. _search.TextChanged += Search_Changed;
  613. if (!isFromSelectedItem) {
  614. _selectedItem = GetSelectedItemFromSource (this._text);
  615. OnSelectedChanged ();
  616. }
  617. }
  618. void Selected ()
  619. {
  620. _isShow = false;
  621. _listview.TabStop = false;
  622. if (_listview.Source.Count == 0 || (_searchset?.Count ?? 0) == 0) {
  623. _text = "";
  624. HideList ();
  625. _isShow = false;
  626. return;
  627. }
  628. SetValue (_listview.SelectedItem > -1 ? _searchset [_listview.SelectedItem] : _text);
  629. _search.CursorPosition = _search.Text.GetColumns ();
  630. Search_Changed (this, new TextChangedEventArgs (_search.Text));
  631. OnOpenSelectedItem ();
  632. Reset (keepSearchText: true);
  633. HideList ();
  634. _isShow = false;
  635. }
  636. private int GetSelectedItemFromSource (string searchText)
  637. {
  638. if (_source is null) {
  639. return -1;
  640. }
  641. for (int i = 0; i < _searchset.Count; i++) {
  642. if (_searchset [i].ToString () == searchText) {
  643. return i;
  644. }
  645. }
  646. return -1;
  647. }
  648. /// <summary>
  649. /// Reset to full original list
  650. /// </summary>
  651. void Reset (bool keepSearchText = false)
  652. {
  653. if (!keepSearchText) {
  654. SetSearchText (string.Empty);
  655. }
  656. ResetSearchSet ();
  657. _listview.SetSource (_searchset);
  658. _listview.Height = CalculatetHeight ();
  659. if (Subviews.Count > 0 && HasFocus) {
  660. _search.SetFocus ();
  661. }
  662. }
  663. void SetSearchText (string value) => _search.Text = _text = value;
  664. void ResetSearchSet (bool noCopy = false)
  665. {
  666. _searchset.Clear ();
  667. if (_autoHide || noCopy) {
  668. return;
  669. }
  670. SetSearchSet ();
  671. }
  672. void SetSearchSet ()
  673. {
  674. if (Source == null) { return; }
  675. // force deep copy
  676. foreach (object item in Source.ToList ()) {
  677. _searchset.Add (item);
  678. }
  679. }
  680. private void Search_Changed (object sender, TextChangedEventArgs e)
  681. {
  682. if (_source is null) { // Object initialization
  683. return;
  684. }
  685. if (string.IsNullOrEmpty (_search.Text) && string.IsNullOrEmpty (e.OldValue)) {
  686. ResetSearchSet ();
  687. } else if (_search.Text != e.OldValue) {
  688. if (_search.Text.Length < e.OldValue.Length) {
  689. _selectedItem = -1;
  690. }
  691. _isShow = true;
  692. ResetSearchSet (noCopy: true);
  693. foreach (object item in _source.ToList ()) {
  694. // Iterate to preserver object type and force deep copy
  695. if (item.ToString ().StartsWith (_search.Text, StringComparison.CurrentCultureIgnoreCase)) {
  696. _searchset.Add (item);
  697. }
  698. }
  699. }
  700. if (HasFocus) {
  701. ShowList ();
  702. } else if (_autoHide) {
  703. _isShow = false;
  704. HideList ();
  705. }
  706. }
  707. /// <summary>
  708. /// Show the search list
  709. /// </summary>
  710. ///
  711. /// Consider making public
  712. void ShowList ()
  713. {
  714. _listview.SetSource (_searchset);
  715. _listview.Clear (); // Ensure list shrinks in Dialog as you type
  716. _listview.Height = CalculatetHeight ();
  717. SuperView?.BringSubviewToFront (this);
  718. }
  719. /// <summary>
  720. /// Hide the search list
  721. /// </summary>
  722. ///
  723. /// Consider making public
  724. void HideList ()
  725. {
  726. if (_lastSelectedItem != _selectedItem) {
  727. OnOpenSelectedItem ();
  728. }
  729. var rect = _listview.BoundsToScreen (_listview.IsInitialized ? _listview.Bounds : Rect.Empty);
  730. Reset (keepSearchText: true);
  731. _listview.Clear (rect);
  732. _listview.TabStop = false;
  733. SuperView?.SendSubviewToBack (this);
  734. SuperView?.SetNeedsDisplay (rect);
  735. OnCollapsed ();
  736. }
  737. /// <summary>
  738. /// Internal height of dynamic search list
  739. /// </summary>
  740. /// <returns></returns>
  741. int CalculatetHeight ()
  742. {
  743. if (!IsInitialized || Bounds.Height == 0) {
  744. return 0;
  745. }
  746. return Math.Min (Math.Max (Bounds.Height - 1, _minimumHeight - 1), _searchset?.Count > 0 ? _searchset.Count : _isShow ? Math.Max (Bounds.Height - 1, _minimumHeight - 1) : 0);
  747. }
  748. }