ListView.cs 40 KB

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