ComboBox.cs 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  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 (!HideDropdownListOnClick && _searchSet.Count > 0)
  43. {
  44. SetValue (_searchSet [_listview.SelectedItem]);
  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 ()
  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. _listview.SelectedItem = SelectedItem > -1 ? SelectedItem : 0;
  395. _listview.TabStop = TabBehavior.TabStop;
  396. _listview.SetFocus ();
  397. OnExpanded ();
  398. }
  399. private int GetSelectedItemFromSource (string searchText)
  400. {
  401. if (_source is null)
  402. {
  403. return -1;
  404. }
  405. for (var i = 0; i < _searchSet.Count; i++)
  406. {
  407. if (_searchSet [i].ToString () == searchText)
  408. {
  409. return i;
  410. }
  411. }
  412. return -1;
  413. }
  414. private bool HasItems () { return Source?.Count > 0; }
  415. /// <summary>Hide the search list</summary>
  416. /// Consider making public
  417. private void HideList ()
  418. {
  419. if (_lastSelectedItem != _selectedItem)
  420. {
  421. OnOpenSelectedItem ();
  422. }
  423. Reset (true);
  424. _listview.ClearViewport (null);
  425. _listview.TabStop = TabBehavior.NoStop;
  426. SuperView?.MoveSubViewToStart (this);
  427. // BUGBUG: SetNeedsDraw takes Viewport relative coordinates, not Screen
  428. Rectangle rect = _listview.ViewportToScreen (_listview.IsInitialized ? _listview.Viewport : Rectangle.Empty);
  429. SuperView?.SetNeedsDraw (rect);
  430. OnCollapsed ();
  431. }
  432. private bool? MoveDown ()
  433. {
  434. if (_search.HasFocus)
  435. {
  436. // jump to list
  437. if (_searchSet?.Count > 0)
  438. {
  439. _listview.TabStop = TabBehavior.TabStop;
  440. _listview.SetFocus ();
  441. if (_listview.SelectedItem > -1)
  442. {
  443. SetValue (_searchSet [_listview.SelectedItem]);
  444. }
  445. else
  446. {
  447. _listview.SelectedItem = 0;
  448. }
  449. }
  450. else
  451. {
  452. return false;
  453. }
  454. return true;
  455. }
  456. return null;
  457. }
  458. private bool? MoveEnd ()
  459. {
  460. if (!IsShow && _search.HasFocus)
  461. {
  462. return null;
  463. }
  464. if (HasItems ())
  465. {
  466. _listview.MoveEnd ();
  467. }
  468. return true;
  469. }
  470. private bool? MoveHome ()
  471. {
  472. if (!IsShow && _search.HasFocus)
  473. {
  474. return null;
  475. }
  476. if (HasItems ())
  477. {
  478. _listview.MoveHome ();
  479. }
  480. return true;
  481. }
  482. private bool? MoveUp ()
  483. {
  484. if (HasItems ())
  485. {
  486. return _listview.MoveUp ();
  487. }
  488. return false;
  489. }
  490. private bool? MoveUpList ()
  491. {
  492. if (_listview.HasFocus && _listview.SelectedItem == 0 && _searchSet?.Count > 0) // jump back to search
  493. {
  494. _search.CursorPosition = _search.Text.GetRuneCount ();
  495. _search.SetFocus ();
  496. }
  497. else
  498. {
  499. MoveUp ();
  500. }
  501. return true;
  502. }
  503. private bool PageDown ()
  504. {
  505. if (HasItems ())
  506. {
  507. _listview.MovePageDown ();
  508. }
  509. return true;
  510. }
  511. private bool PageUp ()
  512. {
  513. if (HasItems ())
  514. {
  515. _listview.MovePageUp ();
  516. }
  517. return true;
  518. }
  519. // TODO: Upgrade Combobox to use Dim.Auto instead of all this stuff.
  520. private void ProcessLayout ()
  521. {
  522. if (Viewport.Height < _minimumHeight && (Height is null || Height is DimAbsolute))
  523. {
  524. Height = _minimumHeight;
  525. }
  526. // BUGBUG: This uses Viewport. Should use ContentSize
  527. if ((!_autoHide && Viewport.Width > 0 && _search.Frame.Width != Viewport.Width)
  528. || (_autoHide && Viewport.Width > 0 && _search.Frame.Width != Viewport.Width - 1))
  529. {
  530. _search.Width = _listview.Width = _autoHide ? Viewport.Width - 1 : Viewport.Width;
  531. _listview.Height = CalculateHeight ();
  532. _search.SetRelativeLayout (GetContentSize ());
  533. _listview.SetRelativeLayout (GetContentSize ());
  534. }
  535. }
  536. /// <summary>Reset to full original list</summary>
  537. private void Reset (bool keepSearchText = false)
  538. {
  539. if (!keepSearchText)
  540. {
  541. SetSearchText (string.Empty);
  542. }
  543. ResetSearchSet ();
  544. _listview.SetSource (_searchSet);
  545. _listview.Height = CalculateHeight ();
  546. if (SubViews.Count > 0 && HasFocus)
  547. {
  548. _search.SetFocus ();
  549. }
  550. }
  551. private void ResetSearchSet (bool noCopy = false)
  552. {
  553. _listview.SuspendCollectionChangedEvent ();
  554. _searchSet.Clear ();
  555. _listview.ResumeSuspendCollectionChangedEvent ();
  556. if (_autoHide || noCopy)
  557. {
  558. return;
  559. }
  560. SetSearchSet ();
  561. }
  562. private void Search_Changed (object sender, EventArgs e)
  563. {
  564. if (_source is null)
  565. {
  566. // Object initialization
  567. return;
  568. }
  569. ShowHideList (Text);
  570. }
  571. private void ShowHideList (string oldText)
  572. {
  573. if (string.IsNullOrEmpty (_search.Text) && string.IsNullOrEmpty (oldText))
  574. {
  575. ResetSearchSet ();
  576. }
  577. else if (_search.Text != oldText)
  578. {
  579. if (_search.Text.Length < oldText.Length)
  580. {
  581. _selectedItem = -1;
  582. }
  583. IsShow = true;
  584. ResetSearchSet (true);
  585. if (!string.IsNullOrEmpty (_search.Text))
  586. {
  587. _listview.SuspendCollectionChangedEvent ();
  588. foreach (object item in _source.ToList ())
  589. {
  590. // Iterate to preserver object type and force deep copy
  591. if (item.ToString ()
  592. .StartsWith (
  593. _search.Text,
  594. StringComparison.CurrentCultureIgnoreCase
  595. ))
  596. {
  597. _searchSet.Add (item);
  598. }
  599. }
  600. _listview.ResumeSuspendCollectionChangedEvent ();
  601. }
  602. }
  603. if (HasFocus)
  604. {
  605. ShowList ();
  606. }
  607. else if (_autoHide)
  608. {
  609. IsShow = false;
  610. HideList ();
  611. }
  612. }
  613. private bool SelectText ()
  614. {
  615. IsShow = false;
  616. _listview.TabStop = TabBehavior.NoStop;
  617. if (_listview.Source.Count == 0 || (_searchSet?.Count ?? 0) == 0)
  618. {
  619. _text = "";
  620. HideList ();
  621. IsShow = false;
  622. return false;
  623. }
  624. SetValue (_listview.SelectedItem > -1 ? _searchSet [_listview.SelectedItem] : _text);
  625. _search.CursorPosition = _search.Text.GetColumns ();
  626. ShowHideList (Text);
  627. OnOpenSelectedItem ();
  628. Reset (true);
  629. HideList ();
  630. IsShow = false;
  631. return true;
  632. }
  633. private void SetSearchSet ()
  634. {
  635. if (Source is null)
  636. {
  637. return;
  638. }
  639. // PERF: At the request of @dodexahedron in the comment https://github.com/gui-cs/Terminal.Gui/pull/3552#discussion_r1648112410.
  640. _listview.SuspendCollectionChangedEvent ();
  641. // force deep copy
  642. foreach (object item in Source.ToList ())
  643. {
  644. _searchSet.Add (item);
  645. }
  646. _listview.ResumeSuspendCollectionChangedEvent ();
  647. }
  648. // Sets the search text field Text as well as our own Text property
  649. private void SetSearchText (string value)
  650. {
  651. _search.Text = value;
  652. _text = value;
  653. }
  654. private void SetValue (object text, bool isFromSelectedItem = false)
  655. {
  656. // TOOD: The fact we have to suspend events to change the text makes this feel very hacky.
  657. _search.TextChanged -= Search_Changed;
  658. // Note we set _text, to avoid set_Text from setting _search.Text again
  659. _text = _search.Text = text.ToString ();
  660. _search.CursorPosition = 0;
  661. _search.TextChanged += Search_Changed;
  662. if (!isFromSelectedItem)
  663. {
  664. _selectedItem = GetSelectedItemFromSource (_text);
  665. OnSelectedChanged ();
  666. }
  667. }
  668. /// <summary>Show the search list</summary>
  669. /// Consider making public
  670. private void ShowList ()
  671. {
  672. _listview.SuspendCollectionChangedEvent ();
  673. _listview.SetSource (_searchSet);
  674. _listview.ResumeSuspendCollectionChangedEvent ();
  675. _listview.ClearViewport (null);
  676. _listview.Height = CalculateHeight ();
  677. SuperView?.MoveSubViewToStart (this);
  678. }
  679. private bool UnixEmulation ()
  680. {
  681. // Unix emulation
  682. Reset ();
  683. return true;
  684. }
  685. private class ComboListView : ListView
  686. {
  687. private ComboBox _container;
  688. private bool _hideDropdownListOnClick;
  689. private int _highlighted = -1;
  690. private bool _isFocusing;
  691. public ComboListView (ComboBox container, bool hideDropdownListOnClick) { SetInitialProperties (container, hideDropdownListOnClick); }
  692. public ComboListView (ComboBox container, ObservableCollection<string> source, bool hideDropdownListOnClick)
  693. {
  694. Source = new ListWrapper<string> (source);
  695. SetInitialProperties (container, hideDropdownListOnClick);
  696. }
  697. public bool HideDropdownListOnClick
  698. {
  699. get => _hideDropdownListOnClick;
  700. set => _hideDropdownListOnClick = WantContinuousButtonPressed = value;
  701. }
  702. protected override bool OnMouseEvent (MouseEventArgs me)
  703. {
  704. bool isMousePositionValid = IsMousePositionValid (me);
  705. var res = false;
  706. if (isMousePositionValid)
  707. {
  708. // We're derived from ListView and it overrides OnMouseEvent, so we need to call it
  709. res = base.OnMouseEvent (me);
  710. }
  711. if (HideDropdownListOnClick && me.Flags == MouseFlags.Button1Clicked)
  712. {
  713. if (!isMousePositionValid && !_isFocusing)
  714. {
  715. _container.IsShow = false;
  716. _container.HideList ();
  717. }
  718. else if (isMousePositionValid)
  719. {
  720. OnOpenSelectedItem ();
  721. }
  722. else
  723. {
  724. _isFocusing = false;
  725. }
  726. return true;
  727. }
  728. if (me.Flags == MouseFlags.ReportMousePosition && HideDropdownListOnClick)
  729. {
  730. if (isMousePositionValid)
  731. {
  732. _highlighted = Math.Min (TopItem + me.Position.Y, Source.Count);
  733. SetNeedsDraw ();
  734. }
  735. _isFocusing = false;
  736. return true;
  737. }
  738. return res;
  739. }
  740. protected override bool OnDrawingContent ()
  741. {
  742. Attribute current = GetAttributeForRole (VisualRole.Focus);
  743. SetAttribute (current);
  744. Move (0, 0);
  745. Rectangle f = Frame;
  746. int item = TopItem;
  747. bool focused = HasFocus;
  748. int col = AllowsMarking ? 2 : 0;
  749. int start = LeftItem;
  750. for (var row = 0; row < f.Height; row++, item++)
  751. {
  752. bool isSelected = item == _container.SelectedItem;
  753. bool isHighlighted = _hideDropdownListOnClick && item == _highlighted;
  754. Attribute newcolor;
  755. if (isHighlighted || (isSelected && !_hideDropdownListOnClick))
  756. {
  757. newcolor = focused ? GetAttributeForRole (VisualRole.Focus) : GetAttributeForRole (VisualRole.HotNormal);
  758. }
  759. else if (isSelected && _hideDropdownListOnClick)
  760. {
  761. newcolor = focused ? GetAttributeForRole (VisualRole.HotFocus) : GetAttributeForRole (VisualRole.HotNormal);
  762. }
  763. else
  764. {
  765. newcolor = GetAttributeForRole (VisualRole.Normal);
  766. }
  767. if (newcolor != current)
  768. {
  769. SetAttribute (newcolor);
  770. current = newcolor;
  771. }
  772. Move (0, row);
  773. if (Source is null || item >= Source.Count)
  774. {
  775. for (var c = 0; c < f.Width; c++)
  776. {
  777. AddRune (0, row, (Rune)' ');
  778. }
  779. }
  780. else
  781. {
  782. var rowEventArgs = new ListViewRowEventArgs (item);
  783. OnRowRender (rowEventArgs);
  784. if (rowEventArgs.RowAttribute is { } && current != rowEventArgs.RowAttribute)
  785. {
  786. current = (Attribute)rowEventArgs.RowAttribute;
  787. SetAttribute (current);
  788. }
  789. if (AllowsMarking)
  790. {
  791. AddRune (
  792. Source.IsMarked (item) ? AllowsMultipleSelection ? Glyphs.CheckStateChecked : Glyphs.Selected :
  793. AllowsMultipleSelection ? Glyphs.CheckStateUnChecked : Glyphs.UnSelected
  794. );
  795. AddRune ((Rune)' ');
  796. }
  797. Source.Render (this, isSelected, item, col, row, f.Width - col, start);
  798. }
  799. }
  800. return true;
  801. }
  802. protected override void OnHasFocusChanged (bool newHasFocus, [CanBeNull] View previousFocusedView, [CanBeNull] View focusedView)
  803. {
  804. if (newHasFocus)
  805. {
  806. if (_hideDropdownListOnClick)
  807. {
  808. _isFocusing = true;
  809. _highlighted = _container.SelectedItem;
  810. Application.Mouse.GrabMouse (this);
  811. }
  812. }
  813. else
  814. {
  815. if (_hideDropdownListOnClick)
  816. {
  817. _isFocusing = false;
  818. _highlighted = _container.SelectedItem;
  819. Application.Mouse.UngrabMouse ();
  820. }
  821. }
  822. }
  823. public override bool OnSelectedChanged ()
  824. {
  825. bool res = base.OnSelectedChanged ();
  826. _highlighted = SelectedItem;
  827. return res;
  828. }
  829. private bool IsMousePositionValid (MouseEventArgs me)
  830. {
  831. if (me.Position.X >= 0 && me.Position.X < Frame.Width && me.Position.Y >= 0 && me.Position.Y < Frame.Height)
  832. {
  833. return true;
  834. }
  835. return false;
  836. }
  837. private void SetInitialProperties (ComboBox container, bool hideDropdownListOnClick)
  838. {
  839. _container = container
  840. ?? throw new ArgumentNullException (
  841. nameof (container),
  842. "ComboBox container cannot be null."
  843. );
  844. HideDropdownListOnClick = hideDropdownListOnClick;
  845. AddCommand (Command.Up, () => _container.MoveUpList ());
  846. }
  847. }
  848. /// <inheritdoc />
  849. public bool EnableForDesign ()
  850. {
  851. var source = new ObservableCollection<string> (["Combo Item 1", "Combo Item two", "Combo Item Quattro", "Last Combo Item"]);
  852. SetSource (source);
  853. Height = Dim.Auto (DimAutoStyle.Content, minimumContentDim: source.Count + 1);
  854. return true;
  855. }
  856. }