ListView.cs 37 KB

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