ListView.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035
  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 (Viewport.Height > 0 && _selected >= _top + Viewport.Height)
  282. {
  283. _top = Math.Max (_selected - Viewport.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 + Viewport.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 + Viewport.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 + Viewport.Height)
  404. {
  405. _top = Math.Max (_source.Count - Viewport.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 > Viewport.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 + Viewport.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 >= Viewport.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 - Viewport.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 + Viewport.Height)
  515. {
  516. _top = Math.Max (_selected - Viewport.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 viewport)
  530. {
  531. base.OnDrawContent (viewport);
  532. Attribute current = ColorScheme.Focus;
  533. Driver.SetAttribute (current);
  534. Move (0, 0);
  535. Rectangle f = Viewport;
  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. // By default, Command.Accept calls OnAccept, so we need to call it here to ensure that the event is fired.
  603. if (OnAccept () == true)
  604. {
  605. return true;
  606. }
  607. OpenSelectedItem?.Invoke (this, new ListViewItemEventArgs (_selected, value));
  608. return true;
  609. }
  610. /// <inheritdoc/>
  611. public override bool OnProcessKeyDown (Key a)
  612. {
  613. // Enable user to find & select an item by typing text
  614. if (CollectionNavigatorBase.IsCompatibleKey (a))
  615. {
  616. int? newItem = KeystrokeNavigator?.GetNextMatchingItem (SelectedItem, (char)a);
  617. if (newItem is int && newItem != -1)
  618. {
  619. SelectedItem = (int)newItem;
  620. EnsureSelectedItemVisible ();
  621. SetNeedsDisplay ();
  622. return true;
  623. }
  624. }
  625. return false;
  626. }
  627. /// <summary>Virtual method that will invoke the <see cref="RowRender"/>.</summary>
  628. /// <param name="rowEventArgs"></param>
  629. public virtual void OnRowRender (ListViewRowEventArgs rowEventArgs) { RowRender?.Invoke (this, rowEventArgs); }
  630. /// <summary>Invokes the <see cref="SelectedItemChanged"/> event if it is defined.</summary>
  631. /// <returns></returns>
  632. public virtual bool OnSelectedChanged ()
  633. {
  634. if (_selected != _lastSelectedItem)
  635. {
  636. object value = _source?.Count > 0 ? _source.ToList () [_selected] : null;
  637. SelectedItemChanged?.Invoke (this, new ListViewItemEventArgs (_selected, value));
  638. _lastSelectedItem = _selected;
  639. EnsureSelectedItemVisible ();
  640. return true;
  641. }
  642. return false;
  643. }
  644. /// <summary>This event is raised when the user Double Clicks on an item or presses ENTER to open the selected item.</summary>
  645. public event EventHandler<ListViewItemEventArgs> OpenSelectedItem;
  646. /// <inheritdoc/>
  647. public override void PositionCursor ()
  648. {
  649. if (_allowsMarking)
  650. {
  651. Move (0, _selected - _top);
  652. }
  653. else
  654. {
  655. Move (Viewport.Width - 1, _selected - _top);
  656. }
  657. }
  658. /// <summary>This event is invoked when this <see cref="ListView"/> is being drawn before rendering.</summary>
  659. public event EventHandler<ListViewRowEventArgs> RowRender;
  660. /// <summary>Scrolls the view down by <paramref name="items"/> items.</summary>
  661. /// <param name="items">Number of items to scroll down.</param>
  662. public virtual bool ScrollDown (int items)
  663. {
  664. _top = Math.Max (Math.Min (_top + items, _source.Count - 1), 0);
  665. SetNeedsDisplay ();
  666. return true;
  667. }
  668. /// <summary>Scrolls the view left.</summary>
  669. /// <param name="cols">Number of columns to scroll left.</param>
  670. public virtual bool ScrollLeft (int cols)
  671. {
  672. _left = Math.Max (_left - cols, 0);
  673. SetNeedsDisplay ();
  674. return true;
  675. }
  676. /// <summary>Scrolls the view right.</summary>
  677. /// <param name="cols">Number of columns to scroll right.</param>
  678. public virtual bool ScrollRight (int cols)
  679. {
  680. _left = Math.Max (Math.Min (_left + cols, MaxLength - 1), 0);
  681. SetNeedsDisplay ();
  682. return true;
  683. }
  684. /// <summary>Scrolls the view up by <paramref name="items"/> items.</summary>
  685. /// <param name="items">Number of items to scroll up.</param>
  686. public virtual bool ScrollUp (int items)
  687. {
  688. _top = Math.Max (_top - items, 0);
  689. SetNeedsDisplay ();
  690. return true;
  691. }
  692. /// <summary>This event is raised when the selected item in the <see cref="ListView"/> has changed.</summary>
  693. public event EventHandler<ListViewItemEventArgs> SelectedItemChanged;
  694. /// <summary>Sets the source of the <see cref="ListView"/> to an <see cref="IList"/>.</summary>
  695. /// <value>An object implementing the IList interface.</value>
  696. /// <remarks>
  697. /// Use the <see cref="Source"/> property to set a new <see cref="IListDataSource"/> source and use custome
  698. /// rendering.
  699. /// </remarks>
  700. public void SetSource (IList source)
  701. {
  702. if (source is null && (Source is null || !(Source is ListWrapper)))
  703. {
  704. Source = null;
  705. }
  706. else
  707. {
  708. Source = new ListWrapper (source);
  709. }
  710. }
  711. /// <summary>Sets the source to an <see cref="IList"/> value asynchronously.</summary>
  712. /// <value>An item implementing the IList interface.</value>
  713. /// <remarks>
  714. /// Use the <see cref="Source"/> property to set a new <see cref="IListDataSource"/> source and use custom
  715. /// rendering.
  716. /// </remarks>
  717. public Task SetSourceAsync (IList source)
  718. {
  719. return Task.Factory.StartNew (
  720. () =>
  721. {
  722. if (source is null && (Source is null || !(Source is ListWrapper)))
  723. {
  724. Source = null;
  725. }
  726. else
  727. {
  728. Source = new ListWrapper (source);
  729. }
  730. return source;
  731. },
  732. CancellationToken.None,
  733. TaskCreationOptions.DenyChildAttach,
  734. TaskScheduler.Default
  735. );
  736. }
  737. private void ListView_LayoutStarted (object sender, LayoutEventArgs e) { EnsureSelectedItemVisible (); }
  738. }
  739. /// <summary>
  740. /// Provides a default implementation of <see cref="IListDataSource"/> that renders <see cref="ListView"/> items
  741. /// using <see cref="object.ToString()"/>.
  742. /// </summary>
  743. public class ListWrapper : IListDataSource
  744. {
  745. private readonly int _count;
  746. private readonly BitArray _marks;
  747. private readonly IList _source;
  748. /// <inheritdoc/>
  749. public ListWrapper (IList source)
  750. {
  751. if (source is { })
  752. {
  753. _count = source.Count;
  754. _marks = new BitArray (_count);
  755. _source = source;
  756. Length = GetMaxLengthItem ();
  757. }
  758. }
  759. /// <inheritdoc/>
  760. public int Count => _source is { } ? _source.Count : 0;
  761. /// <inheritdoc/>
  762. public int Length { get; }
  763. /// <inheritdoc/>
  764. public void Render (
  765. ListView container,
  766. ConsoleDriver driver,
  767. bool marked,
  768. int item,
  769. int col,
  770. int line,
  771. int width,
  772. int start = 0
  773. )
  774. {
  775. container.Move (col, line);
  776. object t = _source? [item];
  777. if (t is null)
  778. {
  779. RenderUstr (driver, "", col, line, width);
  780. }
  781. else
  782. {
  783. if (t is string u)
  784. {
  785. RenderUstr (driver, u, col, line, width, start);
  786. }
  787. else if (t is string s)
  788. {
  789. RenderUstr (driver, s, col, line, width, start);
  790. }
  791. else
  792. {
  793. RenderUstr (driver, t.ToString (), col, line, width, start);
  794. }
  795. }
  796. }
  797. /// <inheritdoc/>
  798. public bool IsMarked (int item)
  799. {
  800. if (item >= 0 && item < _count)
  801. {
  802. return _marks [item];
  803. }
  804. return false;
  805. }
  806. /// <inheritdoc/>
  807. public void SetMark (int item, bool value)
  808. {
  809. if (item >= 0 && item < _count)
  810. {
  811. _marks [item] = value;
  812. }
  813. }
  814. /// <inheritdoc/>
  815. public IList ToList () { return _source; }
  816. /// <inheritdoc/>
  817. public int StartsWith (string search)
  818. {
  819. if (_source is null || _source?.Count == 0)
  820. {
  821. return -1;
  822. }
  823. for (var i = 0; i < _source.Count; i++)
  824. {
  825. object t = _source [i];
  826. if (t is string u)
  827. {
  828. if (u.ToUpper ().StartsWith (search.ToUpperInvariant ()))
  829. {
  830. return i;
  831. }
  832. }
  833. else if (t is string s)
  834. {
  835. if (s.StartsWith (search, StringComparison.InvariantCultureIgnoreCase))
  836. {
  837. return i;
  838. }
  839. }
  840. }
  841. return -1;
  842. }
  843. private int GetMaxLengthItem ()
  844. {
  845. if (_source is null || _source?.Count == 0)
  846. {
  847. return 0;
  848. }
  849. var maxLength = 0;
  850. for (var i = 0; i < _source.Count; i++)
  851. {
  852. object t = _source [i];
  853. int l;
  854. if (t is string u)
  855. {
  856. l = u.GetColumns ();
  857. }
  858. else if (t is string s)
  859. {
  860. l = s.Length;
  861. }
  862. else
  863. {
  864. l = t.ToString ().Length;
  865. }
  866. if (l > maxLength)
  867. {
  868. maxLength = l;
  869. }
  870. }
  871. return maxLength;
  872. }
  873. private void RenderUstr (ConsoleDriver driver, string ustr, int col, int line, int width, int start = 0)
  874. {
  875. string u = TextFormatter.ClipAndJustify (ustr, width, TextAlignment.Left);
  876. driver.AddStr (u);
  877. width -= u.GetColumns ();
  878. while (width-- > 0)
  879. {
  880. driver.AddRune ((Rune)' ');
  881. }
  882. }
  883. }