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. 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.Enter, Command.Accept);
  78. KeyBindings.Add (Key.F4, Command.Toggle);
  79. KeyBindings.Add (Key.CursorDown, Command.Down);
  80. KeyBindings.Add (Key.CursorUp, Command.Up);
  81. KeyBindings.Add (Key.PageDown, Command.PageDown);
  82. KeyBindings.Add (Key.PageUp, Command.PageUp);
  83. KeyBindings.Add (Key.Home, Command.Start);
  84. KeyBindings.Add (Key.End, Command.End);
  85. KeyBindings.Add (Key.Esc, Command.Cancel);
  86. KeyBindings.Add (Key.U.WithCtrl, Command.UnixEmulation);
  87. }
  88. /// <inheritdoc/>
  89. public new ColorScheme ColorScheme
  90. {
  91. get => base.ColorScheme;
  92. set
  93. {
  94. _listview.ColorScheme = value;
  95. base.ColorScheme = value;
  96. SetNeedsDisplay ();
  97. }
  98. }
  99. /// <summary>Gets or sets if the drop-down list can be hide with a button click event.</summary>
  100. public bool HideDropdownListOnClick
  101. {
  102. get => _hideDropdownListOnClick;
  103. set => _hideDropdownListOnClick = _listview.HideDropdownListOnClick = value;
  104. }
  105. /// <summary>Gets the drop-down list state, expanded or collapsed.</summary>
  106. public bool IsShow { get; private set; }
  107. /// <summary>If set to true, no changes to the text will be allowed.</summary>
  108. public bool ReadOnly
  109. {
  110. get => _search.ReadOnly;
  111. set
  112. {
  113. _search.ReadOnly = value;
  114. if (_search.ReadOnly)
  115. {
  116. if (_search.ColorScheme is { })
  117. {
  118. _search.ColorScheme = new ColorScheme (_search.ColorScheme) { Normal = _search.ColorScheme.Focus };
  119. }
  120. }
  121. }
  122. }
  123. /// <summary>Current search text</summary>
  124. public string SearchText
  125. {
  126. get => _search.Text;
  127. set => SetSearchText (value);
  128. }
  129. /// <summary>Gets the index of the currently selected item in the <see cref="Source"/></summary>
  130. /// <value>The selected item or -1 none selected.</value>
  131. public int SelectedItem
  132. {
  133. get => _selectedItem;
  134. set
  135. {
  136. if (_selectedItem != value
  137. && (value == -1
  138. || (_source is { } && value > -1 && value < _source.Count)))
  139. {
  140. _selectedItem = _lastSelectedItem = value;
  141. if (_selectedItem != -1)
  142. {
  143. SetValue (_source.ToList () [_selectedItem].ToString (), true);
  144. }
  145. else
  146. {
  147. SetValue ("", true);
  148. }
  149. OnSelectedChanged ();
  150. }
  151. }
  152. }
  153. /// <summary>Gets or sets the <see cref="IListDataSource"/> backing this <see cref="ComboBox"/>, enabling custom rendering.</summary>
  154. /// <value>The source.</value>
  155. /// <remarks>Use <see cref="SetSource{T}"/> to set a new <see cref="ObservableCollection{T}"/> source.</remarks>
  156. public IListDataSource Source
  157. {
  158. get => _source;
  159. set
  160. {
  161. _source = value;
  162. // Only need to refresh list if its been added to a container view
  163. if (SuperView is { } && SuperView.Subviews.Contains (this))
  164. {
  165. Text = string.Empty;
  166. SetNeedsDisplay ();
  167. }
  168. }
  169. }
  170. /// <summary>The text of the currently selected list item</summary>
  171. public new string Text
  172. {
  173. get => _text;
  174. set => SetSearchText (value);
  175. }
  176. /// <summary>
  177. /// Collapses the drop-down list. Returns true if the state changed or false if it was already collapsed and no
  178. /// action was taken
  179. /// </summary>
  180. public virtual bool Collapse ()
  181. {
  182. if (!IsShow)
  183. {
  184. return false;
  185. }
  186. IsShow = false;
  187. HideList ();
  188. return true;
  189. }
  190. /// <summary>This event is raised when the drop-down list is collapsed.</summary>
  191. public event EventHandler Collapsed;
  192. /// <summary>
  193. /// Expands the drop-down list. Returns true if the state changed or false if it was already expanded and no
  194. /// action was taken
  195. /// </summary>
  196. public virtual bool Expand ()
  197. {
  198. if (IsShow)
  199. {
  200. return false;
  201. }
  202. SetSearchSet ();
  203. IsShow = true;
  204. ShowList ();
  205. FocusSelectedItem ();
  206. return true;
  207. }
  208. /// <summary>This event is raised when the drop-down list is expanded.</summary>
  209. public event EventHandler Expanded;
  210. /// <inheritdoc/>
  211. protected internal override bool OnMouseEvent (MouseEvent me)
  212. {
  213. if (me.Position.X == Viewport.Right - 1
  214. && me.Position.Y == Viewport.Top
  215. && me.Flags == MouseFlags.Button1Pressed
  216. && _autoHide)
  217. {
  218. if (IsShow)
  219. {
  220. IsShow = false;
  221. HideList ();
  222. }
  223. else
  224. {
  225. SetSearchSet ();
  226. IsShow = true;
  227. ShowList ();
  228. FocusSelectedItem ();
  229. }
  230. return me.Handled = true;
  231. }
  232. if (me.Flags == MouseFlags.Button1Pressed)
  233. {
  234. if (!_search.HasFocus)
  235. {
  236. _search.SetFocus ();
  237. }
  238. return me.Handled = true;
  239. }
  240. return false;
  241. }
  242. /// <summary>Virtual method which invokes the <see cref="Collapsed"/> event.</summary>
  243. public virtual void OnCollapsed () { Collapsed?.Invoke (this, EventArgs.Empty); }
  244. /// <inheritdoc/>
  245. public override void OnDrawContent (Rectangle viewport)
  246. {
  247. base.OnDrawContent (viewport);
  248. if (!_autoHide)
  249. {
  250. return;
  251. }
  252. Driver.SetAttribute (ColorScheme.Focus);
  253. Move (Viewport.Right - 1, 0);
  254. Driver.AddRune (Glyphs.DownArrow);
  255. }
  256. /// <summary>Virtual method which invokes the <see cref="Expanded"/> event.</summary>
  257. public virtual void OnExpanded () { Expanded?.Invoke (this, EventArgs.Empty); }
  258. /// <inheritdoc/>
  259. protected override void OnHasFocusChanged (bool newHasFocus, View previousFocusedView, View view)
  260. {
  261. if (newHasFocus)
  262. {
  263. if (!_search.HasFocus && !_listview.HasFocus)
  264. {
  265. _search.SetFocus ();
  266. }
  267. _search.CursorPosition = _search.Text.GetRuneCount ();
  268. }
  269. else
  270. {
  271. if (_source?.Count > 0
  272. && _selectedItem > -1
  273. && _selectedItem < _source.Count - 1
  274. && _text != _source.ToList () [_selectedItem].ToString ())
  275. {
  276. SetValue (_source.ToList () [_selectedItem].ToString ());
  277. }
  278. if (_autoHide && IsShow && view != this && view != _search && view != _listview)
  279. {
  280. IsShow = false;
  281. HideList ();
  282. }
  283. else if (_listview.TabStop?.HasFlag (TabBehavior.TabStop) ?? false)
  284. {
  285. _listview.TabStop = TabBehavior.NoStop;
  286. }
  287. }
  288. }
  289. /// <summary>Invokes the OnOpenSelectedItem event if it is defined.</summary>
  290. /// <returns></returns>
  291. public virtual bool OnOpenSelectedItem ()
  292. {
  293. string value = _search.Text;
  294. _lastSelectedItem = SelectedItem;
  295. OpenSelectedItem?.Invoke (this, new ListViewItemEventArgs (SelectedItem, value));
  296. return true;
  297. }
  298. /// <summary>Invokes the SelectedChanged event if it is defined.</summary>
  299. /// <returns></returns>
  300. public virtual bool OnSelectedChanged ()
  301. {
  302. // Note: Cannot rely on "listview.SelectedItem != lastSelectedItem" because the list is dynamic.
  303. // So we cannot optimize. Ie: Don't call if not changed
  304. SelectedItemChanged?.Invoke (this, new ListViewItemEventArgs (SelectedItem, _search.Text));
  305. return true;
  306. }
  307. /// <summary>This event is raised when the user Double Clicks on an item or presses ENTER to open the selected item.</summary>
  308. public event EventHandler<ListViewItemEventArgs> OpenSelectedItem;
  309. /// <summary>This event is raised when the selected item in the <see cref="ComboBox"/> has changed.</summary>
  310. public event EventHandler<ListViewItemEventArgs> SelectedItemChanged;
  311. /// <summary>Sets the source of the <see cref="ComboBox"/> to an <see cref="ObservableCollection{T}"/>.</summary>
  312. /// <value>An object implementing the INotifyCollectionChanged and INotifyPropertyChanged interface.</value>
  313. /// <remarks>
  314. /// Use the <see cref="Source"/> property to set a new <see cref="IListDataSource"/> source and use custom
  315. /// rendering.
  316. /// </remarks>
  317. public void SetSource<T> (ObservableCollection<T> source)
  318. {
  319. if (source is null)
  320. {
  321. Source = null;
  322. }
  323. else
  324. {
  325. _listview.SetSource<T> (source);
  326. Source = _listview.Source;
  327. }
  328. }
  329. private bool ActivateSelected ()
  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. 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 Accept Command (Enter)
  558. void Search_Accept (object sender, HandledEventArgs e) { e.Handled = true; }
  559. private void Search_Changed (object sender, EventArgs e)
  560. {
  561. if (_source is null)
  562. {
  563. // Object initialization
  564. return;
  565. }
  566. ShowHideList (Text);
  567. }
  568. private void ShowHideList (string oldText)
  569. {
  570. if (string.IsNullOrEmpty (_search.Text) && string.IsNullOrEmpty (oldText))
  571. {
  572. ResetSearchSet ();
  573. }
  574. else if (_search.Text != oldText)
  575. {
  576. if (_search.Text.Length < oldText.Length)
  577. {
  578. _selectedItem = -1;
  579. }
  580. IsShow = true;
  581. ResetSearchSet (true);
  582. if (!string.IsNullOrEmpty (_search.Text))
  583. {
  584. _listview.SuspendCollectionChangedEvent ();
  585. foreach (object item in _source.ToList ())
  586. {
  587. // Iterate to preserver object type and force deep copy
  588. if (item.ToString ()
  589. .StartsWith (
  590. _search.Text,
  591. StringComparison.CurrentCultureIgnoreCase
  592. ))
  593. {
  594. _searchSet.Add (item);
  595. }
  596. }
  597. _listview.ResumeSuspendCollectionChangedEvent ();
  598. }
  599. }
  600. if (HasFocus)
  601. {
  602. ShowList ();
  603. }
  604. else if (_autoHide)
  605. {
  606. IsShow = false;
  607. HideList ();
  608. }
  609. }
  610. private void Selected ()
  611. {
  612. IsShow = false;
  613. _listview.TabStop = TabBehavior.NoStop;
  614. if (_listview.Source.Count == 0 || (_searchSet?.Count ?? 0) == 0)
  615. {
  616. _text = "";
  617. HideList ();
  618. IsShow = false;
  619. return;
  620. }
  621. SetValue (_listview.SelectedItem > -1 ? _searchSet [_listview.SelectedItem] : _text);
  622. _search.CursorPosition = _search.Text.GetColumns ();
  623. ShowHideList (Text);
  624. OnOpenSelectedItem ();
  625. Reset (true);
  626. HideList ();
  627. IsShow = false;
  628. }
  629. private void SetSearchSet ()
  630. {
  631. if (Source is null)
  632. {
  633. return;
  634. }
  635. // PERF: At the request of @dodexahedron in the comment https://github.com/gui-cs/Terminal.Gui/pull/3552#discussion_r1648112410.
  636. _listview.SuspendCollectionChangedEvent ();
  637. // force deep copy
  638. foreach (object item in Source.ToList ())
  639. {
  640. _searchSet.Add (item);
  641. }
  642. _listview.ResumeSuspendCollectionChangedEvent ();
  643. }
  644. // Sets the search text field Text as well as our own Text property
  645. private void SetSearchText (string value)
  646. {
  647. _search.Text = value;
  648. _text = value;
  649. }
  650. private void SetValue (object text, bool isFromSelectedItem = false)
  651. {
  652. // TOOD: The fact we have to suspend events to change the text makes this feel very hacky.
  653. _search.TextChanged -= Search_Changed;
  654. // Note we set _text, to avoid set_Text from setting _search.Text again
  655. _text = _search.Text = text.ToString ();
  656. _search.CursorPosition = 0;
  657. _search.TextChanged += Search_Changed;
  658. if (!isFromSelectedItem)
  659. {
  660. _selectedItem = GetSelectedItemFromSource (_text);
  661. OnSelectedChanged ();
  662. }
  663. }
  664. /// <summary>Show the search list</summary>
  665. /// Consider making public
  666. private void ShowList ()
  667. {
  668. _listview.SuspendCollectionChangedEvent ();
  669. _listview.SetSource (_searchSet);
  670. _listview.ResumeSuspendCollectionChangedEvent ();
  671. _listview.Clear ();
  672. _listview.Height = CalculateHeight ();
  673. SuperView?.MoveSubviewToStart (this);
  674. }
  675. private bool UnixEmulation ()
  676. {
  677. // Unix emulation
  678. Reset ();
  679. return true;
  680. }
  681. private class ComboListView : ListView
  682. {
  683. private ComboBox _container;
  684. private bool _hideDropdownListOnClick;
  685. private int _highlighted = -1;
  686. private bool _isFocusing;
  687. public ComboListView (ComboBox container, bool hideDropdownListOnClick) { SetInitialProperties (container, hideDropdownListOnClick); }
  688. public ComboListView (ComboBox container, ObservableCollection<string> source, bool hideDropdownListOnClick)
  689. {
  690. Source = new ListWrapper<string> (source);
  691. SetInitialProperties (container, hideDropdownListOnClick);
  692. }
  693. public bool HideDropdownListOnClick
  694. {
  695. get => _hideDropdownListOnClick;
  696. set => _hideDropdownListOnClick = WantContinuousButtonPressed = value;
  697. }
  698. // BUGBUG: OnMouseEvent is internal!
  699. protected internal override bool OnMouseEvent (MouseEvent me)
  700. {
  701. var res = false;
  702. bool isMousePositionValid = IsMousePositionValid (me);
  703. if (isMousePositionValid)
  704. {
  705. res = base.OnMouseEvent (me);
  706. }
  707. if (HideDropdownListOnClick && me.Flags == MouseFlags.Button1Clicked)
  708. {
  709. if (!isMousePositionValid && !_isFocusing)
  710. {
  711. _container.IsShow = false;
  712. _container.HideList ();
  713. }
  714. else if (isMousePositionValid)
  715. {
  716. OnOpenSelectedItem ();
  717. }
  718. else
  719. {
  720. _isFocusing = false;
  721. }
  722. return true;
  723. }
  724. if (me.Flags == MouseFlags.ReportMousePosition && HideDropdownListOnClick)
  725. {
  726. if (isMousePositionValid)
  727. {
  728. _highlighted = Math.Min (TopItem + me.Position.Y, Source.Count);
  729. SetNeedsDisplay ();
  730. }
  731. _isFocusing = false;
  732. return true;
  733. }
  734. return res;
  735. }
  736. public override void OnDrawContent (Rectangle viewport)
  737. {
  738. Attribute current = ColorScheme.Focus;
  739. Driver.SetAttribute (current);
  740. Move (0, 0);
  741. Rectangle f = Frame;
  742. int item = TopItem;
  743. bool focused = HasFocus;
  744. int col = AllowsMarking ? 2 : 0;
  745. int start = LeftItem;
  746. for (var row = 0; row < f.Height; row++, item++)
  747. {
  748. bool isSelected = item == _container.SelectedItem;
  749. bool isHighlighted = _hideDropdownListOnClick && item == _highlighted;
  750. Attribute newcolor;
  751. if (isHighlighted || (isSelected && !_hideDropdownListOnClick))
  752. {
  753. newcolor = focused ? ColorScheme.Focus : ColorScheme.HotNormal;
  754. }
  755. else if (isSelected && _hideDropdownListOnClick)
  756. {
  757. newcolor = focused ? ColorScheme.HotFocus : ColorScheme.HotNormal;
  758. }
  759. else
  760. {
  761. newcolor = focused ? GetNormalColor () : GetNormalColor ();
  762. }
  763. if (newcolor != current)
  764. {
  765. Driver.SetAttribute (newcolor);
  766. current = newcolor;
  767. }
  768. Move (0, row);
  769. if (Source is null || item >= Source.Count)
  770. {
  771. for (var c = 0; c < f.Width; c++)
  772. {
  773. Driver.AddRune ((Rune)' ');
  774. }
  775. }
  776. else
  777. {
  778. var rowEventArgs = new ListViewRowEventArgs (item);
  779. OnRowRender (rowEventArgs);
  780. if (rowEventArgs.RowAttribute is { } && current != rowEventArgs.RowAttribute)
  781. {
  782. current = (Attribute)rowEventArgs.RowAttribute;
  783. Driver.SetAttribute (current);
  784. }
  785. if (AllowsMarking)
  786. {
  787. Driver.AddRune (
  788. Source.IsMarked (item) ? AllowsMultipleSelection ? Glyphs.CheckStateChecked : Glyphs.Selected :
  789. AllowsMultipleSelection ? Glyphs.CheckStateUnChecked : Glyphs.UnSelected
  790. );
  791. Driver.AddRune ((Rune)' ');
  792. }
  793. Source.Render (this, Driver, isSelected, item, col, row, f.Width - col, start);
  794. }
  795. }
  796. }
  797. protected override void OnHasFocusChanged (bool newHasFocus, [CanBeNull] View previousFocusedView, [CanBeNull] View focusedVew)
  798. {
  799. if (newHasFocus)
  800. {
  801. if (_hideDropdownListOnClick)
  802. {
  803. _isFocusing = true;
  804. _highlighted = _container.SelectedItem;
  805. Application.GrabMouse (this);
  806. }
  807. }
  808. else
  809. {
  810. if (_hideDropdownListOnClick)
  811. {
  812. _isFocusing = false;
  813. _highlighted = _container.SelectedItem;
  814. Application.UngrabMouse ();
  815. }
  816. }
  817. }
  818. public override bool OnSelectedChanged ()
  819. {
  820. bool res = base.OnSelectedChanged ();
  821. _highlighted = SelectedItem;
  822. return res;
  823. }
  824. private bool IsMousePositionValid (MouseEvent me)
  825. {
  826. if (me.Position.X >= 0 && me.Position.X < Frame.Width && me.Position.Y >= 0 && me.Position.Y < Frame.Height)
  827. {
  828. return true;
  829. }
  830. return false;
  831. }
  832. private void SetInitialProperties (ComboBox container, bool hideDropdownListOnClick)
  833. {
  834. _container = container
  835. ?? throw new ArgumentNullException (
  836. nameof (container),
  837. "ComboBox container cannot be null."
  838. );
  839. HideDropdownListOnClick = hideDropdownListOnClick;
  840. AddCommand (Command.Up, () => _container.MoveUpList ());
  841. }
  842. }
  843. /// <inheritdoc />
  844. public bool EnableForDesign ()
  845. {
  846. var source = new ObservableCollection<string> (["Combo Item 1", "Combo Item two", "Combo Item Quattro", "Last Combo Item"]);
  847. SetSource (source);
  848. Height = Dim.Auto (DimAutoStyle.Content, minimumContentDim: source.Count + 1);
  849. return true;
  850. }
  851. }