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