ComboBox.cs 30 KB

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