ListView.cs 34 KB

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