ListView.cs 37 KB

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