ListView.cs 31 KB

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