ComboBox.cs 29 KB

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