ListView.cs 33 KB

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