ListView.cs 32 KB

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