ListView.cs 35 KB

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