ComboBox.cs 29 KB

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