ComboBox.cs 30 KB

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