ListView.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  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. SetContentSize (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.Position.Y + Viewport.Y >= _source.Count
  358. || me.Position.Y + Viewport.Y < 0
  359. || me.Position.Y + Viewport.Y > Viewport.Y + Viewport.Height)
  360. {
  361. return true;
  362. }
  363. _selected = Viewport.Y + me.Position.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 (_lastSelectedItem != _selected)
  600. {
  601. EnsureSelectedItemVisible ();
  602. }
  603. return base.OnEnter (view);
  604. }
  605. // TODO: This should be cancelable
  606. /// <summary>Invokes the <see cref="OpenSelectedItem"/> event if it is defined.</summary>
  607. /// <returns><see langword="true"/> if the <see cref="OpenSelectedItem"/> event was fired.</returns>
  608. public bool OnOpenSelectedItem ()
  609. {
  610. if (_source is null || _source.Count <= _selected || _selected < 0 || OpenSelectedItem is null)
  611. {
  612. return false;
  613. }
  614. object value = _source.ToList () [_selected];
  615. // By default, Command.Accept calls OnAccept, so we need to call it here to ensure that the event is fired.
  616. if (OnAccept () == true)
  617. {
  618. return true;
  619. }
  620. OpenSelectedItem?.Invoke (this, new ListViewItemEventArgs (_selected, value));
  621. return true;
  622. }
  623. /// <inheritdoc/>
  624. public override bool OnProcessKeyDown (Key a)
  625. {
  626. // Enable user to find & select an item by typing text
  627. if (CollectionNavigatorBase.IsCompatibleKey (a))
  628. {
  629. int? newItem = KeystrokeNavigator?.GetNextMatchingItem (SelectedItem, (char)a);
  630. if (newItem is int && newItem != -1)
  631. {
  632. SelectedItem = (int)newItem;
  633. EnsureSelectedItemVisible ();
  634. SetNeedsDisplay ();
  635. return true;
  636. }
  637. }
  638. return false;
  639. }
  640. /// <summary>Virtual method that will invoke the <see cref="RowRender"/>.</summary>
  641. /// <param name="rowEventArgs"></param>
  642. public virtual void OnRowRender (ListViewRowEventArgs rowEventArgs) { RowRender?.Invoke (this, rowEventArgs); }
  643. /// <summary>Invokes the <see cref="SelectedItemChanged"/> event if it is defined.</summary>
  644. /// <returns></returns>
  645. public virtual bool OnSelectedChanged ()
  646. {
  647. if (_selected != _lastSelectedItem)
  648. {
  649. object value = _source?.Count > 0 ? _source.ToList () [_selected] : null;
  650. SelectedItemChanged?.Invoke (this, new ListViewItemEventArgs (_selected, value));
  651. _lastSelectedItem = _selected;
  652. EnsureSelectedItemVisible ();
  653. return true;
  654. }
  655. return false;
  656. }
  657. /// <summary>This event is raised when the user Double Clicks on an item or presses ENTER to open the selected item.</summary>
  658. public event EventHandler<ListViewItemEventArgs> OpenSelectedItem;
  659. /// <inheritdoc/>
  660. public override Point? PositionCursor ()
  661. {
  662. int x = 0;
  663. int y = _selected - Viewport.Y;
  664. if (!_allowsMarking)
  665. {
  666. x = Viewport.Width - 1;
  667. }
  668. Move (x, y);
  669. return null; // Don't show the cursor
  670. }
  671. /// <summary>This event is invoked when this <see cref="ListView"/> is being drawn before rendering.</summary>
  672. public event EventHandler<ListViewRowEventArgs> RowRender;
  673. /// <summary>This event is raised when the selected item in the <see cref="ListView"/> has changed.</summary>
  674. public event EventHandler<ListViewItemEventArgs> SelectedItemChanged;
  675. /// <summary>Sets the source of the <see cref="ListView"/> to an <see cref="IList"/>.</summary>
  676. /// <value>An object implementing the IList interface.</value>
  677. /// <remarks>
  678. /// Use the <see cref="Source"/> property to set a new <see cref="IListDataSource"/> source and use custome
  679. /// rendering.
  680. /// </remarks>
  681. public void SetSource (IList source)
  682. {
  683. if (source is null && (Source is null || !(Source is ListWrapper)))
  684. {
  685. Source = null;
  686. }
  687. else
  688. {
  689. Source = new ListWrapper (source);
  690. }
  691. }
  692. /// <summary>Sets the source to an <see cref="IList"/> value asynchronously.</summary>
  693. /// <value>An item implementing the IList interface.</value>
  694. /// <remarks>
  695. /// Use the <see cref="Source"/> property to set a new <see cref="IListDataSource"/> source and use custom
  696. /// rendering.
  697. /// </remarks>
  698. public Task SetSourceAsync (IList source)
  699. {
  700. return Task.Factory.StartNew (
  701. () =>
  702. {
  703. if (source is null && (Source is null || !(Source is ListWrapper)))
  704. {
  705. Source = null;
  706. }
  707. else
  708. {
  709. Source = new ListWrapper (source);
  710. }
  711. return source;
  712. },
  713. CancellationToken.None,
  714. TaskCreationOptions.DenyChildAttach,
  715. TaskScheduler.Default
  716. );
  717. }
  718. private void ListView_LayoutStarted (object sender, LayoutEventArgs e) { EnsureSelectedItemVisible (); }
  719. }
  720. /// <summary>
  721. /// Provides a default implementation of <see cref="IListDataSource"/> that renders <see cref="ListView"/> items
  722. /// using <see cref="object.ToString()"/>.
  723. /// </summary>
  724. public class ListWrapper : IListDataSource
  725. {
  726. private readonly int _count;
  727. private readonly BitArray _marks;
  728. private readonly IList _source;
  729. /// <inheritdoc/>
  730. public ListWrapper (IList source)
  731. {
  732. if (source is { })
  733. {
  734. _count = source.Count;
  735. _marks = new BitArray (_count);
  736. _source = source;
  737. Length = GetMaxLengthItem ();
  738. }
  739. }
  740. /// <inheritdoc/>
  741. public int Count => _source is { } ? _source.Count : 0;
  742. /// <inheritdoc/>
  743. public int Length { get; }
  744. /// <inheritdoc/>
  745. public void Render (
  746. ListView container,
  747. ConsoleDriver driver,
  748. bool marked,
  749. int item,
  750. int col,
  751. int line,
  752. int width,
  753. int start = 0
  754. )
  755. {
  756. container.Move (Math.Max (col - start, 0), line);
  757. object t = _source? [item];
  758. if (t is null)
  759. {
  760. RenderUstr (driver, "", col, line, width);
  761. }
  762. else
  763. {
  764. if (t is string u)
  765. {
  766. RenderUstr (driver, u, col, line, width, start);
  767. }
  768. else if (t is string s)
  769. {
  770. RenderUstr (driver, s, col, line, width, start);
  771. }
  772. else
  773. {
  774. RenderUstr (driver, t.ToString (), col, line, width, start);
  775. }
  776. }
  777. }
  778. /// <inheritdoc/>
  779. public bool IsMarked (int item)
  780. {
  781. if (item >= 0 && item < _count)
  782. {
  783. return _marks [item];
  784. }
  785. return false;
  786. }
  787. /// <inheritdoc/>
  788. public void SetMark (int item, bool value)
  789. {
  790. if (item >= 0 && item < _count)
  791. {
  792. _marks [item] = value;
  793. }
  794. }
  795. /// <inheritdoc/>
  796. public IList ToList () { return _source; }
  797. /// <inheritdoc/>
  798. public int StartsWith (string search)
  799. {
  800. if (_source is null || _source?.Count == 0)
  801. {
  802. return -1;
  803. }
  804. for (var i = 0; i < _source.Count; i++)
  805. {
  806. object t = _source [i];
  807. if (t is string u)
  808. {
  809. if (u.ToUpper ().StartsWith (search.ToUpperInvariant ()))
  810. {
  811. return i;
  812. }
  813. }
  814. else if (t is string s)
  815. {
  816. if (s.StartsWith (search, StringComparison.InvariantCultureIgnoreCase))
  817. {
  818. return i;
  819. }
  820. }
  821. }
  822. return -1;
  823. }
  824. private int GetMaxLengthItem ()
  825. {
  826. if (_source is null || _source?.Count == 0)
  827. {
  828. return 0;
  829. }
  830. var maxLength = 0;
  831. for (var i = 0; i < _source.Count; i++)
  832. {
  833. object t = _source [i];
  834. int l;
  835. if (t is string u)
  836. {
  837. l = u.GetColumns ();
  838. }
  839. else if (t is string s)
  840. {
  841. l = s.Length;
  842. }
  843. else
  844. {
  845. l = t.ToString ().Length;
  846. }
  847. if (l > maxLength)
  848. {
  849. maxLength = l;
  850. }
  851. }
  852. return maxLength;
  853. }
  854. private void RenderUstr (ConsoleDriver driver, string ustr, int col, int line, int width, int start = 0)
  855. {
  856. string str = start > ustr.GetColumns () ? string.Empty : ustr.Substring (Math.Min (start, ustr.ToRunes ().Length - 1));
  857. string u = TextFormatter.ClipAndJustify (str, width, Alignment.Start);
  858. driver.AddStr (u);
  859. width -= u.GetColumns ();
  860. while (width-- > 0)
  861. {
  862. driver.AddRune ((Rune)' ');
  863. }
  864. }
  865. }