ListView.cs 37 KB

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