ListView.cs 33 KB

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