ListView.cs 31 KB

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