ComboBox.cs 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  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. using System.Threading.Channels;
  11. namespace Terminal.Gui;
  12. /// <summary>Provides a drop-down list of items the user can select from.</summary>
  13. public class ComboBox : View, IDesignable
  14. {
  15. private readonly ComboListView _listview;
  16. private readonly int _minimumHeight = 2;
  17. private readonly TextField _search;
  18. private readonly ObservableCollection<object> _searchSet = [];
  19. private bool _autoHide = true;
  20. private bool _hideDropdownListOnClick;
  21. private int _lastSelectedItem = -1;
  22. private int _selectedItem = -1;
  23. private IListDataSource _source;
  24. private string _text = "";
  25. /// <summary>Public constructor</summary>
  26. public ComboBox ()
  27. {
  28. CanFocus = true;
  29. _search = new TextField () { CanFocus = true, TabStop = TabBehavior.NoStop };
  30. _listview = new ComboListView (this, HideDropdownListOnClick) { CanFocus = true, TabStop = TabBehavior.NoStop };
  31. _search.TextChanged += Search_Changed;
  32. _listview.Y = Pos.Bottom (_search);
  33. _listview.OpenSelectedItem += (sender, a) => Selected ();
  34. Add (_search, _listview);
  35. // BUGBUG: This should not be needed; LayoutComplete will handle
  36. Initialized += (s, e) => ProcessLayout ();
  37. // On resize
  38. LayoutComplete += (sender, a) => ProcessLayout ();
  39. ;
  40. _listview.SelectedItemChanged += (sender, e) =>
  41. {
  42. if (!HideDropdownListOnClick && _searchSet.Count > 0)
  43. {
  44. SetValue (_searchSet [_listview.SelectedItem]);
  45. }
  46. };
  47. Added += (s, e) =>
  48. {
  49. // Determine if this view is hosted inside a dialog and is the only control
  50. for (View view = SuperView; view != null; view = view.SuperView)
  51. {
  52. if (view is Dialog && SuperView is { } && SuperView.Subviews.Count == 1 && SuperView.Subviews [0] == this)
  53. {
  54. _autoHide = false;
  55. break;
  56. }
  57. }
  58. SetNeedsLayout ();
  59. SetNeedsDisplay ();
  60. ShowHideList (Text);
  61. };
  62. // Things this view knows how to do
  63. AddCommand (Command.Accept, () => ActivateSelected ());
  64. AddCommand (Command.Toggle, () => ExpandCollapse ());
  65. AddCommand (Command.Expand, () => Expand ());
  66. AddCommand (Command.Collapse, () => Collapse ());
  67. AddCommand (Command.Down, () => MoveDown ());
  68. AddCommand (Command.Up, () => MoveUp ());
  69. AddCommand (Command.PageDown, () => PageDown ());
  70. AddCommand (Command.PageUp, () => PageUp ());
  71. AddCommand (Command.Start, () => MoveHome ());
  72. AddCommand (Command.End, () => MoveEnd ());
  73. AddCommand (Command.Cancel, () => CancelSelected ());
  74. AddCommand (Command.UnixEmulation, () => UnixEmulation ());
  75. // Default keybindings for this view
  76. KeyBindings.Add (Key.F4, Command.Toggle);
  77. KeyBindings.Add (Key.CursorDown, Command.Down);
  78. KeyBindings.Add (Key.CursorUp, Command.Up);
  79. KeyBindings.Add (Key.PageDown, Command.PageDown);
  80. KeyBindings.Add (Key.PageUp, Command.PageUp);
  81. KeyBindings.Add (Key.Home, Command.Start);
  82. KeyBindings.Add (Key.End, Command.End);
  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. /// <summary>Virtual method which invokes the <see cref="Expanded"/> event.</summary>
  255. public virtual void OnExpanded () { Expanded?.Invoke (this, EventArgs.Empty); }
  256. /// <inheritdoc/>
  257. protected override void OnHasFocusChanged (bool newHasFocus, View previousFocusedView, View view)
  258. {
  259. if (newHasFocus)
  260. {
  261. if (!_search.HasFocus && !_listview.HasFocus)
  262. {
  263. _search.SetFocus ();
  264. }
  265. _search.CursorPosition = _search.Text.GetRuneCount ();
  266. }
  267. else
  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. }
  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. if (HasFocus)
  353. {
  354. _search.SetFocus ();
  355. }
  356. if (ReadOnly || HideDropdownListOnClick)
  357. {
  358. SelectedItem = _lastSelectedItem;
  359. if (SelectedItem > -1 && _listview.Source?.Count > 0)
  360. {
  361. Text = _listview.Source.ToList () [SelectedItem]?.ToString ();
  362. }
  363. }
  364. else if (!ReadOnly)
  365. {
  366. Text = string.Empty;
  367. _selectedItem = _lastSelectedItem;
  368. OnSelectedChanged ();
  369. }
  370. return Collapse ();
  371. }
  372. /// <summary>Toggles the expand/collapse state of the sublist in the combo box</summary>
  373. /// <returns></returns>
  374. private bool ExpandCollapse ()
  375. {
  376. if (_search.HasFocus || _listview.HasFocus)
  377. {
  378. if (!IsShow)
  379. {
  380. return Expand ();
  381. }
  382. return Collapse ();
  383. }
  384. return false;
  385. }
  386. private void FocusSelectedItem ()
  387. {
  388. _listview.SelectedItem = SelectedItem > -1 ? SelectedItem : 0;
  389. _listview.TabStop = TabBehavior.TabStop;
  390. _listview.SetFocus ();
  391. OnExpanded ();
  392. }
  393. private int GetSelectedItemFromSource (string searchText)
  394. {
  395. if (_source is null)
  396. {
  397. return -1;
  398. }
  399. for (var i = 0; i < _searchSet.Count; i++)
  400. {
  401. if (_searchSet [i].ToString () == searchText)
  402. {
  403. return i;
  404. }
  405. }
  406. return -1;
  407. }
  408. private bool HasItems () { return Source?.Count > 0; }
  409. /// <summary>Hide the search list</summary>
  410. /// Consider making public
  411. private void HideList ()
  412. {
  413. if (_lastSelectedItem != _selectedItem)
  414. {
  415. OnOpenSelectedItem ();
  416. }
  417. Reset (true);
  418. _listview.Clear ();
  419. _listview.TabStop = TabBehavior.NoStop;
  420. SuperView?.MoveSubviewToStart (this);
  421. Rectangle rect = _listview.ViewportToScreen (_listview.IsInitialized ? _listview.Viewport : Rectangle.Empty);
  422. SuperView?.SetNeedsDisplay (rect);
  423. OnCollapsed ();
  424. }
  425. private bool? MoveDown ()
  426. {
  427. if (_search.HasFocus)
  428. {
  429. // jump to list
  430. if (_searchSet?.Count > 0)
  431. {
  432. _listview.TabStop = TabBehavior.TabStop;
  433. _listview.SetFocus ();
  434. if (_listview.SelectedItem > -1)
  435. {
  436. SetValue (_searchSet [_listview.SelectedItem]);
  437. }
  438. else
  439. {
  440. _listview.SelectedItem = 0;
  441. }
  442. }
  443. else
  444. {
  445. return false;
  446. }
  447. return true;
  448. }
  449. return null;
  450. }
  451. private bool? MoveEnd ()
  452. {
  453. if (!IsShow && _search.HasFocus)
  454. {
  455. return null;
  456. }
  457. if (HasItems ())
  458. {
  459. _listview.MoveEnd ();
  460. }
  461. return true;
  462. }
  463. private bool? MoveHome ()
  464. {
  465. if (!IsShow && _search.HasFocus)
  466. {
  467. return null;
  468. }
  469. if (HasItems ())
  470. {
  471. _listview.MoveHome ();
  472. }
  473. return true;
  474. }
  475. private bool? MoveUp ()
  476. {
  477. if (HasItems ())
  478. {
  479. return _listview.MoveUp ();
  480. }
  481. return false;
  482. }
  483. private bool? MoveUpList ()
  484. {
  485. if (_listview.HasFocus && _listview.SelectedItem == 0 && _searchSet?.Count > 0) // jump back to search
  486. {
  487. _search.CursorPosition = _search.Text.GetRuneCount ();
  488. _search.SetFocus ();
  489. }
  490. else
  491. {
  492. MoveUp ();
  493. }
  494. return true;
  495. }
  496. private bool PageDown ()
  497. {
  498. if (HasItems ())
  499. {
  500. _listview.MovePageDown ();
  501. }
  502. return true;
  503. }
  504. private bool PageUp ()
  505. {
  506. if (HasItems ())
  507. {
  508. _listview.MovePageUp ();
  509. }
  510. return true;
  511. }
  512. // TODO: Upgrade Combobox to use Dim.Auto instead of all this stuff.
  513. private void ProcessLayout ()
  514. {
  515. if (Viewport.Height < _minimumHeight && (Height is null || Height is DimAbsolute))
  516. {
  517. Height = _minimumHeight;
  518. }
  519. // BUGBUG: This uses Viewport. Should use ContentSize
  520. if ((!_autoHide && Viewport.Width > 0 && _search.Frame.Width != Viewport.Width)
  521. || (_autoHide && Viewport.Width > 0 && _search.Frame.Width != Viewport.Width - 1))
  522. {
  523. _search.Width = _listview.Width = _autoHide ? Viewport.Width - 1 : Viewport.Width;
  524. _listview.Height = CalculateHeight ();
  525. _search.SetRelativeLayout (GetContentSize ());
  526. _listview.SetRelativeLayout (GetContentSize ());
  527. }
  528. }
  529. /// <summary>Reset to full original list</summary>
  530. private void Reset (bool keepSearchText = false)
  531. {
  532. if (!keepSearchText)
  533. {
  534. SetSearchText (string.Empty);
  535. }
  536. ResetSearchSet ();
  537. _listview.SetSource (_searchSet);
  538. _listview.Height = CalculateHeight ();
  539. if (Subviews.Count > 0 && HasFocus)
  540. {
  541. _search.SetFocus ();
  542. }
  543. }
  544. private void ResetSearchSet (bool noCopy = false)
  545. {
  546. _listview.SuspendCollectionChangedEvent ();
  547. _searchSet.Clear ();
  548. _listview.ResumeSuspendCollectionChangedEvent ();
  549. if (_autoHide || noCopy)
  550. {
  551. return;
  552. }
  553. SetSearchSet ();
  554. }
  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?.MoveSubviewToStart (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. // BUGBUG: OnMouseEvent is internal!
  695. protected internal override bool OnMouseEvent (MouseEvent me)
  696. {
  697. var res = false;
  698. bool isMousePositionValid = IsMousePositionValid (me);
  699. if (isMousePositionValid)
  700. {
  701. res = base.OnMouseEvent (me);
  702. }
  703. if (HideDropdownListOnClick && me.Flags == MouseFlags.Button1Clicked)
  704. {
  705. if (!isMousePositionValid && !_isFocusing)
  706. {
  707. _container.IsShow = false;
  708. _container.HideList ();
  709. }
  710. else if (isMousePositionValid)
  711. {
  712. OnOpenSelectedItem ();
  713. }
  714. else
  715. {
  716. _isFocusing = false;
  717. }
  718. return true;
  719. }
  720. if (me.Flags == MouseFlags.ReportMousePosition && HideDropdownListOnClick)
  721. {
  722. if (isMousePositionValid)
  723. {
  724. _highlighted = Math.Min (TopItem + me.Position.Y, Source.Count);
  725. SetNeedsDisplay ();
  726. }
  727. _isFocusing = false;
  728. return true;
  729. }
  730. return res;
  731. }
  732. public override void OnDrawContent (Rectangle viewport)
  733. {
  734. Attribute current = ColorScheme.Focus;
  735. Driver.SetAttribute (current);
  736. Move (0, 0);
  737. Rectangle f = Frame;
  738. int item = TopItem;
  739. bool focused = HasFocus;
  740. int col = AllowsMarking ? 2 : 0;
  741. int start = LeftItem;
  742. for (var row = 0; row < f.Height; row++, item++)
  743. {
  744. bool isSelected = item == _container.SelectedItem;
  745. bool isHighlighted = _hideDropdownListOnClick && item == _highlighted;
  746. Attribute newcolor;
  747. if (isHighlighted || (isSelected && !_hideDropdownListOnClick))
  748. {
  749. newcolor = focused ? ColorScheme.Focus : ColorScheme.HotNormal;
  750. }
  751. else if (isSelected && _hideDropdownListOnClick)
  752. {
  753. newcolor = focused ? ColorScheme.HotFocus : ColorScheme.HotNormal;
  754. }
  755. else
  756. {
  757. newcolor = focused ? GetNormalColor () : GetNormalColor ();
  758. }
  759. if (newcolor != current)
  760. {
  761. Driver.SetAttribute (newcolor);
  762. current = newcolor;
  763. }
  764. Move (0, row);
  765. if (Source is null || item >= Source.Count)
  766. {
  767. for (var c = 0; c < f.Width; c++)
  768. {
  769. Driver.AddRune ((Rune)' ');
  770. }
  771. }
  772. else
  773. {
  774. var rowEventArgs = new ListViewRowEventArgs (item);
  775. OnRowRender (rowEventArgs);
  776. if (rowEventArgs.RowAttribute is { } && current != rowEventArgs.RowAttribute)
  777. {
  778. current = (Attribute)rowEventArgs.RowAttribute;
  779. Driver.SetAttribute (current);
  780. }
  781. if (AllowsMarking)
  782. {
  783. Driver.AddRune (
  784. Source.IsMarked (item) ? AllowsMultipleSelection ? Glyphs.CheckStateChecked : Glyphs.Selected :
  785. AllowsMultipleSelection ? Glyphs.CheckStateUnChecked : Glyphs.UnSelected
  786. );
  787. Driver.AddRune ((Rune)' ');
  788. }
  789. Source.Render (this, Driver, isSelected, item, col, row, f.Width - col, start);
  790. }
  791. }
  792. }
  793. protected override void OnHasFocusChanged (bool newHasFocus, [CanBeNull] View previousFocusedView, [CanBeNull] View focusedVew)
  794. {
  795. if (newHasFocus)
  796. {
  797. if (_hideDropdownListOnClick)
  798. {
  799. _isFocusing = true;
  800. _highlighted = _container.SelectedItem;
  801. Application.GrabMouse (this);
  802. }
  803. }
  804. else
  805. {
  806. if (_hideDropdownListOnClick)
  807. {
  808. _isFocusing = false;
  809. _highlighted = _container.SelectedItem;
  810. Application.UngrabMouse ();
  811. }
  812. }
  813. }
  814. public override bool OnSelectedChanged ()
  815. {
  816. bool res = base.OnSelectedChanged ();
  817. _highlighted = SelectedItem;
  818. return res;
  819. }
  820. private bool IsMousePositionValid (MouseEvent me)
  821. {
  822. if (me.Position.X >= 0 && me.Position.X < Frame.Width && me.Position.Y >= 0 && me.Position.Y < Frame.Height)
  823. {
  824. return true;
  825. }
  826. return false;
  827. }
  828. private void SetInitialProperties (ComboBox container, bool hideDropdownListOnClick)
  829. {
  830. _container = container
  831. ?? throw new ArgumentNullException (
  832. nameof (container),
  833. "ComboBox container cannot be null."
  834. );
  835. HideDropdownListOnClick = hideDropdownListOnClick;
  836. AddCommand (Command.Up, () => _container.MoveUpList ());
  837. }
  838. }
  839. /// <inheritdoc />
  840. public bool EnableForDesign ()
  841. {
  842. var source = new ObservableCollection<string> (["Combo Item 1", "Combo Item two", "Combo Item Quattro", "Last Combo Item"]);
  843. SetSource (source);
  844. Height = Dim.Auto (DimAutoStyle.Content, minimumContentDim: source.Count + 1);
  845. return true;
  846. }
  847. }