ListView.cs 31 KB

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