ComboBox.cs 30 KB

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