ListView.cs 31 KB

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