ListView.cs 31 KB

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