ListView.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185
  1. using System.Collections;
  2. using System.Collections.ObjectModel;
  3. using System.Collections.Specialized;
  4. namespace Terminal.Gui.Views;
  5. /// <summary>
  6. /// Provides 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 = false;
  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 = Attribute.Default;
  618. Move (0, 0);
  619. Rectangle f = Viewport;
  620. int item = Viewport.Y;
  621. bool focused = HasFocus;
  622. int col = _allowsMarking ? 2 : 0;
  623. int start = Viewport.X;
  624. for (var row = 0; row < f.Height; row++, item++)
  625. {
  626. bool isSelected = item == _selected;
  627. Attribute newAttribute = focused ? isSelected ? GetAttributeForRole (VisualRole.Focus) : GetAttributeForRole (VisualRole.Normal) :
  628. isSelected ? GetAttributeForRole (VisualRole.Active) : GetAttributeForRole (VisualRole.Normal);
  629. if (newAttribute != current)
  630. {
  631. SetAttribute (newAttribute);
  632. current = newAttribute;
  633. }
  634. Move (0, row);
  635. if (_source is null || item >= _source.Count)
  636. {
  637. for (var c = 0; c < f.Width; c++)
  638. {
  639. AddRune ((Rune)' ');
  640. }
  641. }
  642. else
  643. {
  644. var rowEventArgs = new ListViewRowEventArgs (item);
  645. OnRowRender (rowEventArgs);
  646. if (rowEventArgs.RowAttribute is { } && current != rowEventArgs.RowAttribute)
  647. {
  648. current = (Attribute)rowEventArgs.RowAttribute;
  649. SetAttribute (current);
  650. }
  651. if (_allowsMarking)
  652. {
  653. AddRune (
  654. _source.IsMarked (item) ? AllowsMultipleSelection ? Glyphs.CheckStateChecked : Glyphs.Selected :
  655. AllowsMultipleSelection ? Glyphs.CheckStateUnChecked : Glyphs.UnSelected
  656. );
  657. AddRune ((Rune)' ');
  658. }
  659. Source.Render (this, isSelected, item, col, row, f.Width - col, start);
  660. }
  661. }
  662. return true;
  663. }
  664. /// <inheritdoc/>
  665. protected override void OnHasFocusChanged (bool newHasFocus, [CanBeNull] View currentFocused, [CanBeNull] View newFocused)
  666. {
  667. if (newHasFocus && _lastSelectedItem != _selected)
  668. {
  669. EnsureSelectedItemVisible ();
  670. }
  671. }
  672. /// <summary>Invokes the <see cref="OpenSelectedItem"/> event if it is defined.</summary>
  673. /// <returns><see langword="true"/> if the <see cref="OpenSelectedItem"/> event was fired.</returns>
  674. public bool OnOpenSelectedItem ()
  675. {
  676. if (_source is null || _source.Count <= _selected || _selected < 0 || OpenSelectedItem is null)
  677. {
  678. return false;
  679. }
  680. object value = _source.ToList () [_selected];
  681. OpenSelectedItem?.Invoke (this, new ListViewItemEventArgs (_selected, value));
  682. // BUGBUG: this should not blindly return true.
  683. return true;
  684. }
  685. /// <inheritdoc/>
  686. protected override bool OnKeyDown (Key key)
  687. {
  688. // If the key was bound to key command, let normal KeyDown processing happen. This enables overriding the default handling.
  689. // See: https://github.com/gui-cs/Terminal.Gui/issues/3950#issuecomment-2807350939
  690. if (KeyBindings.TryGet (key, out _))
  691. {
  692. return false;
  693. }
  694. // Enable user to find & select an item by typing text
  695. if (KeystrokeNavigator.Matcher.IsCompatibleKey (key))
  696. {
  697. int? newItem = KeystrokeNavigator?.GetNextMatchingItem (SelectedItem, (char)key);
  698. if (newItem is { } && newItem != -1)
  699. {
  700. SelectedItem = (int)newItem;
  701. EnsureSelectedItemVisible ();
  702. SetNeedsDraw ();
  703. return true;
  704. }
  705. }
  706. return false;
  707. }
  708. /// <summary>Virtual method that will invoke the <see cref="RowRender"/>.</summary>
  709. /// <param name="rowEventArgs"></param>
  710. public virtual void OnRowRender (ListViewRowEventArgs rowEventArgs) { RowRender?.Invoke (this, rowEventArgs); }
  711. // TODO: Use standard event model
  712. /// <summary>Invokes the <see cref="SelectedItemChanged"/> event if it is defined.</summary>
  713. /// <returns></returns>
  714. public virtual bool OnSelectedChanged ()
  715. {
  716. if (_selected != _lastSelectedItem)
  717. {
  718. object value = _source?.Count > 0 ? _source.ToList () [_selected] : null;
  719. SelectedItemChanged?.Invoke (this, new ListViewItemEventArgs (_selected, value));
  720. _lastSelectedItem = _selected;
  721. EnsureSelectedItemVisible ();
  722. return true;
  723. }
  724. return false;
  725. }
  726. /// <summary>This event is raised when the user Double-Clicks on an item or presses ENTER to open the selected item.</summary>
  727. public event EventHandler<ListViewItemEventArgs> OpenSelectedItem;
  728. /// <summary>This event is invoked when this <see cref="ListView"/> is being drawn before rendering.</summary>
  729. public event EventHandler<ListViewRowEventArgs> RowRender;
  730. /// <summary>This event is raised when the selected item in the <see cref="ListView"/> has changed.</summary>
  731. public event EventHandler<ListViewItemEventArgs> SelectedItemChanged;
  732. /// <summary>
  733. /// Event to raise when an item is added, removed, or moved, or the entire list is refreshed.
  734. /// </summary>
  735. public event NotifyCollectionChangedEventHandler CollectionChanged;
  736. /// <summary>Sets the source of the <see cref="ListView"/> to an <see cref="IList"/>.</summary>
  737. /// <value>An object implementing the IList interface.</value>
  738. /// <remarks>
  739. /// Use the <see cref="Source"/> property to set a new <see cref="IListDataSource"/> source and use custom
  740. /// rendering.
  741. /// </remarks>
  742. public void SetSource<T> (ObservableCollection<T> source)
  743. {
  744. if (source is null && Source is not ListWrapper<T>)
  745. {
  746. Source = null;
  747. }
  748. else
  749. {
  750. Source = new ListWrapper<T> (source);
  751. }
  752. }
  753. /// <summary>Sets the source to an <see cref="IList"/> value asynchronously.</summary>
  754. /// <value>An item implementing the IList interface.</value>
  755. /// <remarks>
  756. /// Use the <see cref="Source"/> property to set a new <see cref="IListDataSource"/> source and use custom
  757. /// rendering.
  758. /// </remarks>
  759. public Task SetSourceAsync<T> (ObservableCollection<T> source)
  760. {
  761. return Task.Factory.StartNew (
  762. () =>
  763. {
  764. if (source is null && (Source is null || !(Source is ListWrapper<T>)))
  765. {
  766. Source = null;
  767. }
  768. else
  769. {
  770. Source = new ListWrapper<T> (source);
  771. }
  772. return source;
  773. },
  774. CancellationToken.None,
  775. TaskCreationOptions.DenyChildAttach,
  776. TaskScheduler.Default
  777. );
  778. }
  779. private void ListView_LayoutStarted (object sender, LayoutEventArgs e) { EnsureSelectedItemVisible (); }
  780. /// <summary>
  781. /// Call the event to raises the <see cref="CollectionChanged"/>.
  782. /// </summary>
  783. /// <param name="e"></param>
  784. protected virtual void OnCollectionChanged (NotifyCollectionChangedEventArgs e) { CollectionChanged?.Invoke (this, e); }
  785. /// <inheritdoc />
  786. protected override void Dispose (bool disposing)
  787. {
  788. _source?.Dispose ();
  789. base.Dispose (disposing);
  790. }
  791. /// <summary>
  792. /// Allow suspending the <see cref="CollectionChanged"/> event from being invoked,
  793. /// </summary>
  794. public void SuspendCollectionChangedEvent ()
  795. {
  796. if (Source is { })
  797. {
  798. Source.SuspendCollectionChangedEvent = true;
  799. }
  800. }
  801. /// <summary>
  802. /// Allow resume the <see cref="CollectionChanged"/> event from being invoked,
  803. /// </summary>
  804. public void ResumeSuspendCollectionChangedEvent ()
  805. {
  806. if (Source is { })
  807. {
  808. Source.SuspendCollectionChangedEvent = false;
  809. }
  810. }
  811. /// <inheritdoc />
  812. public bool EnableForDesign ()
  813. {
  814. var source = new ListWrapper<string> (["List Item 1", "List Item two", "List Item Quattro", "Last List Item"]);
  815. Source = source;
  816. return true;
  817. }
  818. }
  819. /// <summary>
  820. /// Provides a default implementation of <see cref="IListDataSource"/> that renders <see cref="ListView"/> items
  821. /// using <see cref="object.ToString()"/>.
  822. /// </summary>
  823. public class ListWrapper<T> : IListDataSource, IDisposable
  824. {
  825. private int _count;
  826. private BitArray _marks;
  827. private readonly ObservableCollection<T> _source;
  828. /// <inheritdoc/>
  829. public ListWrapper (ObservableCollection<T> source)
  830. {
  831. if (source is { })
  832. {
  833. _count = source.Count;
  834. _marks = new BitArray (_count);
  835. _source = source;
  836. _source.CollectionChanged += Source_CollectionChanged;
  837. Length = GetMaxLengthItem ();
  838. }
  839. }
  840. private void Source_CollectionChanged (object sender, NotifyCollectionChangedEventArgs e)
  841. {
  842. if (!SuspendCollectionChangedEvent)
  843. {
  844. CheckAndResizeMarksIfRequired ();
  845. CollectionChanged?.Invoke (sender, e);
  846. }
  847. }
  848. /// <inheritdoc />
  849. public event NotifyCollectionChangedEventHandler CollectionChanged;
  850. /// <inheritdoc/>
  851. public int Count => _source?.Count ?? 0;
  852. /// <inheritdoc/>
  853. public int Length { get; private set; }
  854. private bool _suspendCollectionChangedEvent;
  855. /// <inheritdoc />
  856. public bool SuspendCollectionChangedEvent
  857. {
  858. get => _suspendCollectionChangedEvent;
  859. set
  860. {
  861. _suspendCollectionChangedEvent = value;
  862. if (!_suspendCollectionChangedEvent)
  863. {
  864. CheckAndResizeMarksIfRequired ();
  865. }
  866. }
  867. }
  868. private void CheckAndResizeMarksIfRequired ()
  869. {
  870. if (_source != null && _count != _source.Count)
  871. {
  872. _count = _source.Count;
  873. BitArray newMarks = new BitArray (_count);
  874. for (var i = 0; i < Math.Min (_marks.Length, newMarks.Length); i++)
  875. {
  876. newMarks [i] = _marks [i];
  877. }
  878. _marks = newMarks;
  879. Length = GetMaxLengthItem ();
  880. }
  881. }
  882. /// <inheritdoc/>
  883. public void Render (
  884. ListView container,
  885. bool marked,
  886. int item,
  887. int col,
  888. int line,
  889. int width,
  890. int start = 0
  891. )
  892. {
  893. container.Move (Math.Max (col - start, 0), line);
  894. if (_source is { })
  895. {
  896. object t = _source [item];
  897. if (t is null)
  898. {
  899. RenderUstr (container, "", col, line, width);
  900. }
  901. else
  902. {
  903. if (t is string s)
  904. {
  905. RenderUstr (container, s, col, line, width, start);
  906. }
  907. else
  908. {
  909. RenderUstr (container, t.ToString (), col, line, width, start);
  910. }
  911. }
  912. }
  913. }
  914. /// <inheritdoc/>
  915. public bool IsMarked (int item)
  916. {
  917. if (item >= 0 && item < _count)
  918. {
  919. return _marks [item];
  920. }
  921. return false;
  922. }
  923. /// <inheritdoc/>
  924. public void SetMark (int item, bool value)
  925. {
  926. if (item >= 0 && item < _count)
  927. {
  928. _marks [item] = value;
  929. }
  930. }
  931. /// <inheritdoc/>
  932. public IList ToList () { return _source; }
  933. /// <inheritdoc/>
  934. public int StartsWith (string search)
  935. {
  936. if (_source is null || _source?.Count == 0)
  937. {
  938. return -1;
  939. }
  940. for (var i = 0; i < _source.Count; i++)
  941. {
  942. object t = _source [i];
  943. if (t is string u)
  944. {
  945. if (u.ToUpper ().StartsWith (search.ToUpperInvariant ()))
  946. {
  947. return i;
  948. }
  949. }
  950. else if (t is string s)
  951. {
  952. if (s.StartsWith (search, StringComparison.InvariantCultureIgnoreCase))
  953. {
  954. return i;
  955. }
  956. }
  957. }
  958. return -1;
  959. }
  960. private int GetMaxLengthItem ()
  961. {
  962. if (_source is null || _source?.Count == 0)
  963. {
  964. return 0;
  965. }
  966. var maxLength = 0;
  967. for (var i = 0; i < _source!.Count; i++)
  968. {
  969. object t = _source [i];
  970. int l;
  971. if (t is string u)
  972. {
  973. l = u.GetColumns ();
  974. }
  975. else if (t is string s)
  976. {
  977. l = s.Length;
  978. }
  979. else
  980. {
  981. l = t.ToString ().Length;
  982. }
  983. if (l > maxLength)
  984. {
  985. maxLength = l;
  986. }
  987. }
  988. return maxLength;
  989. }
  990. private void RenderUstr (View driver, string ustr, int col, int line, int width, int start = 0)
  991. {
  992. string str = start > ustr.GetColumns () ? string.Empty : ustr.Substring (Math.Min (start, ustr.ToRunes ().Length - 1));
  993. string u = TextFormatter.ClipAndJustify (str, width, Alignment.Start);
  994. driver.AddStr (u);
  995. width -= u.GetColumns ();
  996. while (width-- > 0)
  997. {
  998. driver.AddRune ((Rune)' ');
  999. }
  1000. }
  1001. /// <inheritdoc />
  1002. public void Dispose ()
  1003. {
  1004. if (_source is { })
  1005. {
  1006. _source.CollectionChanged -= Source_CollectionChanged;
  1007. }
  1008. }
  1009. }