ListView.cs 36 KB

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