ListView.cs 37 KB

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