ComboBox.cs 30 KB

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