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. namespace Terminal.Gui;
  11. /// <summary>Provides a drop-down list of items the user can select from.</summary>
  12. public class ComboBox : View, IDesignable
  13. {
  14. private readonly ComboListView _listview;
  15. private readonly int _minimumHeight = 2;
  16. private readonly TextField _search;
  17. private readonly ObservableCollection<object> _searchSet = [];
  18. private bool _autoHide = true;
  19. private bool _hideDropdownListOnClick;
  20. private int _lastSelectedItem = -1;
  21. private int _selectedItem = -1;
  22. private IListDataSource _source;
  23. private string _text = "";
  24. /// <summary>Public constructor</summary>
  25. public ComboBox ()
  26. {
  27. CanFocus = true;
  28. _search = new TextField () { CanFocus = true, TabStop = TabBehavior.NoStop };
  29. _listview = new ComboListView (this, HideDropdownListOnClick) { CanFocus = true, TabStop = TabBehavior.NoStop};
  30. _search.TextChanged += Search_Changed;
  31. _search.Accept += Search_Accept;
  32. _listview.Y = Pos.Bottom (_search);
  33. _listview.OpenSelectedItem += (sender, a) => Selected ();
  34. Add (_search, _listview);
  35. // BUGBUG: This should not be needed; LayoutComplete will handle
  36. Initialized += (s, e) => ProcessLayout ();
  37. // On resize
  38. LayoutComplete += (sender, a) => ProcessLayout ();
  39. ;
  40. _listview.SelectedItemChanged += (sender, e) =>
  41. {
  42. if (!HideDropdownListOnClick && _searchSet.Count > 0)
  43. {
  44. SetValue (_searchSet [_listview.SelectedItem]);
  45. }
  46. };
  47. Added += (s, e) =>
  48. {
  49. // Determine if this view is hosted inside a dialog and is the only control
  50. for (View view = SuperView; view != null; view = view.SuperView)
  51. {
  52. if (view is Dialog && SuperView is { } && SuperView.Subviews.Count == 1 && SuperView.Subviews [0] == this)
  53. {
  54. _autoHide = false;
  55. break;
  56. }
  57. }
  58. SetNeedsLayout ();
  59. SetNeedsDisplay ();
  60. ShowHideList (Text);
  61. };
  62. // Things this view knows how to do
  63. AddCommand (Command.Accept, () => ActivateSelected ());
  64. AddCommand (Command.ToggleExpandCollapse, () => ExpandCollapse ());
  65. AddCommand (Command.Expand, () => Expand ());
  66. AddCommand (Command.Collapse, () => Collapse ());
  67. AddCommand (Command.LineDown, () => MoveDown ());
  68. AddCommand (Command.LineUp, () => MoveUp ());
  69. AddCommand (Command.PageDown, () => PageDown ());
  70. AddCommand (Command.PageUp, () => PageUp ());
  71. AddCommand (Command.TopHome, () => MoveHome ());
  72. AddCommand (Command.BottomEnd, () => MoveEnd ());
  73. AddCommand (Command.Cancel, () => CancelSelected ());
  74. AddCommand (Command.UnixEmulation, () => UnixEmulation ());
  75. // Default keybindings for this view
  76. KeyBindings.Add (Key.Enter, Command.Accept);
  77. KeyBindings.Add (Key.F4, Command.ToggleExpandCollapse);
  78. KeyBindings.Add (Key.CursorDown, Command.LineDown);
  79. KeyBindings.Add (Key.CursorUp, Command.LineUp);
  80. KeyBindings.Add (Key.PageDown, Command.PageDown);
  81. KeyBindings.Add (Key.PageUp, Command.PageUp);
  82. KeyBindings.Add (Key.Home, Command.TopHome);
  83. KeyBindings.Add (Key.End, Command.BottomEnd);
  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. /// <inheritdoc/>
  256. protected override bool OnHasFocusChanging (View view)
  257. {
  258. if (!_search.HasFocus && !_listview.HasFocus)
  259. {
  260. _search.SetFocus ();
  261. }
  262. _search.CursorPosition = _search.Text.GetRuneCount ();
  263. return false; // Don't cancel the focus switch
  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 (View view)
  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. return;
  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. _search.SetFocus ();
  354. if (ReadOnly || HideDropdownListOnClick)
  355. {
  356. SelectedItem = _lastSelectedItem;
  357. if (SelectedItem > -1 && _listview.Source?.Count > 0)
  358. {
  359. Text = _listview.Source.ToList () [SelectedItem]?.ToString ();
  360. }
  361. }
  362. else if (!ReadOnly)
  363. {
  364. Text = string.Empty;
  365. _selectedItem = _lastSelectedItem;
  366. OnSelectedChanged ();
  367. }
  368. return Collapse ();
  369. }
  370. /// <summary>Toggles the expand/collapse state of the sublist in the combo box</summary>
  371. /// <returns></returns>
  372. private bool ExpandCollapse ()
  373. {
  374. if (_search.HasFocus || _listview.HasFocus)
  375. {
  376. if (!IsShow)
  377. {
  378. return Expand ();
  379. }
  380. return Collapse ();
  381. }
  382. return false;
  383. }
  384. private void FocusSelectedItem ()
  385. {
  386. _listview.SelectedItem = SelectedItem > -1 ? SelectedItem : 0;
  387. _listview.TabStop = TabBehavior.TabStop;
  388. _listview.SetFocus ();
  389. OnExpanded ();
  390. }
  391. private int GetSelectedItemFromSource (string searchText)
  392. {
  393. if (_source is null)
  394. {
  395. return -1;
  396. }
  397. for (var i = 0; i < _searchSet.Count; i++)
  398. {
  399. if (_searchSet [i].ToString () == searchText)
  400. {
  401. return i;
  402. }
  403. }
  404. return -1;
  405. }
  406. private bool HasItems () { return Source?.Count > 0; }
  407. /// <summary>Hide the search list</summary>
  408. /// Consider making public
  409. private void HideList ()
  410. {
  411. if (_lastSelectedItem != _selectedItem)
  412. {
  413. OnOpenSelectedItem ();
  414. }
  415. Reset (true);
  416. _listview.Clear ();
  417. _listview.TabStop = TabBehavior.NoStop;
  418. SuperView?.SendSubviewToBack (this);
  419. Rectangle rect = _listview.ViewportToScreen (_listview.IsInitialized ? _listview.Viewport : Rectangle.Empty);
  420. SuperView?.SetNeedsDisplay (rect);
  421. OnCollapsed ();
  422. }
  423. private bool? MoveDown ()
  424. {
  425. if (_search.HasFocus)
  426. {
  427. // jump to list
  428. if (_searchSet?.Count > 0)
  429. {
  430. _listview.TabStop = TabBehavior.TabStop;
  431. _listview.SetFocus ();
  432. if (_listview.SelectedItem > -1)
  433. {
  434. SetValue (_searchSet [_listview.SelectedItem]);
  435. }
  436. else
  437. {
  438. _listview.SelectedItem = 0;
  439. }
  440. }
  441. else
  442. {
  443. return false;
  444. }
  445. return true;
  446. }
  447. return null;
  448. }
  449. private bool? MoveEnd ()
  450. {
  451. if (!IsShow && _search.HasFocus)
  452. {
  453. return null;
  454. }
  455. if (HasItems ())
  456. {
  457. _listview.MoveEnd ();
  458. }
  459. return true;
  460. }
  461. private bool? MoveHome ()
  462. {
  463. if (!IsShow && _search.HasFocus)
  464. {
  465. return null;
  466. }
  467. if (HasItems ())
  468. {
  469. _listview.MoveHome ();
  470. }
  471. return true;
  472. }
  473. private bool? MoveUp ()
  474. {
  475. if (HasItems ())
  476. {
  477. return _listview.MoveUp ();
  478. }
  479. return false;
  480. }
  481. private bool? MoveUpList ()
  482. {
  483. if (_listview.HasFocus && _listview.SelectedItem == 0 && _searchSet?.Count > 0) // jump back to search
  484. {
  485. _search.CursorPosition = _search.Text.GetRuneCount ();
  486. _search.SetFocus ();
  487. }
  488. else
  489. {
  490. MoveUp ();
  491. }
  492. return true;
  493. }
  494. private bool PageDown ()
  495. {
  496. if (HasItems ())
  497. {
  498. _listview.MovePageDown ();
  499. }
  500. return true;
  501. }
  502. private bool PageUp ()
  503. {
  504. if (HasItems ())
  505. {
  506. _listview.MovePageUp ();
  507. }
  508. return true;
  509. }
  510. // TODO: Upgrade Combobox to use Dim.Auto instead of all this stuff.
  511. private void ProcessLayout ()
  512. {
  513. if (Viewport.Height < _minimumHeight && (Height is null || Height is DimAbsolute))
  514. {
  515. Height = _minimumHeight;
  516. }
  517. // BUGBUG: This uses Viewport. Should use ContentSize
  518. if ((!_autoHide && Viewport.Width > 0 && _search.Frame.Width != Viewport.Width)
  519. || (_autoHide && Viewport.Width > 0 && _search.Frame.Width != Viewport.Width - 1))
  520. {
  521. _search.Width = _listview.Width = _autoHide ? Viewport.Width - 1 : Viewport.Width;
  522. _listview.Height = CalculateHeight ();
  523. _search.SetRelativeLayout (GetContentSize ());
  524. _listview.SetRelativeLayout (GetContentSize ());
  525. }
  526. }
  527. /// <summary>Reset to full original list</summary>
  528. private void Reset (bool keepSearchText = false)
  529. {
  530. if (!keepSearchText)
  531. {
  532. SetSearchText (string.Empty);
  533. }
  534. ResetSearchSet ();
  535. _listview.SetSource (_searchSet);
  536. _listview.Height = CalculateHeight ();
  537. if (Subviews.Count > 0 && HasFocus)
  538. {
  539. _search.SetFocus ();
  540. }
  541. }
  542. private void ResetSearchSet (bool noCopy = false)
  543. {
  544. _listview.SuspendCollectionChangedEvent ();
  545. _searchSet.Clear ();
  546. _listview.ResumeSuspendCollectionChangedEvent ();
  547. if (_autoHide || noCopy)
  548. {
  549. return;
  550. }
  551. SetSearchSet ();
  552. }
  553. // Tell TextField to handle Accept Command (Enter)
  554. void Search_Accept (object sender, HandledEventArgs e) { e.Handled = true; }
  555. private void Search_Changed (object sender, EventArgs e)
  556. {
  557. if (_source is null)
  558. {
  559. // Object initialization
  560. return;
  561. }
  562. ShowHideList (Text);
  563. }
  564. private void ShowHideList (string oldText)
  565. {
  566. if (string.IsNullOrEmpty (_search.Text) && string.IsNullOrEmpty (oldText))
  567. {
  568. ResetSearchSet ();
  569. }
  570. else if (_search.Text != oldText)
  571. {
  572. if (_search.Text.Length < oldText.Length)
  573. {
  574. _selectedItem = -1;
  575. }
  576. IsShow = true;
  577. ResetSearchSet (true);
  578. if (!string.IsNullOrEmpty (_search.Text))
  579. {
  580. _listview.SuspendCollectionChangedEvent ();
  581. foreach (object item in _source.ToList ())
  582. {
  583. // Iterate to preserver object type and force deep copy
  584. if (item.ToString ()
  585. .StartsWith (
  586. _search.Text,
  587. StringComparison.CurrentCultureIgnoreCase
  588. ))
  589. {
  590. _searchSet.Add (item);
  591. }
  592. }
  593. _listview.ResumeSuspendCollectionChangedEvent ();
  594. }
  595. }
  596. if (HasFocus)
  597. {
  598. ShowList ();
  599. }
  600. else if (_autoHide)
  601. {
  602. IsShow = false;
  603. HideList ();
  604. }
  605. }
  606. private void Selected ()
  607. {
  608. IsShow = false;
  609. _listview.TabStop = TabBehavior.NoStop;
  610. if (_listview.Source.Count == 0 || (_searchSet?.Count ?? 0) == 0)
  611. {
  612. _text = "";
  613. HideList ();
  614. IsShow = false;
  615. return;
  616. }
  617. SetValue (_listview.SelectedItem > -1 ? _searchSet [_listview.SelectedItem] : _text);
  618. _search.CursorPosition = _search.Text.GetColumns ();
  619. ShowHideList (Text);
  620. OnOpenSelectedItem ();
  621. Reset (true);
  622. HideList ();
  623. IsShow = false;
  624. }
  625. private void SetSearchSet ()
  626. {
  627. if (Source is null)
  628. {
  629. return;
  630. }
  631. // PERF: At the request of @dodexahedron in the comment https://github.com/gui-cs/Terminal.Gui/pull/3552#discussion_r1648112410.
  632. _listview.SuspendCollectionChangedEvent ();
  633. // force deep copy
  634. foreach (object item in Source.ToList ())
  635. {
  636. _searchSet.Add (item);
  637. }
  638. _listview.ResumeSuspendCollectionChangedEvent ();
  639. }
  640. // Sets the search text field Text as well as our own Text property
  641. private void SetSearchText (string value)
  642. {
  643. _search.Text = value;
  644. _text = value;
  645. }
  646. private void SetValue (object text, bool isFromSelectedItem = false)
  647. {
  648. // TOOD: The fact we have to suspend events to change the text makes this feel very hacky.
  649. _search.TextChanged -= Search_Changed;
  650. // Note we set _text, to avoid set_Text from setting _search.Text again
  651. _text = _search.Text = text.ToString ();
  652. _search.CursorPosition = 0;
  653. _search.TextChanged += Search_Changed;
  654. if (!isFromSelectedItem)
  655. {
  656. _selectedItem = GetSelectedItemFromSource (_text);
  657. OnSelectedChanged ();
  658. }
  659. }
  660. /// <summary>Show the search list</summary>
  661. /// Consider making public
  662. private void ShowList ()
  663. {
  664. _listview.SuspendCollectionChangedEvent ();
  665. _listview.SetSource (_searchSet);
  666. _listview.ResumeSuspendCollectionChangedEvent ();
  667. _listview.Clear ();
  668. _listview.Height = CalculateHeight ();
  669. SuperView?.BringSubviewToFront (this);
  670. }
  671. private bool UnixEmulation ()
  672. {
  673. // Unix emulation
  674. Reset ();
  675. return true;
  676. }
  677. private class ComboListView : ListView
  678. {
  679. private ComboBox _container;
  680. private bool _hideDropdownListOnClick;
  681. private int _highlighted = -1;
  682. private bool _isFocusing;
  683. public ComboListView (ComboBox container, bool hideDropdownListOnClick) { SetInitialProperties (container, hideDropdownListOnClick); }
  684. public ComboListView (ComboBox container, ObservableCollection<string> source, bool hideDropdownListOnClick)
  685. {
  686. Source = new ListWrapper<string> (source);
  687. SetInitialProperties (container, hideDropdownListOnClick);
  688. }
  689. public bool HideDropdownListOnClick
  690. {
  691. get => _hideDropdownListOnClick;
  692. set => _hideDropdownListOnClick = WantContinuousButtonPressed = value;
  693. }
  694. // BUGBUG: OnMouseEvent is internal!
  695. protected internal override bool OnMouseEvent (MouseEvent me)
  696. {
  697. var res = false;
  698. bool isMousePositionValid = IsMousePositionValid (me);
  699. if (isMousePositionValid)
  700. {
  701. res = base.OnMouseEvent (me);
  702. }
  703. if (HideDropdownListOnClick && me.Flags == MouseFlags.Button1Clicked)
  704. {
  705. if (!isMousePositionValid && !_isFocusing)
  706. {
  707. _container.IsShow = false;
  708. _container.HideList ();
  709. }
  710. else if (isMousePositionValid)
  711. {
  712. OnOpenSelectedItem ();
  713. }
  714. else
  715. {
  716. _isFocusing = false;
  717. }
  718. return true;
  719. }
  720. if (me.Flags == MouseFlags.ReportMousePosition && HideDropdownListOnClick)
  721. {
  722. if (isMousePositionValid)
  723. {
  724. _highlighted = Math.Min (TopItem + me.Position.Y, Source.Count);
  725. SetNeedsDisplay ();
  726. }
  727. _isFocusing = false;
  728. return true;
  729. }
  730. return res;
  731. }
  732. public override void OnDrawContent (Rectangle viewport)
  733. {
  734. Attribute current = ColorScheme.Focus;
  735. Driver.SetAttribute (current);
  736. Move (0, 0);
  737. Rectangle f = Frame;
  738. int item = TopItem;
  739. bool focused = HasFocus;
  740. int col = AllowsMarking ? 2 : 0;
  741. int start = LeftItem;
  742. for (var row = 0; row < f.Height; row++, item++)
  743. {
  744. bool isSelected = item == _container.SelectedItem;
  745. bool isHighlighted = _hideDropdownListOnClick && item == _highlighted;
  746. Attribute newcolor;
  747. if (isHighlighted || (isSelected && !_hideDropdownListOnClick))
  748. {
  749. newcolor = focused ? ColorScheme.Focus : ColorScheme.HotNormal;
  750. }
  751. else if (isSelected && _hideDropdownListOnClick)
  752. {
  753. newcolor = focused ? ColorScheme.HotFocus : ColorScheme.HotNormal;
  754. }
  755. else
  756. {
  757. newcolor = focused ? GetNormalColor () : GetNormalColor ();
  758. }
  759. if (newcolor != current)
  760. {
  761. Driver.SetAttribute (newcolor);
  762. current = newcolor;
  763. }
  764. Move (0, row);
  765. if (Source is null || item >= Source.Count)
  766. {
  767. for (var c = 0; c < f.Width; c++)
  768. {
  769. Driver.AddRune ((Rune)' ');
  770. }
  771. }
  772. else
  773. {
  774. var rowEventArgs = new ListViewRowEventArgs (item);
  775. OnRowRender (rowEventArgs);
  776. if (rowEventArgs.RowAttribute is { } && current != rowEventArgs.RowAttribute)
  777. {
  778. current = (Attribute)rowEventArgs.RowAttribute;
  779. Driver.SetAttribute (current);
  780. }
  781. if (AllowsMarking)
  782. {
  783. Driver.AddRune (
  784. Source.IsMarked (item) ? AllowsMultipleSelection ? Glyphs.CheckStateChecked : Glyphs.Selected :
  785. AllowsMultipleSelection ? Glyphs.CheckStateUnChecked : Glyphs.UnSelected
  786. );
  787. Driver.AddRune ((Rune)' ');
  788. }
  789. Source.Render (this, Driver, isSelected, item, col, row, f.Width - col, start);
  790. }
  791. }
  792. }
  793. protected override bool OnHasFocusChanging (View view)
  794. {
  795. if (_hideDropdownListOnClick)
  796. {
  797. _isFocusing = true;
  798. _highlighted = _container.SelectedItem;
  799. Application.GrabMouse (this);
  800. }
  801. return false; // Don't cancel the focus switch
  802. }
  803. protected override void OnHasFocusChanged (View view)
  804. {
  805. if (_hideDropdownListOnClick)
  806. {
  807. _isFocusing = false;
  808. _highlighted = _container.SelectedItem;
  809. Application.UngrabMouse ();
  810. }
  811. }
  812. public override bool OnSelectedChanged ()
  813. {
  814. bool res = base.OnSelectedChanged ();
  815. _highlighted = SelectedItem;
  816. return res;
  817. }
  818. private bool IsMousePositionValid (MouseEvent me)
  819. {
  820. if (me.Position.X >= 0 && me.Position.X < Frame.Width && me.Position.Y >= 0 && me.Position.Y < Frame.Height)
  821. {
  822. return true;
  823. }
  824. return false;
  825. }
  826. private void SetInitialProperties (ComboBox container, bool hideDropdownListOnClick)
  827. {
  828. _container = container
  829. ?? throw new ArgumentNullException (
  830. nameof (container),
  831. "ComboBox container cannot be null."
  832. );
  833. HideDropdownListOnClick = hideDropdownListOnClick;
  834. AddCommand (Command.LineUp, () => _container.MoveUpList ());
  835. }
  836. }
  837. /// <inheritdoc />
  838. public bool EnableForDesign ()
  839. {
  840. var source = new ObservableCollection<string> (["Combo Item 1", "Combo Item two", "Combo Item Quattro", "Last Combo Item"]);
  841. SetSource (source);
  842. Height = Dim.Auto (DimAutoStyle.Content, minimumContentDim: source.Count + 1);
  843. return true;
  844. }
  845. }