ListView.cs 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  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="ObservableCollection{T}"/> 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. if (_source is { })
  239. {
  240. _source.CollectionChanged += Source_CollectionChanged;
  241. }
  242. SetContentSize (new Size (_source?.Length ?? Viewport.Width, _source?.Count ?? Viewport.Width));
  243. if (IsInitialized)
  244. {
  245. Viewport = Viewport with { Y = 0 };
  246. }
  247. KeystrokeNavigator.Collection = _source?.ToList ();
  248. _selected = -1;
  249. _lastSelectedItem = -1;
  250. SetNeedsDisplay ();
  251. }
  252. }
  253. private void Source_CollectionChanged (object sender, NotifyCollectionChangedEventArgs e)
  254. {
  255. if (Source is { Count: > 0 } && _selected > Source.Count - 1)
  256. {
  257. SelectedItem = Source.Count - 1;
  258. }
  259. SetNeedsDisplay ();
  260. OnCollectionChanged (e);
  261. }
  262. /// <summary>Gets or sets the index of the item that will appear at the top of the <see cref="View.Viewport"/>.</summary>
  263. /// <remarks>
  264. /// This a helper property for accessing <c>listView.Viewport.Y</c>.
  265. /// </remarks>
  266. /// <value>The top item.</value>
  267. public int TopItem
  268. {
  269. get => Viewport.Y;
  270. set
  271. {
  272. if (_source is null)
  273. {
  274. return;
  275. }
  276. Viewport = Viewport with { Y = value };
  277. }
  278. }
  279. /// <summary>
  280. /// If <see cref="AllowsMarking"/> and <see cref="AllowsMultipleSelection"/> are both <see langword="true"/>,
  281. /// unmarks all marked items other than the currently selected.
  282. /// </summary>
  283. /// <returns><see langword="true"/> if unmarking was successful.</returns>
  284. public virtual bool AllowsAll ()
  285. {
  286. if (!_allowsMarking)
  287. {
  288. return false;
  289. }
  290. if (!AllowsMultipleSelection)
  291. {
  292. for (var i = 0; i < Source.Count; i++)
  293. {
  294. if (Source.IsMarked (i) && i != _selected)
  295. {
  296. Source.SetMark (i, false);
  297. return true;
  298. }
  299. }
  300. }
  301. return true;
  302. }
  303. /// <summary>Ensures the selected item is always visible on the screen.</summary>
  304. public void EnsureSelectedItemVisible ()
  305. {
  306. if (SuperView?.IsInitialized == true)
  307. {
  308. if (_selected < Viewport.Y)
  309. {
  310. // TODO: The Max check here is not needed because, by default, Viewport enforces staying w/in ContentArea (View.ScrollSettings).
  311. Viewport = Viewport with { Y = _selected };
  312. }
  313. else if (Viewport.Height > 0 && _selected >= Viewport.Y + Viewport.Height)
  314. {
  315. Viewport = Viewport with { Y = _selected - Viewport.Height + 1 };
  316. }
  317. LayoutStarted -= ListView_LayoutStarted;
  318. }
  319. else
  320. {
  321. LayoutStarted += ListView_LayoutStarted;
  322. }
  323. }
  324. /// <summary>Marks the <see cref="SelectedItem"/> if it is not already marked.</summary>
  325. /// <returns><see langword="true"/> if the <see cref="SelectedItem"/> was marked.</returns>
  326. public virtual bool MarkUnmarkRow ()
  327. {
  328. if (AllowsAll ())
  329. {
  330. Source.SetMark (SelectedItem, !Source.IsMarked (SelectedItem));
  331. SetNeedsDisplay ();
  332. return true;
  333. }
  334. return false;
  335. }
  336. /// <inheritdoc/>
  337. protected internal override bool OnMouseEvent (MouseEvent me)
  338. {
  339. if (!me.Flags.HasFlag (MouseFlags.Button1Clicked)
  340. && !me.Flags.HasFlag (MouseFlags.Button1DoubleClicked)
  341. && me.Flags != MouseFlags.WheeledDown
  342. && me.Flags != MouseFlags.WheeledUp
  343. && me.Flags != MouseFlags.WheeledRight
  344. && me.Flags != MouseFlags.WheeledLeft)
  345. {
  346. return false;
  347. }
  348. if (!HasFocus && CanFocus)
  349. {
  350. SetFocus ();
  351. }
  352. if (_source is null)
  353. {
  354. return false;
  355. }
  356. if (me.Flags == MouseFlags.WheeledDown)
  357. {
  358. ScrollVertical (1);
  359. return true;
  360. }
  361. if (me.Flags == MouseFlags.WheeledUp)
  362. {
  363. ScrollVertical (-1);
  364. return true;
  365. }
  366. if (me.Flags == MouseFlags.WheeledRight)
  367. {
  368. ScrollHorizontal (1);
  369. return true;
  370. }
  371. if (me.Flags == MouseFlags.WheeledLeft)
  372. {
  373. ScrollHorizontal (-1);
  374. return true;
  375. }
  376. if (me.Position.Y + Viewport.Y >= _source.Count
  377. || me.Position.Y + Viewport.Y < 0
  378. || me.Position.Y + Viewport.Y > Viewport.Y + Viewport.Height)
  379. {
  380. return true;
  381. }
  382. _selected = Viewport.Y + me.Position.Y;
  383. if (AllowsAll ())
  384. {
  385. Source.SetMark (SelectedItem, !Source.IsMarked (SelectedItem));
  386. SetNeedsDisplay ();
  387. return true;
  388. }
  389. OnSelectedChanged ();
  390. SetNeedsDisplay ();
  391. if (me.Flags == MouseFlags.Button1DoubleClicked)
  392. {
  393. OnOpenSelectedItem ();
  394. }
  395. return true;
  396. }
  397. /// <summary>Changes the <see cref="SelectedItem"/> to the next item in the list, scrolling the list if needed.</summary>
  398. /// <returns></returns>
  399. public virtual bool MoveDown ()
  400. {
  401. if (_source is null || _source.Count == 0)
  402. {
  403. // Do we set lastSelectedItem to -1 here?
  404. return false; //Nothing for us to move to
  405. }
  406. if (_selected >= _source.Count)
  407. {
  408. // If for some reason we are currently outside of the
  409. // valid values range, we should select the bottommost valid value.
  410. // This can occur if the backing data source changes.
  411. _selected = _source.Count - 1;
  412. OnSelectedChanged ();
  413. SetNeedsDisplay ();
  414. }
  415. else if (_selected + 1 < _source.Count)
  416. {
  417. //can move by down by one.
  418. _selected++;
  419. if (_selected >= Viewport.Y + Viewport.Height)
  420. {
  421. Viewport = Viewport with { Y = Viewport.Y + 1 };
  422. }
  423. else if (_selected < Viewport.Y)
  424. {
  425. Viewport = Viewport with { Y = _selected };
  426. }
  427. OnSelectedChanged ();
  428. SetNeedsDisplay ();
  429. }
  430. else if (_selected == 0)
  431. {
  432. OnSelectedChanged ();
  433. SetNeedsDisplay ();
  434. }
  435. else if (_selected >= Viewport.Y + Viewport.Height)
  436. {
  437. Viewport = Viewport with { Y = _source.Count - Viewport.Height };
  438. SetNeedsDisplay ();
  439. }
  440. return true;
  441. }
  442. /// <summary>Changes the <see cref="SelectedItem"/> to last item in the list, scrolling the list if needed.</summary>
  443. /// <returns></returns>
  444. public virtual bool MoveEnd ()
  445. {
  446. if (_source is { Count: > 0 } && _selected != _source.Count - 1)
  447. {
  448. _selected = _source.Count - 1;
  449. if (Viewport.Y + _selected > Viewport.Height - 1)
  450. {
  451. Viewport = Viewport with { Y = _selected };
  452. }
  453. OnSelectedChanged ();
  454. SetNeedsDisplay ();
  455. }
  456. return true;
  457. }
  458. /// <summary>Changes the <see cref="SelectedItem"/> to the first item in the list, scrolling the list if needed.</summary>
  459. /// <returns></returns>
  460. public virtual bool MoveHome ()
  461. {
  462. if (_selected != 0)
  463. {
  464. _selected = 0;
  465. Viewport = Viewport with { Y = _selected };
  466. OnSelectedChanged ();
  467. SetNeedsDisplay ();
  468. }
  469. return true;
  470. }
  471. /// <summary>
  472. /// Changes the <see cref="SelectedItem"/> to the item just below the bottom of the visible list, scrolling if
  473. /// needed.
  474. /// </summary>
  475. /// <returns></returns>
  476. public virtual bool MovePageDown ()
  477. {
  478. if (_source is null)
  479. {
  480. return true;
  481. }
  482. int n = _selected + Viewport.Height;
  483. if (n >= _source.Count)
  484. {
  485. n = _source.Count - 1;
  486. }
  487. if (n != _selected)
  488. {
  489. _selected = n;
  490. if (_source.Count >= Viewport.Height)
  491. {
  492. Viewport = Viewport with { Y = _selected };
  493. }
  494. else
  495. {
  496. Viewport = Viewport with { Y = 0 };
  497. }
  498. OnSelectedChanged ();
  499. SetNeedsDisplay ();
  500. }
  501. return true;
  502. }
  503. /// <summary>Changes the <see cref="SelectedItem"/> to the item at the top of the visible list.</summary>
  504. /// <returns></returns>
  505. public virtual bool MovePageUp ()
  506. {
  507. int n = _selected - Viewport.Height;
  508. if (n < 0)
  509. {
  510. n = 0;
  511. }
  512. if (n != _selected)
  513. {
  514. _selected = n;
  515. Viewport = Viewport with { Y = _selected };
  516. OnSelectedChanged ();
  517. SetNeedsDisplay ();
  518. }
  519. return true;
  520. }
  521. /// <summary>Changes the <see cref="SelectedItem"/> to the previous item in the list, scrolling the list if needed.</summary>
  522. /// <returns></returns>
  523. public virtual bool MoveUp ()
  524. {
  525. if (_source is null || _source.Count == 0)
  526. {
  527. // Do we set lastSelectedItem to -1 here?
  528. return false; //Nothing for us to move to
  529. }
  530. if (_selected >= _source.Count)
  531. {
  532. // If for some reason we are currently outside of the
  533. // valid values range, we should select the bottommost valid value.
  534. // This can occur if the backing data source changes.
  535. _selected = _source.Count - 1;
  536. OnSelectedChanged ();
  537. SetNeedsDisplay ();
  538. }
  539. else if (_selected > 0)
  540. {
  541. _selected--;
  542. if (_selected > Source.Count)
  543. {
  544. _selected = Source.Count - 1;
  545. }
  546. if (_selected < Viewport.Y)
  547. {
  548. Viewport = Viewport with { Y = _selected };
  549. }
  550. else if (_selected > Viewport.Y + Viewport.Height)
  551. {
  552. Viewport = Viewport with { Y = _selected - Viewport.Height + 1 };
  553. }
  554. OnSelectedChanged ();
  555. SetNeedsDisplay ();
  556. }
  557. else if (_selected < Viewport.Y)
  558. {
  559. Viewport = Viewport with { Y = _selected };
  560. SetNeedsDisplay ();
  561. }
  562. return true;
  563. }
  564. /// <inheritdoc/>
  565. public override void OnDrawContent (Rectangle viewport)
  566. {
  567. base.OnDrawContent (viewport);
  568. Attribute current = ColorScheme.Focus;
  569. Driver.SetAttribute (current);
  570. Move (0, 0);
  571. Rectangle f = Viewport;
  572. int item = Viewport.Y;
  573. bool focused = HasFocus;
  574. int col = _allowsMarking ? 2 : 0;
  575. int start = Viewport.X;
  576. for (var row = 0; row < f.Height; row++, item++)
  577. {
  578. bool isSelected = item == _selected;
  579. Attribute newcolor = focused ? isSelected ? ColorScheme.Focus : GetNormalColor () :
  580. isSelected ? ColorScheme.HotNormal : GetNormalColor ();
  581. if (newcolor != current)
  582. {
  583. Driver.SetAttribute (newcolor);
  584. current = newcolor;
  585. }
  586. Move (0, row);
  587. if (_source is null || item >= _source.Count)
  588. {
  589. for (var c = 0; c < f.Width; c++)
  590. {
  591. Driver.AddRune ((Rune)' ');
  592. }
  593. }
  594. else
  595. {
  596. var rowEventArgs = new ListViewRowEventArgs (item);
  597. OnRowRender (rowEventArgs);
  598. if (rowEventArgs.RowAttribute is { } && current != rowEventArgs.RowAttribute)
  599. {
  600. current = (Attribute)rowEventArgs.RowAttribute;
  601. Driver.SetAttribute (current);
  602. }
  603. if (_allowsMarking)
  604. {
  605. Driver.AddRune (
  606. _source.IsMarked (item) ? AllowsMultipleSelection ? Glyphs.Checked : Glyphs.Selected :
  607. AllowsMultipleSelection ? Glyphs.UnChecked : Glyphs.UnSelected
  608. );
  609. Driver.AddRune ((Rune)' ');
  610. }
  611. Source.Render (this, Driver, isSelected, item, col, row, f.Width - col, start);
  612. }
  613. }
  614. }
  615. /// <inheritdoc/>
  616. public override bool OnEnter (View view)
  617. {
  618. if (_lastSelectedItem != _selected)
  619. {
  620. EnsureSelectedItemVisible ();
  621. }
  622. return base.OnEnter (view);
  623. }
  624. // TODO: This should be cancelable
  625. /// <summary>Invokes the <see cref="OpenSelectedItem"/> event if it is defined.</summary>
  626. /// <returns><see langword="true"/> if the <see cref="OpenSelectedItem"/> event was fired.</returns>
  627. public bool OnOpenSelectedItem ()
  628. {
  629. if (_source is null || _source.Count <= _selected || _selected < 0 || OpenSelectedItem is null)
  630. {
  631. return false;
  632. }
  633. object value = _source.ToList () [_selected];
  634. // By default, Command.Accept calls OnAccept, so we need to call it here to ensure that the event is fired.
  635. if (OnAccept () == true)
  636. {
  637. return true;
  638. }
  639. OpenSelectedItem?.Invoke (this, new ListViewItemEventArgs (_selected, value));
  640. return true;
  641. }
  642. /// <inheritdoc/>
  643. public override bool OnProcessKeyDown (Key a)
  644. {
  645. // Enable user to find & select an item by typing text
  646. if (CollectionNavigatorBase.IsCompatibleKey (a))
  647. {
  648. int? newItem = KeystrokeNavigator?.GetNextMatchingItem (SelectedItem, (char)a);
  649. if (newItem is int && newItem != -1)
  650. {
  651. SelectedItem = (int)newItem;
  652. EnsureSelectedItemVisible ();
  653. SetNeedsDisplay ();
  654. return true;
  655. }
  656. }
  657. return false;
  658. }
  659. /// <summary>Virtual method that will invoke the <see cref="RowRender"/>.</summary>
  660. /// <param name="rowEventArgs"></param>
  661. public virtual void OnRowRender (ListViewRowEventArgs rowEventArgs) { RowRender?.Invoke (this, rowEventArgs); }
  662. /// <summary>Invokes the <see cref="SelectedItemChanged"/> event if it is defined.</summary>
  663. /// <returns></returns>
  664. public virtual bool OnSelectedChanged ()
  665. {
  666. if (_selected != _lastSelectedItem)
  667. {
  668. object value = _source?.Count > 0 ? _source.ToList () [_selected] : null;
  669. SelectedItemChanged?.Invoke (this, new ListViewItemEventArgs (_selected, value));
  670. _lastSelectedItem = _selected;
  671. EnsureSelectedItemVisible ();
  672. return true;
  673. }
  674. return false;
  675. }
  676. /// <summary>This event is raised when the user Double Clicks on an item or presses ENTER to open the selected item.</summary>
  677. public event EventHandler<ListViewItemEventArgs> OpenSelectedItem;
  678. /// <inheritdoc/>
  679. public override Point? PositionCursor ()
  680. {
  681. int x = 0;
  682. int y = _selected - Viewport.Y;
  683. if (!_allowsMarking)
  684. {
  685. x = Viewport.Width - 1;
  686. }
  687. Move (x, y);
  688. return null; // Don't show the cursor
  689. }
  690. /// <summary>This event is invoked when this <see cref="ListView"/> is being drawn before rendering.</summary>
  691. public event EventHandler<ListViewRowEventArgs> RowRender;
  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>
  695. /// Event to raise when an item is added, removed, or moved, or the entire list is refreshed.
  696. /// </summary>
  697. public event NotifyCollectionChangedEventHandler CollectionChanged;
  698. /// <summary>Sets the source of the <see cref="ListView"/> to an <see cref="IList"/>.</summary>
  699. /// <value>An object implementing the IList interface.</value>
  700. /// <remarks>
  701. /// Use the <see cref="Source"/> property to set a new <see cref="IListDataSource"/> source and use custom
  702. /// rendering.
  703. /// </remarks>
  704. public void SetSource<T> (ObservableCollection<T> source)
  705. {
  706. if (source is null && Source is not ListWrapper<T>)
  707. {
  708. Source = null;
  709. }
  710. else
  711. {
  712. Source = new ListWrapper<T> (source);
  713. }
  714. }
  715. /// <summary>Sets the source to an <see cref="IList"/> value asynchronously.</summary>
  716. /// <value>An item implementing the IList interface.</value>
  717. /// <remarks>
  718. /// Use the <see cref="Source"/> property to set a new <see cref="IListDataSource"/> source and use custom
  719. /// rendering.
  720. /// </remarks>
  721. public Task SetSourceAsync<T> (ObservableCollection<T> source)
  722. {
  723. return Task.Factory.StartNew (
  724. () =>
  725. {
  726. if (source is null && (Source is null || !(Source is ListWrapper<T>)))
  727. {
  728. Source = null;
  729. }
  730. else
  731. {
  732. Source = new ListWrapper<T> (source);
  733. }
  734. return source;
  735. },
  736. CancellationToken.None,
  737. TaskCreationOptions.DenyChildAttach,
  738. TaskScheduler.Default
  739. );
  740. }
  741. private void ListView_LayoutStarted (object sender, LayoutEventArgs e) { EnsureSelectedItemVisible (); }
  742. /// <summary>
  743. /// Call the event to raise when an item is added, removed, or moved, or the entire list is refreshed.
  744. /// </summary>
  745. /// <param name="e"></param>
  746. protected virtual void OnCollectionChanged (NotifyCollectionChangedEventArgs e) { CollectionChanged?.Invoke (this, e); }
  747. }
  748. /// <summary>
  749. /// Provides a default implementation of <see cref="IListDataSource"/> that renders <see cref="ListView"/> items
  750. /// using <see cref="object.ToString()"/>.
  751. /// </summary>
  752. public class ListWrapper<T> : IListDataSource
  753. {
  754. private int _count;
  755. private BitArray _marks;
  756. private readonly ObservableCollection<T> _source;
  757. /// <inheritdoc/>
  758. public ListWrapper (ObservableCollection<T> source)
  759. {
  760. if (source is { })
  761. {
  762. _count = source.Count;
  763. _marks = new BitArray (_count);
  764. _source = source;
  765. _source.CollectionChanged += (s, e) =>
  766. {
  767. CheckAndResizeMarksIfRequired ();
  768. CollectionChanged?.Invoke (s, e);
  769. };
  770. Length = GetMaxLengthItem ();
  771. }
  772. }
  773. /// <inheritdoc />
  774. public event NotifyCollectionChangedEventHandler CollectionChanged;
  775. /// <inheritdoc/>
  776. public int Count => _source?.Count ?? 0;
  777. /// <inheritdoc/>
  778. public int Length { get; private set; }
  779. void CheckAndResizeMarksIfRequired ()
  780. {
  781. if (_source != null && _count != _source.Count)
  782. {
  783. _count = _source.Count;
  784. BitArray newMarks = new BitArray (_count);
  785. for (var i = 0; i < Math.Min (_marks.Length, newMarks.Length); i++)
  786. {
  787. newMarks [i] = _marks [i];
  788. }
  789. _marks = newMarks;
  790. Length = GetMaxLengthItem ();
  791. }
  792. }
  793. /// <inheritdoc/>
  794. public void Render (
  795. ListView container,
  796. ConsoleDriver driver,
  797. bool marked,
  798. int item,
  799. int col,
  800. int line,
  801. int width,
  802. int start = 0
  803. )
  804. {
  805. container.Move (Math.Max (col - start, 0), line);
  806. if (_source is { })
  807. {
  808. object t = _source [item];
  809. if (t is null)
  810. {
  811. RenderUstr (driver, "", col, line, width);
  812. }
  813. else
  814. {
  815. if (t is string s)
  816. {
  817. RenderUstr (driver, s, col, line, width, start);
  818. }
  819. else
  820. {
  821. RenderUstr (driver, t.ToString (), col, line, width, start);
  822. }
  823. }
  824. }
  825. }
  826. /// <inheritdoc/>
  827. public bool IsMarked (int item)
  828. {
  829. if (item >= 0 && item < _count)
  830. {
  831. return _marks [item];
  832. }
  833. return false;
  834. }
  835. /// <inheritdoc/>
  836. public void SetMark (int item, bool value)
  837. {
  838. if (item >= 0 && item < _count)
  839. {
  840. _marks [item] = value;
  841. }
  842. }
  843. /// <inheritdoc/>
  844. public IList ToList () { return _source; }
  845. /// <inheritdoc/>
  846. public int StartsWith (string search)
  847. {
  848. if (_source is null || _source?.Count == 0)
  849. {
  850. return -1;
  851. }
  852. for (var i = 0; i < _source.Count; i++)
  853. {
  854. object t = _source [i];
  855. if (t is string u)
  856. {
  857. if (u.ToUpper ().StartsWith (search.ToUpperInvariant ()))
  858. {
  859. return i;
  860. }
  861. }
  862. else if (t is string s)
  863. {
  864. if (s.StartsWith (search, StringComparison.InvariantCultureIgnoreCase))
  865. {
  866. return i;
  867. }
  868. }
  869. }
  870. return -1;
  871. }
  872. private int GetMaxLengthItem ()
  873. {
  874. if (_source is null || _source?.Count == 0)
  875. {
  876. return 0;
  877. }
  878. var maxLength = 0;
  879. for (var i = 0; i < _source.Count; i++)
  880. {
  881. object t = _source [i];
  882. int l;
  883. if (t is string u)
  884. {
  885. l = u.GetColumns ();
  886. }
  887. else if (t is string s)
  888. {
  889. l = s.Length;
  890. }
  891. else
  892. {
  893. l = t.ToString ().Length;
  894. }
  895. if (l > maxLength)
  896. {
  897. maxLength = l;
  898. }
  899. }
  900. return maxLength;
  901. }
  902. private void RenderUstr (ConsoleDriver driver, string ustr, int col, int line, int width, int start = 0)
  903. {
  904. string str = start > ustr.GetColumns () ? string.Empty : ustr.Substring (Math.Min (start, ustr.ToRunes ().Length - 1));
  905. string u = TextFormatter.ClipAndJustify (str, width, Alignment.Start);
  906. driver.AddStr (u);
  907. width -= u.GetColumns ();
  908. while (width-- > 0)
  909. {
  910. driver.AddRune ((Rune)' ');
  911. }
  912. }
  913. }