ListView.cs 32 KB

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