ComboBox.cs 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  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. LayoutComplete += (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. SetNeedsDisplay ();
  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. SetNeedsDisplay ();
  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. SetNeedsDisplay ();
  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 internal override bool OnMouseEvent (MouseEvent 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. public override void OnDrawContent (Rectangle viewport)
  255. {
  256. base.OnDrawContent (viewport);
  257. if (!_autoHide)
  258. {
  259. return;
  260. }
  261. Driver.SetAttribute (ColorScheme.Focus);
  262. Move (Viewport.Right - 1, 0);
  263. Driver.AddRune (Glyphs.DownArrow);
  264. }
  265. /// <summary>Virtual method which invokes the <see cref="Expanded"/> event.</summary>
  266. public virtual void OnExpanded () { Expanded?.Invoke (this, EventArgs.Empty); }
  267. /// <inheritdoc/>
  268. protected override void OnHasFocusChanged (bool newHasFocus, View previousFocusedView, View view)
  269. {
  270. if (newHasFocus)
  271. {
  272. if (!_search.HasFocus && !_listview.HasFocus)
  273. {
  274. _search.SetFocus ();
  275. }
  276. _search.CursorPosition = _search.Text.GetRuneCount ();
  277. }
  278. else
  279. {
  280. if (_source?.Count > 0
  281. && _selectedItem > -1
  282. && _selectedItem < _source.Count - 1
  283. && _text != _source.ToList () [_selectedItem].ToString ())
  284. {
  285. SetValue (_source.ToList () [_selectedItem].ToString ());
  286. }
  287. if (_autoHide && IsShow && view != this && view != _search && view != _listview)
  288. {
  289. IsShow = false;
  290. HideList ();
  291. }
  292. else if (_listview.TabStop?.HasFlag (TabBehavior.TabStop) ?? false)
  293. {
  294. _listview.TabStop = TabBehavior.NoStop;
  295. }
  296. }
  297. }
  298. /// <summary>Invokes the OnOpenSelectedItem event if it is defined.</summary>
  299. /// <returns></returns>
  300. public virtual bool OnOpenSelectedItem ()
  301. {
  302. string value = _search.Text;
  303. _lastSelectedItem = SelectedItem;
  304. OpenSelectedItem?.Invoke (this, new ListViewItemEventArgs (SelectedItem, value));
  305. return true;
  306. }
  307. /// <summary>Invokes the SelectedChanged event if it is defined.</summary>
  308. /// <returns></returns>
  309. public virtual bool OnSelectedChanged ()
  310. {
  311. // Note: Cannot rely on "listview.SelectedItem != lastSelectedItem" because the list is dynamic.
  312. // So we cannot optimize. Ie: Don't call if not changed
  313. SelectedItemChanged?.Invoke (this, new ListViewItemEventArgs (SelectedItem, _search.Text));
  314. return true;
  315. }
  316. /// <summary>This event is raised when the user Double Clicks on an item or presses ENTER to open the selected item.</summary>
  317. public event EventHandler<ListViewItemEventArgs> OpenSelectedItem;
  318. /// <summary>This event is raised when the selected item in the <see cref="ComboBox"/> has changed.</summary>
  319. public event EventHandler<ListViewItemEventArgs> SelectedItemChanged;
  320. /// <summary>Sets the source of the <see cref="ComboBox"/> to an <see cref="ObservableCollection{T}"/>.</summary>
  321. /// <value>An object implementing the INotifyCollectionChanged and INotifyPropertyChanged interface.</value>
  322. /// <remarks>
  323. /// Use the <see cref="Source"/> property to set a new <see cref="IListDataSource"/> source and use custom
  324. /// rendering.
  325. /// </remarks>
  326. public void SetSource<T> (ObservableCollection<T> source)
  327. {
  328. if (source is null)
  329. {
  330. Source = null;
  331. }
  332. else
  333. {
  334. _listview.SetSource<T> (source);
  335. Source = _listview.Source;
  336. }
  337. }
  338. private bool ActivateSelected (CommandContext ctx)
  339. {
  340. if (HasItems ())
  341. {
  342. if (SelectText ())
  343. {
  344. return false;
  345. }
  346. return RaiseAccepting (ctx) == true;
  347. }
  348. return false;
  349. }
  350. /// <summary>Internal height of dynamic search list</summary>
  351. /// <returns></returns>
  352. private int CalculateHeight ()
  353. {
  354. if (!IsInitialized || Viewport.Height == 0)
  355. {
  356. return 0;
  357. }
  358. return Math.Min (
  359. Math.Max (Viewport.Height - 1, _minimumHeight - 1),
  360. _searchSet?.Count > 0 ? _searchSet.Count :
  361. IsShow ? Math.Max (Viewport.Height - 1, _minimumHeight - 1) : 0
  362. );
  363. }
  364. private bool CancelSelected ()
  365. {
  366. if (HasFocus)
  367. {
  368. _search.SetFocus ();
  369. }
  370. if (ReadOnly || HideDropdownListOnClick)
  371. {
  372. SelectedItem = _lastSelectedItem;
  373. if (SelectedItem > -1 && _listview.Source?.Count > 0)
  374. {
  375. Text = _listview.Source.ToList () [SelectedItem]?.ToString ();
  376. }
  377. }
  378. else if (!ReadOnly)
  379. {
  380. Text = string.Empty;
  381. _selectedItem = _lastSelectedItem;
  382. OnSelectedChanged ();
  383. }
  384. return Collapse ();
  385. }
  386. /// <summary>Toggles the expand/collapse state of the sublist in the combo box</summary>
  387. /// <returns></returns>
  388. private bool ExpandCollapse ()
  389. {
  390. if (_search.HasFocus || _listview.HasFocus)
  391. {
  392. if (!IsShow)
  393. {
  394. return Expand ();
  395. }
  396. return Collapse ();
  397. }
  398. return false;
  399. }
  400. private void FocusSelectedItem ()
  401. {
  402. _listview.SelectedItem = SelectedItem > -1 ? SelectedItem : 0;
  403. _listview.TabStop = TabBehavior.TabStop;
  404. _listview.SetFocus ();
  405. OnExpanded ();
  406. }
  407. private int GetSelectedItemFromSource (string searchText)
  408. {
  409. if (_source is null)
  410. {
  411. return -1;
  412. }
  413. for (var i = 0; i < _searchSet.Count; i++)
  414. {
  415. if (_searchSet [i].ToString () == searchText)
  416. {
  417. return i;
  418. }
  419. }
  420. return -1;
  421. }
  422. private bool HasItems () { return Source?.Count > 0; }
  423. /// <summary>Hide the search list</summary>
  424. /// Consider making public
  425. private void HideList ()
  426. {
  427. if (_lastSelectedItem != _selectedItem)
  428. {
  429. OnOpenSelectedItem ();
  430. }
  431. Reset (true);
  432. _listview.Clear ();
  433. _listview.TabStop = TabBehavior.NoStop;
  434. SuperView?.MoveSubviewToStart (this);
  435. Rectangle rect = _listview.ViewportToScreen (_listview.IsInitialized ? _listview.Viewport : Rectangle.Empty);
  436. SuperView?.SetNeedsDisplay (rect);
  437. OnCollapsed ();
  438. }
  439. private bool? MoveDown ()
  440. {
  441. if (_search.HasFocus)
  442. {
  443. // jump to list
  444. if (_searchSet?.Count > 0)
  445. {
  446. _listview.TabStop = TabBehavior.TabStop;
  447. _listview.SetFocus ();
  448. if (_listview.SelectedItem > -1)
  449. {
  450. SetValue (_searchSet [_listview.SelectedItem]);
  451. }
  452. else
  453. {
  454. _listview.SelectedItem = 0;
  455. }
  456. }
  457. else
  458. {
  459. return false;
  460. }
  461. return true;
  462. }
  463. return null;
  464. }
  465. private bool? MoveEnd ()
  466. {
  467. if (!IsShow && _search.HasFocus)
  468. {
  469. return null;
  470. }
  471. if (HasItems ())
  472. {
  473. _listview.MoveEnd ();
  474. }
  475. return true;
  476. }
  477. private bool? MoveHome ()
  478. {
  479. if (!IsShow && _search.HasFocus)
  480. {
  481. return null;
  482. }
  483. if (HasItems ())
  484. {
  485. _listview.MoveHome ();
  486. }
  487. return true;
  488. }
  489. private bool? MoveUp ()
  490. {
  491. if (HasItems ())
  492. {
  493. return _listview.MoveUp ();
  494. }
  495. return false;
  496. }
  497. private bool? MoveUpList ()
  498. {
  499. if (_listview.HasFocus && _listview.SelectedItem == 0 && _searchSet?.Count > 0) // jump back to search
  500. {
  501. _search.CursorPosition = _search.Text.GetRuneCount ();
  502. _search.SetFocus ();
  503. }
  504. else
  505. {
  506. MoveUp ();
  507. }
  508. return true;
  509. }
  510. private bool PageDown ()
  511. {
  512. if (HasItems ())
  513. {
  514. _listview.MovePageDown ();
  515. }
  516. return true;
  517. }
  518. private bool PageUp ()
  519. {
  520. if (HasItems ())
  521. {
  522. _listview.MovePageUp ();
  523. }
  524. return true;
  525. }
  526. // TODO: Upgrade Combobox to use Dim.Auto instead of all this stuff.
  527. private void ProcessLayout ()
  528. {
  529. if (Viewport.Height < _minimumHeight && (Height is null || Height is DimAbsolute))
  530. {
  531. Height = _minimumHeight;
  532. }
  533. // BUGBUG: This uses Viewport. Should use ContentSize
  534. if ((!_autoHide && Viewport.Width > 0 && _search.Frame.Width != Viewport.Width)
  535. || (_autoHide && Viewport.Width > 0 && _search.Frame.Width != Viewport.Width - 1))
  536. {
  537. _search.Width = _listview.Width = _autoHide ? Viewport.Width - 1 : Viewport.Width;
  538. _listview.Height = CalculateHeight ();
  539. _search.SetRelativeLayout (GetContentSize ());
  540. _listview.SetRelativeLayout (GetContentSize ());
  541. }
  542. }
  543. /// <summary>Reset to full original list</summary>
  544. private void Reset (bool keepSearchText = false)
  545. {
  546. if (!keepSearchText)
  547. {
  548. SetSearchText (string.Empty);
  549. }
  550. ResetSearchSet ();
  551. _listview.SetSource (_searchSet);
  552. _listview.Height = CalculateHeight ();
  553. if (Subviews.Count > 0 && HasFocus)
  554. {
  555. _search.SetFocus ();
  556. }
  557. }
  558. private void ResetSearchSet (bool noCopy = false)
  559. {
  560. _listview.SuspendCollectionChangedEvent ();
  561. _searchSet.Clear ();
  562. _listview.ResumeSuspendCollectionChangedEvent ();
  563. if (_autoHide || noCopy)
  564. {
  565. return;
  566. }
  567. SetSearchSet ();
  568. }
  569. private void Search_Changed (object sender, EventArgs e)
  570. {
  571. if (_source is null)
  572. {
  573. // Object initialization
  574. return;
  575. }
  576. ShowHideList (Text);
  577. }
  578. private void ShowHideList (string oldText)
  579. {
  580. if (string.IsNullOrEmpty (_search.Text) && string.IsNullOrEmpty (oldText))
  581. {
  582. ResetSearchSet ();
  583. }
  584. else if (_search.Text != oldText)
  585. {
  586. if (_search.Text.Length < oldText.Length)
  587. {
  588. _selectedItem = -1;
  589. }
  590. IsShow = true;
  591. ResetSearchSet (true);
  592. if (!string.IsNullOrEmpty (_search.Text))
  593. {
  594. _listview.SuspendCollectionChangedEvent ();
  595. foreach (object item in _source.ToList ())
  596. {
  597. // Iterate to preserver object type and force deep copy
  598. if (item.ToString ()
  599. .StartsWith (
  600. _search.Text,
  601. StringComparison.CurrentCultureIgnoreCase
  602. ))
  603. {
  604. _searchSet.Add (item);
  605. }
  606. }
  607. _listview.ResumeSuspendCollectionChangedEvent ();
  608. }
  609. }
  610. if (HasFocus)
  611. {
  612. ShowList ();
  613. }
  614. else if (_autoHide)
  615. {
  616. IsShow = false;
  617. HideList ();
  618. }
  619. }
  620. private bool SelectText ()
  621. {
  622. IsShow = false;
  623. _listview.TabStop = TabBehavior.NoStop;
  624. if (_listview.Source.Count == 0 || (_searchSet?.Count ?? 0) == 0)
  625. {
  626. _text = "";
  627. HideList ();
  628. IsShow = false;
  629. return false;
  630. }
  631. SetValue (_listview.SelectedItem > -1 ? _searchSet [_listview.SelectedItem] : _text);
  632. _search.CursorPosition = _search.Text.GetColumns ();
  633. ShowHideList (Text);
  634. OnOpenSelectedItem ();
  635. Reset (true);
  636. HideList ();
  637. IsShow = false;
  638. return true;
  639. }
  640. private void SetSearchSet ()
  641. {
  642. if (Source is null)
  643. {
  644. return;
  645. }
  646. // PERF: At the request of @dodexahedron in the comment https://github.com/gui-cs/Terminal.Gui/pull/3552#discussion_r1648112410.
  647. _listview.SuspendCollectionChangedEvent ();
  648. // force deep copy
  649. foreach (object item in Source.ToList ())
  650. {
  651. _searchSet.Add (item);
  652. }
  653. _listview.ResumeSuspendCollectionChangedEvent ();
  654. }
  655. // Sets the search text field Text as well as our own Text property
  656. private void SetSearchText (string value)
  657. {
  658. _search.Text = value;
  659. _text = value;
  660. }
  661. private void SetValue (object text, bool isFromSelectedItem = false)
  662. {
  663. // TOOD: The fact we have to suspend events to change the text makes this feel very hacky.
  664. _search.TextChanged -= Search_Changed;
  665. // Note we set _text, to avoid set_Text from setting _search.Text again
  666. _text = _search.Text = text.ToString ();
  667. _search.CursorPosition = 0;
  668. _search.TextChanged += Search_Changed;
  669. if (!isFromSelectedItem)
  670. {
  671. _selectedItem = GetSelectedItemFromSource (_text);
  672. OnSelectedChanged ();
  673. }
  674. }
  675. /// <summary>Show the search list</summary>
  676. /// Consider making public
  677. private void ShowList ()
  678. {
  679. _listview.SuspendCollectionChangedEvent ();
  680. _listview.SetSource (_searchSet);
  681. _listview.ResumeSuspendCollectionChangedEvent ();
  682. _listview.Clear ();
  683. _listview.Height = CalculateHeight ();
  684. SuperView?.MoveSubviewToStart (this);
  685. }
  686. private bool UnixEmulation ()
  687. {
  688. // Unix emulation
  689. Reset ();
  690. return true;
  691. }
  692. private class ComboListView : ListView
  693. {
  694. private ComboBox _container;
  695. private bool _hideDropdownListOnClick;
  696. private int _highlighted = -1;
  697. private bool _isFocusing;
  698. public ComboListView (ComboBox container, bool hideDropdownListOnClick) { SetInitialProperties (container, hideDropdownListOnClick); }
  699. public ComboListView (ComboBox container, ObservableCollection<string> source, bool hideDropdownListOnClick)
  700. {
  701. Source = new ListWrapper<string> (source);
  702. SetInitialProperties (container, hideDropdownListOnClick);
  703. }
  704. public bool HideDropdownListOnClick
  705. {
  706. get => _hideDropdownListOnClick;
  707. set => _hideDropdownListOnClick = WantContinuousButtonPressed = value;
  708. }
  709. // BUGBUG: OnMouseEvent is internal!
  710. protected internal override bool OnMouseEvent (MouseEvent me)
  711. {
  712. var res = false;
  713. bool isMousePositionValid = IsMousePositionValid (me);
  714. if (isMousePositionValid)
  715. {
  716. res = base.OnMouseEvent (me);
  717. }
  718. if (HideDropdownListOnClick && me.Flags == MouseFlags.Button1Clicked)
  719. {
  720. if (!isMousePositionValid && !_isFocusing)
  721. {
  722. _container.IsShow = false;
  723. _container.HideList ();
  724. }
  725. else if (isMousePositionValid)
  726. {
  727. OnOpenSelectedItem ();
  728. }
  729. else
  730. {
  731. _isFocusing = false;
  732. }
  733. return true;
  734. }
  735. if (me.Flags == MouseFlags.ReportMousePosition && HideDropdownListOnClick)
  736. {
  737. if (isMousePositionValid)
  738. {
  739. _highlighted = Math.Min (TopItem + me.Position.Y, Source.Count);
  740. SetNeedsDisplay ();
  741. }
  742. _isFocusing = false;
  743. return true;
  744. }
  745. return res;
  746. }
  747. public override void OnDrawContent (Rectangle viewport)
  748. {
  749. Attribute current = ColorScheme.Focus;
  750. Driver.SetAttribute (current);
  751. Move (0, 0);
  752. Rectangle f = Frame;
  753. int item = TopItem;
  754. bool focused = HasFocus;
  755. int col = AllowsMarking ? 2 : 0;
  756. int start = LeftItem;
  757. for (var row = 0; row < f.Height; row++, item++)
  758. {
  759. bool isSelected = item == _container.SelectedItem;
  760. bool isHighlighted = _hideDropdownListOnClick && item == _highlighted;
  761. Attribute newcolor;
  762. if (isHighlighted || (isSelected && !_hideDropdownListOnClick))
  763. {
  764. newcolor = focused ? ColorScheme.Focus : ColorScheme.HotNormal;
  765. }
  766. else if (isSelected && _hideDropdownListOnClick)
  767. {
  768. newcolor = focused ? ColorScheme.HotFocus : ColorScheme.HotNormal;
  769. }
  770. else
  771. {
  772. newcolor = focused ? GetNormalColor () : GetNormalColor ();
  773. }
  774. if (newcolor != current)
  775. {
  776. Driver.SetAttribute (newcolor);
  777. current = newcolor;
  778. }
  779. Move (0, row);
  780. if (Source is null || item >= Source.Count)
  781. {
  782. for (var c = 0; c < f.Width; c++)
  783. {
  784. Driver.AddRune ((Rune)' ');
  785. }
  786. }
  787. else
  788. {
  789. var rowEventArgs = new ListViewRowEventArgs (item);
  790. OnRowRender (rowEventArgs);
  791. if (rowEventArgs.RowAttribute is { } && current != rowEventArgs.RowAttribute)
  792. {
  793. current = (Attribute)rowEventArgs.RowAttribute;
  794. Driver.SetAttribute (current);
  795. }
  796. if (AllowsMarking)
  797. {
  798. Driver.AddRune (
  799. Source.IsMarked (item) ? AllowsMultipleSelection ? Glyphs.CheckStateChecked : Glyphs.Selected :
  800. AllowsMultipleSelection ? Glyphs.CheckStateUnChecked : Glyphs.UnSelected
  801. );
  802. Driver.AddRune ((Rune)' ');
  803. }
  804. Source.Render (this, Driver, isSelected, item, col, row, f.Width - col, start);
  805. }
  806. }
  807. }
  808. protected override void OnHasFocusChanged (bool newHasFocus, [CanBeNull] View previousFocusedView, [CanBeNull] View focusedVew)
  809. {
  810. if (newHasFocus)
  811. {
  812. if (_hideDropdownListOnClick)
  813. {
  814. _isFocusing = true;
  815. _highlighted = _container.SelectedItem;
  816. Application.GrabMouse (this);
  817. }
  818. }
  819. else
  820. {
  821. if (_hideDropdownListOnClick)
  822. {
  823. _isFocusing = false;
  824. _highlighted = _container.SelectedItem;
  825. Application.UngrabMouse ();
  826. }
  827. }
  828. }
  829. public override bool OnSelectedChanged ()
  830. {
  831. bool res = base.OnSelectedChanged ();
  832. _highlighted = SelectedItem;
  833. return res;
  834. }
  835. private bool IsMousePositionValid (MouseEvent me)
  836. {
  837. if (me.Position.X >= 0 && me.Position.X < Frame.Width && me.Position.Y >= 0 && me.Position.Y < Frame.Height)
  838. {
  839. return true;
  840. }
  841. return false;
  842. }
  843. private void SetInitialProperties (ComboBox container, bool hideDropdownListOnClick)
  844. {
  845. _container = container
  846. ?? throw new ArgumentNullException (
  847. nameof (container),
  848. "ComboBox container cannot be null."
  849. );
  850. HideDropdownListOnClick = hideDropdownListOnClick;
  851. AddCommand (Command.Up, () => _container.MoveUpList ());
  852. }
  853. }
  854. /// <inheritdoc />
  855. public bool EnableForDesign ()
  856. {
  857. var source = new ObservableCollection<string> (["Combo Item 1", "Combo Item two", "Combo Item Quattro", "Last Combo Item"]);
  858. SetSource (source);
  859. Height = Dim.Auto (DimAutoStyle.Content, minimumContentDim: source.Count + 1);
  860. return true;
  861. }
  862. }