ListView.cs 33 KB

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