ComboBox.cs 21 KB

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