ComboBox.cs 29 KB

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