ComboBox.cs 30 KB

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