ComboBox.cs 29 KB

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