ComboBox.cs 30 KB

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