ListView.cs 37 KB

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