ListView.cs 37 KB

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