ComboBox.cs 29 KB

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