ComboBox.cs 30 KB

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