ListView.cs 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  1. using System.Collections;
  2. namespace Terminal.Gui;
  3. /// <summary>Implement <see cref="IListDataSource"/> to provide custom rendering for a <see cref="ListView"/>.</summary>
  4. public interface IListDataSource
  5. {
  6. /// <summary>Returns the number of elements to display</summary>
  7. int Count { get; }
  8. /// <summary>Returns the maximum length of elements to display</summary>
  9. int Length { get; }
  10. /// <summary>Should return whether the specified item is currently marked.</summary>
  11. /// <returns><see langword="true"/>, if marked, <see langword="false"/> otherwise.</returns>
  12. /// <param name="item">Item index.</param>
  13. bool IsMarked (int item);
  14. /// <summary>This method is invoked to render a specified item, the method should cover the entire provided width.</summary>
  15. /// <returns>The render.</returns>
  16. /// <param name="container">The list view to render.</param>
  17. /// <param name="driver">The console driver to render.</param>
  18. /// <param name="selected">Describes whether the item being rendered is currently selected by the user.</param>
  19. /// <param name="item">The index of the item to render, zero for the first item and so on.</param>
  20. /// <param name="col">The column where the rendering will start</param>
  21. /// <param name="line">The line where the rendering will be done.</param>
  22. /// <param name="width">The width that must be filled out.</param>
  23. /// <param name="start">The index of the string to be displayed.</param>
  24. /// <remarks>
  25. /// The default color will be set before this method is invoked, and will be based on whether the item is selected
  26. /// or not.
  27. /// </remarks>
  28. void Render (
  29. ListView container,
  30. ConsoleDriver driver,
  31. bool selected,
  32. int item,
  33. int col,
  34. int line,
  35. int width,
  36. int start = 0
  37. );
  38. /// <summary>Flags the item as marked.</summary>
  39. /// <param name="item">Item index.</param>
  40. /// <param name="value">If set to <see langword="true"/> value.</param>
  41. void SetMark (int item, bool value);
  42. /// <summary>Return the source as IList.</summary>
  43. /// <returns></returns>
  44. IList ToList ();
  45. }
  46. /// <summary>
  47. /// ListView <see cref="View"/> renders a scrollable list of data where each item can be activated to perform an
  48. /// action.
  49. /// </summary>
  50. /// <remarks>
  51. /// <para>
  52. /// The <see cref="ListView"/> displays lists of data and allows the user to scroll through the data. Items in
  53. /// the can be activated firing an event (with the ENTER key or a mouse double-click). If the
  54. /// <see cref="AllowsMarking"/> property is true, elements of the list can be marked by the user.
  55. /// </para>
  56. /// <para>
  57. /// By default <see cref="ListView"/> uses <see cref="object.ToString"/> to render the items of any
  58. /// <see cref="IList"/> object (e.g. arrays, <see cref="List{T}"/>, and other collections). Alternatively, an
  59. /// object that implements <see cref="IListDataSource"/> can be provided giving full control of what is rendered.
  60. /// </para>
  61. /// <para>
  62. /// <see cref="ListView"/> can display any object that implements the <see cref="IList"/> interface.
  63. /// <see cref="string"/> values are converted into <see cref="string"/> values before rendering, and other values
  64. /// are converted into <see cref="string"/> by calling <see cref="object.ToString"/> and then converting to
  65. /// <see cref="string"/> .
  66. /// </para>
  67. /// <para>
  68. /// To change the contents of the ListView, set the <see cref="Source"/> property (when providing custom
  69. /// rendering via <see cref="IListDataSource"/>) or call <see cref="SetSource"/> an <see cref="IList"/> is being
  70. /// used.
  71. /// </para>
  72. /// <para>
  73. /// When <see cref="AllowsMarking"/> is set to true the rendering will prefix the rendered items with [x] or [ ]
  74. /// and bind the SPACE key to toggle the selection. To implement a different marking style set
  75. /// <see cref="AllowsMarking"/> to false and implement custom rendering.
  76. /// </para>
  77. /// <para>
  78. /// Searching the ListView with the keyboard is supported. Users type the first characters of an item, and the
  79. /// first item that starts with what the user types will be selected.
  80. /// </para>
  81. /// </remarks>
  82. public class ListView : View
  83. {
  84. private bool _allowsMarking;
  85. private bool _allowsMultipleSelection = true;
  86. private int _lastSelectedItem = -1;
  87. private int _selected = -1;
  88. private IListDataSource _source;
  89. private int _top, _left;
  90. /// <summary>
  91. /// Initializes a new instance of <see cref="ListView"/>. Set the <see cref="Source"/> property to display
  92. /// something.
  93. /// </summary>
  94. public ListView ()
  95. {
  96. CanFocus = true;
  97. // Things this view knows how to do
  98. AddCommand (Command.LineUp, () => MoveUp ());
  99. AddCommand (Command.LineDown, () => MoveDown ());
  100. AddCommand (Command.ScrollUp, () => ScrollUp (1));
  101. AddCommand (Command.ScrollDown, () => ScrollDown (1));
  102. AddCommand (Command.PageUp, () => MovePageUp ());
  103. AddCommand (Command.PageDown, () => MovePageDown ());
  104. AddCommand (Command.TopHome, () => MoveHome ());
  105. AddCommand (Command.BottomEnd, () => MoveEnd ());
  106. AddCommand (Command.OpenSelectedItem, () => OnOpenSelectedItem ());
  107. AddCommand (Command.ToggleChecked, () => MarkUnmarkRow ());
  108. // Default keybindings for all ListViews
  109. KeyBindings.Add (KeyCode.CursorUp, Command.LineUp);
  110. KeyBindings.Add (KeyCode.P | KeyCode.CtrlMask, Command.LineUp);
  111. KeyBindings.Add (KeyCode.CursorDown, Command.LineDown);
  112. KeyBindings.Add (KeyCode.N | KeyCode.CtrlMask, Command.LineDown);
  113. KeyBindings.Add (KeyCode.PageUp, Command.PageUp);
  114. KeyBindings.Add (KeyCode.PageDown, Command.PageDown);
  115. KeyBindings.Add (KeyCode.V | KeyCode.CtrlMask, Command.PageDown);
  116. KeyBindings.Add (KeyCode.Home, Command.TopHome);
  117. KeyBindings.Add (KeyCode.End, Command.BottomEnd);
  118. KeyBindings.Add (KeyCode.Enter, Command.OpenSelectedItem);
  119. }
  120. /// <summary>Gets or sets whether this <see cref="ListView"/> allows items to be marked.</summary>
  121. /// <value>Set to <see langword="true"/> to allow marking elements of the list.</value>
  122. /// <remarks>
  123. /// If set to <see langword="true"/>, <see cref="ListView"/> will render items marked items with "[x]", and
  124. /// unmarked items with "[ ]" spaces. SPACE key will toggle marking. The default is <see langword="false"/>.
  125. /// </remarks>
  126. public bool AllowsMarking
  127. {
  128. get => _allowsMarking;
  129. set
  130. {
  131. _allowsMarking = value;
  132. if (_allowsMarking)
  133. {
  134. KeyBindings.Add (KeyCode.Space, Command.ToggleChecked);
  135. }
  136. else
  137. {
  138. KeyBindings.Remove (KeyCode.Space);
  139. }
  140. SetNeedsDisplay ();
  141. }
  142. }
  143. /// <summary>
  144. /// If set to <see langword="true"/> more than one item can be selected. If <see langword="false"/> selecting an
  145. /// item will cause all others to be un-selected. The default is <see langword="false"/>.
  146. /// </summary>
  147. public bool AllowsMultipleSelection
  148. {
  149. get => _allowsMultipleSelection;
  150. set
  151. {
  152. _allowsMultipleSelection = value;
  153. if (Source != null && !_allowsMultipleSelection)
  154. {
  155. // Clear all selections except selected
  156. for (var i = 0; i < Source.Count; i++)
  157. {
  158. if (Source.IsMarked (i) && i != _selected)
  159. {
  160. Source.SetMark (i, false);
  161. }
  162. }
  163. }
  164. SetNeedsDisplay ();
  165. }
  166. }
  167. /// <summary>
  168. /// Gets the <see cref="CollectionNavigator"/> that searches the <see cref="ListView.Source"/> collection as the
  169. /// user types.
  170. /// </summary>
  171. public CollectionNavigator KeystrokeNavigator { get; } = new ();
  172. /// <summary>Gets or sets the leftmost column that is currently visible (when scrolling horizontally).</summary>
  173. /// <value>The left position.</value>
  174. public int LeftItem
  175. {
  176. get => _left;
  177. set
  178. {
  179. if (_source is null)
  180. {
  181. return;
  182. }
  183. if (value < 0 || (MaxLength > 0 && value >= MaxLength))
  184. {
  185. throw new ArgumentException ("value");
  186. }
  187. _left = value;
  188. SetNeedsDisplay ();
  189. }
  190. }
  191. /// <summary>Gets the widest item in the list.</summary>
  192. public int MaxLength => _source?.Length ?? 0;
  193. /// <summary>Gets or sets the index of the currently selected item.</summary>
  194. /// <value>The selected item.</value>
  195. public int SelectedItem
  196. {
  197. get => _selected;
  198. set
  199. {
  200. if (_source is null || _source.Count == 0)
  201. {
  202. return;
  203. }
  204. if (value < -1 || value >= _source.Count)
  205. {
  206. throw new ArgumentException ("value");
  207. }
  208. _selected = value;
  209. OnSelectedChanged ();
  210. }
  211. }
  212. /// <summary>Gets or sets the <see cref="IListDataSource"/> backing this <see cref="ListView"/>, enabling custom rendering.</summary>
  213. /// <value>The source.</value>
  214. /// <remarks>Use <see cref="SetSource"/> to set a new <see cref="IList"/> source.</remarks>
  215. public IListDataSource Source
  216. {
  217. get => _source;
  218. set
  219. {
  220. _source = value;
  221. KeystrokeNavigator.Collection = _source?.ToList ();
  222. _top = 0;
  223. _selected = -1;
  224. _lastSelectedItem = -1;
  225. SetNeedsDisplay ();
  226. }
  227. }
  228. /// <summary>Gets or sets the item that is displayed at the top of the <see cref="ListView"/>.</summary>
  229. /// <value>The top item.</value>
  230. public int TopItem
  231. {
  232. get => _top;
  233. set
  234. {
  235. if (_source is null)
  236. {
  237. return;
  238. }
  239. if (value < 0 || (_source.Count > 0 && value >= _source.Count))
  240. {
  241. throw new ArgumentException ("value");
  242. }
  243. _top = Math.Max (value, 0);
  244. SetNeedsDisplay ();
  245. }
  246. }
  247. /// <summary>
  248. /// If <see cref="AllowsMarking"/> and <see cref="AllowsMultipleSelection"/> are both <see langword="true"/>,
  249. /// unmarks all marked items other than the currently selected.
  250. /// </summary>
  251. /// <returns><see langword="true"/> if unmarking was successful.</returns>
  252. public virtual bool AllowsAll ()
  253. {
  254. if (!_allowsMarking)
  255. {
  256. return false;
  257. }
  258. if (!AllowsMultipleSelection)
  259. {
  260. for (var i = 0; i < Source.Count; i++)
  261. {
  262. if (Source.IsMarked (i) && i != _selected)
  263. {
  264. Source.SetMark (i, false);
  265. return true;
  266. }
  267. }
  268. }
  269. return true;
  270. }
  271. /// <summary>Ensures the selected item is always visible on the screen.</summary>
  272. public void EnsureSelectedItemVisible ()
  273. {
  274. if (SuperView?.IsInitialized == true)
  275. {
  276. if (_selected < _top)
  277. {
  278. _top = Math.Max (_selected, 0);
  279. }
  280. else if (Bounds.Height > 0 && _selected >= _top + Bounds.Height)
  281. {
  282. _top = Math.Max (_selected - Bounds.Height + 1, 0);
  283. }
  284. LayoutStarted -= ListView_LayoutStarted;
  285. }
  286. else
  287. {
  288. LayoutStarted += ListView_LayoutStarted;
  289. }
  290. }
  291. /// <summary>Marks the <see cref="SelectedItem"/> if it is not already marked.</summary>
  292. /// <returns><see langword="true"/> if the <see cref="SelectedItem"/> was marked.</returns>
  293. public virtual bool MarkUnmarkRow ()
  294. {
  295. if (AllowsAll ())
  296. {
  297. Source.SetMark (SelectedItem, !Source.IsMarked (SelectedItem));
  298. SetNeedsDisplay ();
  299. return true;
  300. }
  301. return false;
  302. }
  303. /// <inheritdoc/>
  304. public override bool MouseEvent (MouseEvent me)
  305. {
  306. if (!me.Flags.HasFlag (MouseFlags.Button1Clicked)
  307. && !me.Flags.HasFlag (MouseFlags.Button1DoubleClicked)
  308. && me.Flags != MouseFlags.WheeledDown
  309. && me.Flags != MouseFlags.WheeledUp
  310. && me.Flags != MouseFlags.WheeledRight
  311. && me.Flags != MouseFlags.WheeledLeft)
  312. {
  313. return false;
  314. }
  315. if (!HasFocus && CanFocus)
  316. {
  317. SetFocus ();
  318. }
  319. if (_source is null)
  320. {
  321. return false;
  322. }
  323. if (me.Flags == MouseFlags.WheeledDown)
  324. {
  325. ScrollDown (1);
  326. return true;
  327. }
  328. if (me.Flags == MouseFlags.WheeledUp)
  329. {
  330. ScrollUp (1);
  331. return true;
  332. }
  333. if (me.Flags == MouseFlags.WheeledRight)
  334. {
  335. ScrollRight (1);
  336. return true;
  337. }
  338. if (me.Flags == MouseFlags.WheeledLeft)
  339. {
  340. ScrollLeft (1);
  341. return true;
  342. }
  343. if (me.Y + _top >= _source.Count
  344. || me.Y + _top < 0
  345. || me.Y + _top > _top + Bounds.Height)
  346. {
  347. return true;
  348. }
  349. _selected = _top + me.Y;
  350. if (AllowsAll ())
  351. {
  352. Source.SetMark (SelectedItem, !Source.IsMarked (SelectedItem));
  353. SetNeedsDisplay ();
  354. return true;
  355. }
  356. OnSelectedChanged ();
  357. SetNeedsDisplay ();
  358. if (me.Flags == MouseFlags.Button1DoubleClicked)
  359. {
  360. OnOpenSelectedItem ();
  361. }
  362. return true;
  363. }
  364. /// <summary>Changes the <see cref="SelectedItem"/> to the next item in the list, scrolling the list if needed.</summary>
  365. /// <returns></returns>
  366. public virtual bool MoveDown ()
  367. {
  368. if (_source.Count == 0)
  369. {
  370. // Do we set lastSelectedItem to -1 here?
  371. return false; //Nothing for us to move to
  372. }
  373. if (_selected >= _source.Count)
  374. {
  375. // If for some reason we are currently outside of the
  376. // valid values range, we should select the bottommost valid value.
  377. // This can occur if the backing data source changes.
  378. _selected = _source.Count - 1;
  379. OnSelectedChanged ();
  380. SetNeedsDisplay ();
  381. }
  382. else if (_selected + 1 < _source.Count)
  383. {
  384. //can move by down by one.
  385. _selected++;
  386. if (_selected >= _top + Bounds.Height)
  387. {
  388. _top++;
  389. }
  390. else if (_selected < _top)
  391. {
  392. _top = Math.Max (_selected, 0);
  393. }
  394. OnSelectedChanged ();
  395. SetNeedsDisplay ();
  396. }
  397. else if (_selected == 0)
  398. {
  399. OnSelectedChanged ();
  400. SetNeedsDisplay ();
  401. }
  402. else if (_selected >= _top + Bounds.Height)
  403. {
  404. _top = Math.Max (_source.Count - Bounds.Height, 0);
  405. SetNeedsDisplay ();
  406. }
  407. return true;
  408. }
  409. /// <summary>Changes the <see cref="SelectedItem"/> to last item in the list, scrolling the list if needed.</summary>
  410. /// <returns></returns>
  411. public virtual bool MoveEnd ()
  412. {
  413. if (_source.Count > 0 && _selected != _source.Count - 1)
  414. {
  415. _selected = _source.Count - 1;
  416. if (_top + _selected > Bounds.Height - 1)
  417. {
  418. _top = Math.Max (_selected, 0);
  419. }
  420. OnSelectedChanged ();
  421. SetNeedsDisplay ();
  422. }
  423. return true;
  424. }
  425. /// <summary>Changes the <see cref="SelectedItem"/> to the first item in the list, scrolling the list if needed.</summary>
  426. /// <returns></returns>
  427. public virtual bool MoveHome ()
  428. {
  429. if (_selected != 0)
  430. {
  431. _selected = 0;
  432. _top = Math.Max (_selected, 0);
  433. OnSelectedChanged ();
  434. SetNeedsDisplay ();
  435. }
  436. return true;
  437. }
  438. /// <summary>
  439. /// Changes the <see cref="SelectedItem"/> to the item just below the bottom of the visible list, scrolling if
  440. /// needed.
  441. /// </summary>
  442. /// <returns></returns>
  443. public virtual bool MovePageDown ()
  444. {
  445. int n = _selected + Bounds.Height;
  446. if (n >= _source.Count)
  447. {
  448. n = _source.Count - 1;
  449. }
  450. if (n != _selected)
  451. {
  452. _selected = n;
  453. if (_source.Count >= Bounds.Height)
  454. {
  455. _top = Math.Max (_selected, 0);
  456. }
  457. else
  458. {
  459. _top = 0;
  460. }
  461. OnSelectedChanged ();
  462. SetNeedsDisplay ();
  463. }
  464. return true;
  465. }
  466. /// <summary>Changes the <see cref="SelectedItem"/> to the item at the top of the visible list.</summary>
  467. /// <returns></returns>
  468. public virtual bool MovePageUp ()
  469. {
  470. int n = _selected - Bounds.Height;
  471. if (n < 0)
  472. {
  473. n = 0;
  474. }
  475. if (n != _selected)
  476. {
  477. _selected = n;
  478. _top = Math.Max (_selected, 0);
  479. OnSelectedChanged ();
  480. SetNeedsDisplay ();
  481. }
  482. return true;
  483. }
  484. /// <summary>Changes the <see cref="SelectedItem"/> to the previous item in the list, scrolling the list if needed.</summary>
  485. /// <returns></returns>
  486. public virtual bool MoveUp ()
  487. {
  488. if (_source.Count == 0)
  489. {
  490. // Do we set lastSelectedItem to -1 here?
  491. return false; //Nothing for us to move to
  492. }
  493. if (_selected >= _source.Count)
  494. {
  495. // If for some reason we are currently outside of the
  496. // valid values range, we should select the bottommost valid value.
  497. // This can occur if the backing data source changes.
  498. _selected = _source.Count - 1;
  499. OnSelectedChanged ();
  500. SetNeedsDisplay ();
  501. }
  502. else if (_selected > 0)
  503. {
  504. _selected--;
  505. if (_selected > Source.Count)
  506. {
  507. _selected = Source.Count - 1;
  508. }
  509. if (_selected < _top)
  510. {
  511. _top = Math.Max (_selected, 0);
  512. }
  513. else if (_selected > _top + Bounds.Height)
  514. {
  515. _top = Math.Max (_selected - Bounds.Height + 1, 0);
  516. }
  517. OnSelectedChanged ();
  518. SetNeedsDisplay ();
  519. }
  520. else if (_selected < _top)
  521. {
  522. _top = Math.Max (_selected, 0);
  523. SetNeedsDisplay ();
  524. }
  525. return true;
  526. }
  527. /// <inheritdoc/>
  528. public override void OnDrawContent (Rect contentArea)
  529. {
  530. base.OnDrawContent (contentArea);
  531. Attribute current = ColorScheme.Focus;
  532. Driver.SetAttribute (current);
  533. Move (0, 0);
  534. Rect f = Bounds;
  535. int item = _top;
  536. bool focused = HasFocus;
  537. int col = _allowsMarking ? 2 : 0;
  538. int start = _left;
  539. for (var row = 0; row < f.Height; row++, item++)
  540. {
  541. bool isSelected = item == _selected;
  542. Attribute newcolor = focused ? isSelected ? ColorScheme.Focus : GetNormalColor () :
  543. isSelected ? ColorScheme.HotNormal : GetNormalColor ();
  544. if (newcolor != current)
  545. {
  546. Driver.SetAttribute (newcolor);
  547. current = newcolor;
  548. }
  549. Move (0, row);
  550. if (_source is null || item >= _source.Count)
  551. {
  552. for (var c = 0; c < f.Width; c++)
  553. {
  554. Driver.AddRune ((Rune)' ');
  555. }
  556. }
  557. else
  558. {
  559. var rowEventArgs = new ListViewRowEventArgs (item);
  560. OnRowRender (rowEventArgs);
  561. if (rowEventArgs.RowAttribute != null && current != rowEventArgs.RowAttribute)
  562. {
  563. current = (Attribute)rowEventArgs.RowAttribute;
  564. Driver.SetAttribute (current);
  565. }
  566. if (_allowsMarking)
  567. {
  568. Driver.AddRune (
  569. _source.IsMarked (item) ? AllowsMultipleSelection ? Glyphs.Checked : Glyphs.Selected :
  570. AllowsMultipleSelection ? Glyphs.UnChecked : Glyphs.UnSelected
  571. );
  572. Driver.AddRune ((Rune)' ');
  573. }
  574. Source.Render (this, Driver, isSelected, item, col, row, f.Width - col, start);
  575. }
  576. }
  577. }
  578. /// <inheritdoc/>
  579. public override bool OnEnter (View view)
  580. {
  581. if (IsInitialized)
  582. {
  583. Application.Driver.SetCursorVisibility (CursorVisibility.Invisible);
  584. }
  585. if (_lastSelectedItem != _selected)
  586. {
  587. EnsureSelectedItemVisible ();
  588. }
  589. return base.OnEnter (view);
  590. }
  591. /// <summary>Invokes the <see cref="OpenSelectedItem"/> event if it is defined.</summary>
  592. /// <returns></returns>
  593. public virtual bool OnOpenSelectedItem ()
  594. {
  595. if (_source.Count <= _selected || _selected < 0 || OpenSelectedItem is null)
  596. {
  597. return false;
  598. }
  599. object value = _source.ToList () [_selected];
  600. OpenSelectedItem?.Invoke (this, new ListViewItemEventArgs (_selected, value));
  601. return true;
  602. }
  603. /// <inheritdoc/>
  604. public override bool OnProcessKeyDown (Key a)
  605. {
  606. // Enable user to find & select an item by typing text
  607. if (CollectionNavigatorBase.IsCompatibleKey (a))
  608. {
  609. int? newItem = KeystrokeNavigator?.GetNextMatchingItem (SelectedItem, (char)a);
  610. if (newItem is int && newItem != -1)
  611. {
  612. SelectedItem = (int)newItem;
  613. EnsureSelectedItemVisible ();
  614. SetNeedsDisplay ();
  615. return true;
  616. }
  617. }
  618. return false;
  619. }
  620. /// <summary>Virtual method that will invoke the <see cref="RowRender"/>.</summary>
  621. /// <param name="rowEventArgs"></param>
  622. public virtual void OnRowRender (ListViewRowEventArgs rowEventArgs) { RowRender?.Invoke (this, rowEventArgs); }
  623. /// <summary>Invokes the <see cref="SelectedItemChanged"/> event if it is defined.</summary>
  624. /// <returns></returns>
  625. public virtual bool OnSelectedChanged ()
  626. {
  627. if (_selected != _lastSelectedItem)
  628. {
  629. object value = _source?.Count > 0 ? _source.ToList () [_selected] : null;
  630. SelectedItemChanged?.Invoke (this, new ListViewItemEventArgs (_selected, value));
  631. _lastSelectedItem = _selected;
  632. EnsureSelectedItemVisible ();
  633. return true;
  634. }
  635. return false;
  636. }
  637. /// <summary>This event is raised when the user Double Clicks on an item or presses ENTER to open the selected item.</summary>
  638. public event EventHandler<ListViewItemEventArgs> OpenSelectedItem;
  639. /// <inheritdoc/>
  640. public override void PositionCursor ()
  641. {
  642. if (_allowsMarking)
  643. {
  644. Move (0, _selected - _top);
  645. }
  646. else
  647. {
  648. Move (Bounds.Width - 1, _selected - _top);
  649. }
  650. }
  651. /// <summary>This event is invoked when this <see cref="ListView"/> is being drawn before rendering.</summary>
  652. public event EventHandler<ListViewRowEventArgs> RowRender;
  653. /// <summary>Scrolls the view down by <paramref name="items"/> items.</summary>
  654. /// <param name="items">Number of items to scroll down.</param>
  655. public virtual bool ScrollDown (int items)
  656. {
  657. _top = Math.Max (Math.Min (_top + items, _source.Count - 1), 0);
  658. SetNeedsDisplay ();
  659. return true;
  660. }
  661. /// <summary>Scrolls the view left.</summary>
  662. /// <param name="cols">Number of columns to scroll left.</param>
  663. public virtual bool ScrollLeft (int cols)
  664. {
  665. _left = Math.Max (_left - cols, 0);
  666. SetNeedsDisplay ();
  667. return true;
  668. }
  669. /// <summary>Scrolls the view right.</summary>
  670. /// <param name="cols">Number of columns to scroll right.</param>
  671. public virtual bool ScrollRight (int cols)
  672. {
  673. _left = Math.Max (Math.Min (_left + cols, MaxLength - 1), 0);
  674. SetNeedsDisplay ();
  675. return true;
  676. }
  677. /// <summary>Scrolls the view up by <paramref name="items"/> items.</summary>
  678. /// <param name="items">Number of items to scroll up.</param>
  679. public virtual bool ScrollUp (int items)
  680. {
  681. _top = Math.Max (_top - items, 0);
  682. SetNeedsDisplay ();
  683. return true;
  684. }
  685. /// <summary>This event is raised when the selected item in the <see cref="ListView"/> has changed.</summary>
  686. public event EventHandler<ListViewItemEventArgs> SelectedItemChanged;
  687. /// <summary>Sets the source of the <see cref="ListView"/> to an <see cref="IList"/>.</summary>
  688. /// <value>An object implementing the IList interface.</value>
  689. /// <remarks>
  690. /// Use the <see cref="Source"/> property to set a new <see cref="IListDataSource"/> source and use custome
  691. /// rendering.
  692. /// </remarks>
  693. public void SetSource (IList source)
  694. {
  695. if (source is null && (Source is null || !(Source is ListWrapper)))
  696. {
  697. Source = null;
  698. }
  699. else
  700. {
  701. Source = new ListWrapper (source);
  702. }
  703. }
  704. /// <summary>Sets the source to an <see cref="IList"/> value asynchronously.</summary>
  705. /// <value>An item implementing the IList interface.</value>
  706. /// <remarks>
  707. /// Use the <see cref="Source"/> property to set a new <see cref="IListDataSource"/> source and use custom
  708. /// rendering.
  709. /// </remarks>
  710. public Task SetSourceAsync (IList source)
  711. {
  712. return Task.Factory.StartNew (
  713. () =>
  714. {
  715. if (source is null && (Source is null || !(Source is ListWrapper)))
  716. {
  717. Source = null;
  718. }
  719. else
  720. {
  721. Source = new ListWrapper (source);
  722. }
  723. return source;
  724. },
  725. CancellationToken.None,
  726. TaskCreationOptions.DenyChildAttach,
  727. TaskScheduler.Default
  728. );
  729. }
  730. private void ListView_LayoutStarted (object sender, LayoutEventArgs e) { EnsureSelectedItemVisible (); }
  731. }
  732. /// <summary>
  733. /// Provides a default implementation of <see cref="IListDataSource"/> that renders <see cref="ListView"/> items
  734. /// using <see cref="object.ToString()"/>.
  735. /// </summary>
  736. public class ListWrapper : IListDataSource
  737. {
  738. private readonly int _count;
  739. private readonly BitArray _marks;
  740. private readonly IList _source;
  741. /// <inheritdoc/>
  742. public ListWrapper (IList source)
  743. {
  744. if (source != null)
  745. {
  746. _count = source.Count;
  747. _marks = new BitArray (_count);
  748. _source = source;
  749. Length = GetMaxLengthItem ();
  750. }
  751. }
  752. /// <inheritdoc/>
  753. public int Count => _source != null ? _source.Count : 0;
  754. /// <inheritdoc/>
  755. public int Length { get; }
  756. /// <inheritdoc/>
  757. public void Render (
  758. ListView container,
  759. ConsoleDriver driver,
  760. bool marked,
  761. int item,
  762. int col,
  763. int line,
  764. int width,
  765. int start = 0
  766. )
  767. {
  768. container.Move (col, line);
  769. object t = _source? [item];
  770. if (t is null)
  771. {
  772. RenderUstr (driver, "", col, line, width);
  773. }
  774. else
  775. {
  776. if (t is string u)
  777. {
  778. RenderUstr (driver, u, col, line, width, start);
  779. }
  780. else if (t is string s)
  781. {
  782. RenderUstr (driver, s, col, line, width, start);
  783. }
  784. else
  785. {
  786. RenderUstr (driver, t.ToString (), col, line, width, start);
  787. }
  788. }
  789. }
  790. /// <inheritdoc/>
  791. public bool IsMarked (int item)
  792. {
  793. if (item >= 0 && item < _count)
  794. {
  795. return _marks [item];
  796. }
  797. return false;
  798. }
  799. /// <inheritdoc/>
  800. public void SetMark (int item, bool value)
  801. {
  802. if (item >= 0 && item < _count)
  803. {
  804. _marks [item] = value;
  805. }
  806. }
  807. /// <inheritdoc/>
  808. public IList ToList () { return _source; }
  809. /// <inheritdoc/>
  810. public int StartsWith (string search)
  811. {
  812. if (_source is null || _source?.Count == 0)
  813. {
  814. return -1;
  815. }
  816. for (var i = 0; i < _source.Count; i++)
  817. {
  818. object t = _source [i];
  819. if (t is string u)
  820. {
  821. if (u.ToUpper ().StartsWith (search.ToUpperInvariant ()))
  822. {
  823. return i;
  824. }
  825. }
  826. else if (t is string s)
  827. {
  828. if (s.StartsWith (search, StringComparison.InvariantCultureIgnoreCase))
  829. {
  830. return i;
  831. }
  832. }
  833. }
  834. return -1;
  835. }
  836. private int GetMaxLengthItem ()
  837. {
  838. if (_source is null || _source?.Count == 0)
  839. {
  840. return 0;
  841. }
  842. var maxLength = 0;
  843. for (var i = 0; i < _source.Count; i++)
  844. {
  845. object t = _source [i];
  846. int l;
  847. if (t is string u)
  848. {
  849. l = u.GetColumns ();
  850. }
  851. else if (t is string s)
  852. {
  853. l = s.Length;
  854. }
  855. else
  856. {
  857. l = t.ToString ().Length;
  858. }
  859. if (l > maxLength)
  860. {
  861. maxLength = l;
  862. }
  863. }
  864. return maxLength;
  865. }
  866. private void RenderUstr (ConsoleDriver driver, string ustr, int col, int line, int width, int start = 0)
  867. {
  868. string u = TextFormatter.ClipAndJustify (ustr, width, TextAlignment.Left);
  869. driver.AddStr (u);
  870. width -= u.GetColumns ();
  871. while (width-- > 0)
  872. {
  873. driver.AddRune ((Rune)' ');
  874. }
  875. }
  876. }