ListView.cs 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034
  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. public 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.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.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. int n = _selected + Bounds.Height;
  447. if (n >= _source.Count)
  448. {
  449. n = _source.Count - 1;
  450. }
  451. if (n != _selected)
  452. {
  453. _selected = n;
  454. if (_source.Count >= Bounds.Height)
  455. {
  456. _top = Math.Max (_selected, 0);
  457. }
  458. else
  459. {
  460. _top = 0;
  461. }
  462. OnSelectedChanged ();
  463. SetNeedsDisplay ();
  464. }
  465. return true;
  466. }
  467. /// <summary>Changes the <see cref="SelectedItem"/> to the item at the top of the visible list.</summary>
  468. /// <returns></returns>
  469. public virtual bool MovePageUp ()
  470. {
  471. int n = _selected - Bounds.Height;
  472. if (n < 0)
  473. {
  474. n = 0;
  475. }
  476. if (n != _selected)
  477. {
  478. _selected = n;
  479. _top = Math.Max (_selected, 0);
  480. OnSelectedChanged ();
  481. SetNeedsDisplay ();
  482. }
  483. return true;
  484. }
  485. /// <summary>Changes the <see cref="SelectedItem"/> to the previous item in the list, scrolling the list if needed.</summary>
  486. /// <returns></returns>
  487. public virtual bool MoveUp ()
  488. {
  489. if (_source.Count == 0)
  490. {
  491. // Do we set lastSelectedItem to -1 here?
  492. return false; //Nothing for us to move to
  493. }
  494. if (_selected >= _source.Count)
  495. {
  496. // If for some reason we are currently outside of the
  497. // valid values range, we should select the bottommost valid value.
  498. // This can occur if the backing data source changes.
  499. _selected = _source.Count - 1;
  500. OnSelectedChanged ();
  501. SetNeedsDisplay ();
  502. }
  503. else if (_selected > 0)
  504. {
  505. _selected--;
  506. if (_selected > Source.Count)
  507. {
  508. _selected = Source.Count - 1;
  509. }
  510. if (_selected < _top)
  511. {
  512. _top = Math.Max (_selected, 0);
  513. }
  514. else if (_selected > _top + Bounds.Height)
  515. {
  516. _top = Math.Max (_selected - Bounds.Height + 1, 0);
  517. }
  518. OnSelectedChanged ();
  519. SetNeedsDisplay ();
  520. }
  521. else if (_selected < _top)
  522. {
  523. _top = Math.Max (_selected, 0);
  524. SetNeedsDisplay ();
  525. }
  526. return true;
  527. }
  528. /// <inheritdoc/>
  529. public override void OnDrawContent (Rectangle contentArea)
  530. {
  531. base.OnDrawContent (contentArea);
  532. Attribute current = ColorScheme.Focus;
  533. Driver.SetAttribute (current);
  534. Move (0, 0);
  535. Rectangle f = Bounds;
  536. int item = _top;
  537. bool focused = HasFocus;
  538. int col = _allowsMarking ? 2 : 0;
  539. int start = _left;
  540. for (var row = 0; row < f.Height; row++, item++)
  541. {
  542. bool isSelected = item == _selected;
  543. Attribute newcolor = focused ? isSelected ? ColorScheme.Focus : GetNormalColor () :
  544. isSelected ? ColorScheme.HotNormal : GetNormalColor ();
  545. if (newcolor != current)
  546. {
  547. Driver.SetAttribute (newcolor);
  548. current = newcolor;
  549. }
  550. Move (0, row);
  551. if (_source is null || item >= _source.Count)
  552. {
  553. for (var c = 0; c < f.Width; c++)
  554. {
  555. Driver.AddRune ((Rune)' ');
  556. }
  557. }
  558. else
  559. {
  560. var rowEventArgs = new ListViewRowEventArgs (item);
  561. OnRowRender (rowEventArgs);
  562. if (rowEventArgs.RowAttribute is { } && current != rowEventArgs.RowAttribute)
  563. {
  564. current = (Attribute)rowEventArgs.RowAttribute;
  565. Driver.SetAttribute (current);
  566. }
  567. if (_allowsMarking)
  568. {
  569. Driver.AddRune (
  570. _source.IsMarked (item) ? AllowsMultipleSelection ? Glyphs.Checked : Glyphs.Selected :
  571. AllowsMultipleSelection ? Glyphs.UnChecked : Glyphs.UnSelected
  572. );
  573. Driver.AddRune ((Rune)' ');
  574. }
  575. Source.Render (this, Driver, isSelected, item, col, row, f.Width - col, start);
  576. }
  577. }
  578. }
  579. /// <inheritdoc/>
  580. public override bool OnEnter (View view)
  581. {
  582. if (IsInitialized)
  583. {
  584. Application.Driver.SetCursorVisibility (CursorVisibility.Invisible);
  585. }
  586. if (_lastSelectedItem != _selected)
  587. {
  588. EnsureSelectedItemVisible ();
  589. }
  590. return base.OnEnter (view);
  591. }
  592. // TODO: This should be cancelable
  593. /// <summary>Invokes the <see cref="OpenSelectedItem"/> event if it is defined.</summary>
  594. /// <returns><see langword="true"/> if the <see cref="OpenSelectedItem"/> event was fired.</returns>
  595. public bool OnOpenSelectedItem ()
  596. {
  597. if (_source.Count <= _selected || _selected < 0 || OpenSelectedItem is null)
  598. {
  599. return false;
  600. }
  601. object value = _source.ToList () [_selected];
  602. if (OnAccept () == true)
  603. {
  604. return false;
  605. }
  606. OpenSelectedItem?.Invoke (this, new ListViewItemEventArgs (_selected, value));
  607. return true;
  608. }
  609. /// <inheritdoc/>
  610. public override bool OnProcessKeyDown (Key a)
  611. {
  612. // Enable user to find & select an item by typing text
  613. if (CollectionNavigatorBase.IsCompatibleKey (a))
  614. {
  615. int? newItem = KeystrokeNavigator?.GetNextMatchingItem (SelectedItem, (char)a);
  616. if (newItem is int && newItem != -1)
  617. {
  618. SelectedItem = (int)newItem;
  619. EnsureSelectedItemVisible ();
  620. SetNeedsDisplay ();
  621. return true;
  622. }
  623. }
  624. return false;
  625. }
  626. /// <summary>Virtual method that will invoke the <see cref="RowRender"/>.</summary>
  627. /// <param name="rowEventArgs"></param>
  628. public virtual void OnRowRender (ListViewRowEventArgs rowEventArgs) { RowRender?.Invoke (this, rowEventArgs); }
  629. /// <summary>Invokes the <see cref="SelectedItemChanged"/> event if it is defined.</summary>
  630. /// <returns></returns>
  631. public virtual bool OnSelectedChanged ()
  632. {
  633. if (_selected != _lastSelectedItem)
  634. {
  635. object value = _source?.Count > 0 ? _source.ToList () [_selected] : null;
  636. SelectedItemChanged?.Invoke (this, new ListViewItemEventArgs (_selected, value));
  637. _lastSelectedItem = _selected;
  638. EnsureSelectedItemVisible ();
  639. return true;
  640. }
  641. return false;
  642. }
  643. /// <summary>This event is raised when the user Double Clicks on an item or presses ENTER to open the selected item.</summary>
  644. public event EventHandler<ListViewItemEventArgs> OpenSelectedItem;
  645. /// <inheritdoc/>
  646. public override void PositionCursor ()
  647. {
  648. if (_allowsMarking)
  649. {
  650. Move (0, _selected - _top);
  651. }
  652. else
  653. {
  654. Move (Bounds.Width - 1, _selected - _top);
  655. }
  656. }
  657. /// <summary>This event is invoked when this <see cref="ListView"/> is being drawn before rendering.</summary>
  658. public event EventHandler<ListViewRowEventArgs> RowRender;
  659. /// <summary>Scrolls the view down by <paramref name="items"/> items.</summary>
  660. /// <param name="items">Number of items to scroll down.</param>
  661. public virtual bool ScrollDown (int items)
  662. {
  663. _top = Math.Max (Math.Min (_top + items, _source.Count - 1), 0);
  664. SetNeedsDisplay ();
  665. return true;
  666. }
  667. /// <summary>Scrolls the view left.</summary>
  668. /// <param name="cols">Number of columns to scroll left.</param>
  669. public virtual bool ScrollLeft (int cols)
  670. {
  671. _left = Math.Max (_left - cols, 0);
  672. SetNeedsDisplay ();
  673. return true;
  674. }
  675. /// <summary>Scrolls the view right.</summary>
  676. /// <param name="cols">Number of columns to scroll right.</param>
  677. public virtual bool ScrollRight (int cols)
  678. {
  679. _left = Math.Max (Math.Min (_left + cols, MaxLength - 1), 0);
  680. SetNeedsDisplay ();
  681. return true;
  682. }
  683. /// <summary>Scrolls the view up by <paramref name="items"/> items.</summary>
  684. /// <param name="items">Number of items to scroll up.</param>
  685. public virtual bool ScrollUp (int items)
  686. {
  687. _top = Math.Max (_top - items, 0);
  688. SetNeedsDisplay ();
  689. return true;
  690. }
  691. /// <summary>This event is raised when the selected item in the <see cref="ListView"/> has changed.</summary>
  692. public event EventHandler<ListViewItemEventArgs> SelectedItemChanged;
  693. /// <summary>Sets the source of the <see cref="ListView"/> to an <see cref="IList"/>.</summary>
  694. /// <value>An object implementing the IList interface.</value>
  695. /// <remarks>
  696. /// Use the <see cref="Source"/> property to set a new <see cref="IListDataSource"/> source and use custome
  697. /// rendering.
  698. /// </remarks>
  699. public void SetSource (IList source)
  700. {
  701. if (source is null && (Source is null || !(Source is ListWrapper)))
  702. {
  703. Source = null;
  704. }
  705. else
  706. {
  707. Source = new ListWrapper (source);
  708. }
  709. }
  710. /// <summary>Sets the source to an <see cref="IList"/> value asynchronously.</summary>
  711. /// <value>An item implementing the IList interface.</value>
  712. /// <remarks>
  713. /// Use the <see cref="Source"/> property to set a new <see cref="IListDataSource"/> source and use custom
  714. /// rendering.
  715. /// </remarks>
  716. public Task SetSourceAsync (IList source)
  717. {
  718. return Task.Factory.StartNew (
  719. () =>
  720. {
  721. if (source is null && (Source is null || !(Source is ListWrapper)))
  722. {
  723. Source = null;
  724. }
  725. else
  726. {
  727. Source = new ListWrapper (source);
  728. }
  729. return source;
  730. },
  731. CancellationToken.None,
  732. TaskCreationOptions.DenyChildAttach,
  733. TaskScheduler.Default
  734. );
  735. }
  736. private void ListView_LayoutStarted (object sender, LayoutEventArgs e) { EnsureSelectedItemVisible (); }
  737. }
  738. /// <summary>
  739. /// Provides a default implementation of <see cref="IListDataSource"/> that renders <see cref="ListView"/> items
  740. /// using <see cref="object.ToString()"/>.
  741. /// </summary>
  742. public class ListWrapper : IListDataSource
  743. {
  744. private readonly int _count;
  745. private readonly BitArray _marks;
  746. private readonly IList _source;
  747. /// <inheritdoc/>
  748. public ListWrapper (IList source)
  749. {
  750. if (source is { })
  751. {
  752. _count = source.Count;
  753. _marks = new BitArray (_count);
  754. _source = source;
  755. Length = GetMaxLengthItem ();
  756. }
  757. }
  758. /// <inheritdoc/>
  759. public int Count => _source is { } ? _source.Count : 0;
  760. /// <inheritdoc/>
  761. public int Length { get; }
  762. /// <inheritdoc/>
  763. public void Render (
  764. ListView container,
  765. ConsoleDriver driver,
  766. bool marked,
  767. int item,
  768. int col,
  769. int line,
  770. int width,
  771. int start = 0
  772. )
  773. {
  774. container.Move (col, line);
  775. object t = _source? [item];
  776. if (t is null)
  777. {
  778. RenderUstr (driver, "", col, line, width);
  779. }
  780. else
  781. {
  782. if (t is string u)
  783. {
  784. RenderUstr (driver, u, col, line, width, start);
  785. }
  786. else if (t is string s)
  787. {
  788. RenderUstr (driver, s, col, line, width, start);
  789. }
  790. else
  791. {
  792. RenderUstr (driver, t.ToString (), col, line, width, start);
  793. }
  794. }
  795. }
  796. /// <inheritdoc/>
  797. public bool IsMarked (int item)
  798. {
  799. if (item >= 0 && item < _count)
  800. {
  801. return _marks [item];
  802. }
  803. return false;
  804. }
  805. /// <inheritdoc/>
  806. public void SetMark (int item, bool value)
  807. {
  808. if (item >= 0 && item < _count)
  809. {
  810. _marks [item] = value;
  811. }
  812. }
  813. /// <inheritdoc/>
  814. public IList ToList () { return _source; }
  815. /// <inheritdoc/>
  816. public int StartsWith (string search)
  817. {
  818. if (_source is null || _source?.Count == 0)
  819. {
  820. return -1;
  821. }
  822. for (var i = 0; i < _source.Count; i++)
  823. {
  824. object t = _source [i];
  825. if (t is string u)
  826. {
  827. if (u.ToUpper ().StartsWith (search.ToUpperInvariant ()))
  828. {
  829. return i;
  830. }
  831. }
  832. else if (t is string s)
  833. {
  834. if (s.StartsWith (search, StringComparison.InvariantCultureIgnoreCase))
  835. {
  836. return i;
  837. }
  838. }
  839. }
  840. return -1;
  841. }
  842. private int GetMaxLengthItem ()
  843. {
  844. if (_source is null || _source?.Count == 0)
  845. {
  846. return 0;
  847. }
  848. var maxLength = 0;
  849. for (var i = 0; i < _source.Count; i++)
  850. {
  851. object t = _source [i];
  852. int l;
  853. if (t is string u)
  854. {
  855. l = u.GetColumns ();
  856. }
  857. else if (t is string s)
  858. {
  859. l = s.Length;
  860. }
  861. else
  862. {
  863. l = t.ToString ().Length;
  864. }
  865. if (l > maxLength)
  866. {
  867. maxLength = l;
  868. }
  869. }
  870. return maxLength;
  871. }
  872. private void RenderUstr (ConsoleDriver driver, string ustr, int col, int line, int width, int start = 0)
  873. {
  874. string u = TextFormatter.ClipAndJustify (ustr, width, TextAlignment.Left);
  875. driver.AddStr (u);
  876. width -= u.GetColumns ();
  877. while (width-- > 0)
  878. {
  879. driver.AddRune ((Rune)' ');
  880. }
  881. }
  882. }