ListView.cs 39 KB

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