ListView.cs 39 KB

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