ListView.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using System.Text;
  8. namespace Terminal.Gui {
  9. /// <summary>
  10. /// Implement <see cref="IListDataSource"/> to provide custom rendering for a <see cref="ListView"/>.
  11. /// </summary>
  12. public interface IListDataSource {
  13. /// <summary>
  14. /// Returns the number of elements to display
  15. /// </summary>
  16. int Count { get; }
  17. /// <summary>
  18. /// Returns the maximum length of elements to display
  19. /// </summary>
  20. int Length { get; }
  21. /// <summary>
  22. /// This method is invoked to render a specified item, the method should cover the entire provided width.
  23. /// </summary>
  24. /// <returns>The render.</returns>
  25. /// <param name="container">The list view to render.</param>
  26. /// <param name="driver">The console driver to render.</param>
  27. /// <param name="selected">Describes whether the item being rendered is currently selected by the user.</param>
  28. /// <param name="item">The index of the item to render, zero for the first item and so on.</param>
  29. /// <param name="col">The column where the rendering will start</param>
  30. /// <param name="line">The line where the rendering will be done.</param>
  31. /// <param name="width">The width that must be filled out.</param>
  32. /// <param name="start">The index of the string to be displayed.</param>
  33. /// <remarks>
  34. /// The default color will be set before this method is invoked, and will be based on whether the item is selected or not.
  35. /// </remarks>
  36. void Render (ListView container, ConsoleDriver driver, bool selected, int item, int col, int line, int width, int start = 0);
  37. /// <summary>
  38. /// Should return whether the specified item is currently marked.
  39. /// </summary>
  40. /// <returns><see langword="true"/>, if marked, <see langword="false"/> otherwise.</returns>
  41. /// <param name="item">Item index.</param>
  42. bool IsMarked (int item);
  43. /// <summary>
  44. /// Flags the item as marked.
  45. /// </summary>
  46. /// <param name="item">Item index.</param>
  47. /// <param name="value">If set to <see langword="true"/> value.</param>
  48. void SetMark (int item, bool value);
  49. /// <summary>
  50. /// Return the source as IList.
  51. /// </summary>
  52. /// <returns></returns>
  53. IList ToList ();
  54. }
  55. /// <summary>
  56. /// ListView <see cref="View"/> renders a scrollable list of data where each item can be activated to perform an action.
  57. /// </summary>
  58. /// <remarks>
  59. /// <para>
  60. /// The <see cref="ListView"/> displays lists of data and allows the user to scroll through the data.
  61. /// Items in the can be activated firing an event (with the ENTER key or a mouse double-click).
  62. /// If the <see cref="AllowsMarking"/> property is true, elements of the list can be marked by the user.
  63. /// </para>
  64. /// <para>
  65. /// By default <see cref="ListView"/> uses <see cref="object.ToString"/> to render the items of any
  66. /// <see cref="IList"/> object (e.g. arrays, <see cref="List{T}"/>,
  67. /// and other collections). Alternatively, an object that implements <see cref="IListDataSource"/>
  68. /// can be provided giving full control of what is rendered.
  69. /// </para>
  70. /// <para>
  71. /// <see cref="ListView"/> can display any object that implements the <see cref="IList"/> interface.
  72. /// <see cref="string"/> values are converted into <see cref="string"/> values before rendering, and other values are
  73. /// converted into <see cref="string"/> by calling <see cref="object.ToString"/> and then converting to <see cref="string"/> .
  74. /// </para>
  75. /// <para>
  76. /// To change the contents of the ListView, set the <see cref="Source"/> property (when
  77. /// providing custom rendering via <see cref="IListDataSource"/>) or call <see cref="SetSource"/>
  78. /// an <see cref="IList"/> is being used.
  79. /// </para>
  80. /// <para>
  81. /// When <see cref="AllowsMarking"/> is set to true the rendering will prefix the rendered items with
  82. /// [x] or [ ] and bind the SPACE key to toggle the selection. To implement a different
  83. /// marking style set <see cref="AllowsMarking"/> to false and implement custom rendering.
  84. /// </para>
  85. /// <para>
  86. /// Searching the ListView with the keyboard is supported. Users type the
  87. /// first characters of an item, and the first item that starts with what the user types will be selected.
  88. /// </para>
  89. /// </remarks>
  90. public class ListView : View {
  91. int top, left;
  92. int selected = -1;
  93. IListDataSource source;
  94. /// <summary>
  95. /// Gets or sets the <see cref="IListDataSource"/> backing this <see cref="ListView"/>, enabling custom rendering.
  96. /// </summary>
  97. /// <value>The source.</value>
  98. /// <remarks>
  99. /// Use <see cref="SetSource"/> to set a new <see cref="IList"/> source.
  100. /// </remarks>
  101. public IListDataSource Source {
  102. get => source;
  103. set {
  104. source = value;
  105. KeystrokeNavigator.Collection = source?.ToList ();
  106. top = 0;
  107. selected = -1;
  108. lastSelectedItem = -1;
  109. SetNeedsDisplay ();
  110. }
  111. }
  112. /// <summary>
  113. /// Sets the source of the <see cref="ListView"/> to an <see cref="IList"/>.
  114. /// </summary>
  115. /// <value>An object implementing the IList interface.</value>
  116. /// <remarks>
  117. /// Use the <see cref="Source"/> property to set a new <see cref="IListDataSource"/> source and use custome rendering.
  118. /// </remarks>
  119. public void SetSource (IList source)
  120. {
  121. if (source == null && (Source == null || !(Source is ListWrapper)))
  122. Source = null;
  123. else {
  124. Source = MakeWrapper (source);
  125. }
  126. }
  127. /// <summary>
  128. /// Sets the source to an <see cref="IList"/> value asynchronously.
  129. /// </summary>
  130. /// <value>An item implementing the IList interface.</value>
  131. /// <remarks>
  132. /// Use the <see cref="Source"/> property to set a new <see cref="IListDataSource"/> source and use custom rendering.
  133. /// </remarks>
  134. public Task SetSourceAsync (IList source)
  135. {
  136. return Task.Factory.StartNew (() => {
  137. if (source == null && (Source == null || !(Source is ListWrapper)))
  138. Source = null;
  139. else
  140. Source = MakeWrapper (source);
  141. return source;
  142. }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  143. }
  144. bool allowsMarking;
  145. /// <summary>
  146. /// Gets or sets whether this <see cref="ListView"/> allows items to be marked.
  147. /// </summary>
  148. /// <value>Set to <see langword="true"/> to allow marking elements of the list.</value>
  149. /// <remarks>
  150. /// If set to <see langword="true"/>, <see cref="ListView"/> will render items marked items with "[x]", and unmarked items with "[ ]"
  151. /// spaces. SPACE key will toggle marking. The default is <see langword="false"/>.
  152. /// </remarks>
  153. public bool AllowsMarking {
  154. get => allowsMarking;
  155. set {
  156. allowsMarking = value;
  157. if (allowsMarking) {
  158. AddKeyBinding (Key.Space, Command.ToggleChecked);
  159. } else {
  160. ClearKeyBinding (Key.Space);
  161. }
  162. SetNeedsDisplay ();
  163. }
  164. }
  165. /// <summary>
  166. /// If set to <see langword="true"/> more than one item can be selected. If <see langword="false"/> selecting
  167. /// an item will cause all others to be un-selected. The default is <see langword="false"/>.
  168. /// </summary>
  169. public bool AllowsMultipleSelection {
  170. get => allowsMultipleSelection;
  171. set {
  172. allowsMultipleSelection = value;
  173. if (Source != null && !allowsMultipleSelection) {
  174. // Clear all selections except selected
  175. for (int i = 0; i < Source.Count; i++) {
  176. if (Source.IsMarked (i) && i != selected) {
  177. Source.SetMark (i, false);
  178. }
  179. }
  180. }
  181. SetNeedsDisplay ();
  182. }
  183. }
  184. /// <summary>
  185. /// Gets or sets the item that is displayed at the top of the <see cref="ListView"/>.
  186. /// </summary>
  187. /// <value>The top item.</value>
  188. public int TopItem {
  189. get => top;
  190. set {
  191. if (source == null)
  192. return;
  193. if (value < 0 || (source.Count > 0 && value >= source.Count))
  194. throw new ArgumentException ("value");
  195. top = Math.Max (value, 0);
  196. SetNeedsDisplay ();
  197. }
  198. }
  199. /// <summary>
  200. /// Gets or sets the leftmost column that is currently visible (when scrolling horizontally).
  201. /// </summary>
  202. /// <value>The left position.</value>
  203. public int LeftItem {
  204. get => left;
  205. set {
  206. if (source == null)
  207. return;
  208. if (value < 0 || (Maxlength > 0 && value >= Maxlength))
  209. throw new ArgumentException ("value");
  210. left = value;
  211. SetNeedsDisplay ();
  212. }
  213. }
  214. /// <summary>
  215. /// Gets the widest item in the list.
  216. /// </summary>
  217. public int Maxlength => (source?.Length) ?? 0;
  218. /// <summary>
  219. /// Gets or sets the index of the currently selected item.
  220. /// </summary>
  221. /// <value>The selected item.</value>
  222. public int SelectedItem {
  223. get => selected;
  224. set {
  225. if (source == null || source.Count == 0) {
  226. return;
  227. }
  228. if (value < -1 || value >= source.Count) {
  229. throw new ArgumentException ("value");
  230. }
  231. selected = value;
  232. OnSelectedChanged ();
  233. }
  234. }
  235. static IListDataSource MakeWrapper (IList source)
  236. {
  237. return new ListWrapper (source);
  238. }
  239. /// <summary>
  240. /// Initializes a new instance of <see cref="ListView"/> that will display the
  241. /// contents of the object implementing the <see cref="IList"/> interface,
  242. /// with relative positioning.
  243. /// </summary>
  244. /// <param name="source">An <see cref="IList"/> data source, if the elements are strings or ustrings,
  245. /// the string is rendered, otherwise the ToString() method is invoked on the result.</param>
  246. public ListView (IList source) : this (MakeWrapper (source))
  247. {
  248. }
  249. /// <summary>
  250. /// Initializes a new instance of <see cref="ListView"/> that will display the provided data source, using relative positioning.
  251. /// </summary>
  252. /// <param name="source"><see cref="IListDataSource"/> object that provides a mechanism to render the data.
  253. /// The number of elements on the collection should not change, if you must change, set
  254. /// the "Source" property to reset the internal settings of the ListView.</param>
  255. public ListView (IListDataSource source) : base ()
  256. {
  257. this.source = source;
  258. Initialize ();
  259. }
  260. /// <summary>
  261. /// Initializes a new instance of <see cref="ListView"/>. Set the <see cref="Source"/> property to display something.
  262. /// </summary>
  263. public ListView () : base ()
  264. {
  265. Initialize ();
  266. }
  267. /// <summary>
  268. /// Initializes a new instance of <see cref="ListView"/> that will display the contents of the object implementing the <see cref="IList"/> interface with an absolute position.
  269. /// </summary>
  270. /// <param name="rect">Frame for the listview.</param>
  271. /// <param name="source">An IList data source, if the elements of the IList are strings or ustrings,
  272. /// the string is rendered, otherwise the ToString() method is invoked on the result.</param>
  273. public ListView (Rect rect, IList source) : this (rect, MakeWrapper (source))
  274. {
  275. Initialize ();
  276. }
  277. /// <summary>
  278. /// Initializes a new instance of <see cref="ListView"/> with the provided data source and an absolute position
  279. /// </summary>
  280. /// <param name="rect">Frame for the listview.</param>
  281. /// <param name="source">IListDataSource object that provides a mechanism to render the data.
  282. /// The number of elements on the collection should not change, if you must change,
  283. /// set the "Source" property to reset the internal settings of the ListView.</param>
  284. public ListView (Rect rect, IListDataSource source) : base (rect)
  285. {
  286. this.source = source;
  287. Initialize ();
  288. }
  289. void Initialize ()
  290. {
  291. Source = source;
  292. CanFocus = true;
  293. // Things this view knows how to do
  294. AddCommand (Command.LineUp, () => MoveUp ());
  295. AddCommand (Command.LineDown, () => MoveDown ());
  296. AddCommand (Command.ScrollUp, () => ScrollUp (1));
  297. AddCommand (Command.ScrollDown, () => ScrollDown (1));
  298. AddCommand (Command.PageUp, () => MovePageUp ());
  299. AddCommand (Command.PageDown, () => MovePageDown ());
  300. AddCommand (Command.TopHome, () => MoveHome ());
  301. AddCommand (Command.BottomEnd, () => MoveEnd ());
  302. AddCommand (Command.OpenSelectedItem, () => OnOpenSelectedItem ());
  303. AddCommand (Command.ToggleChecked, () => MarkUnmarkRow ());
  304. // Default keybindings for all ListViews
  305. AddKeyBinding (Key.CursorUp, Command.LineUp);
  306. AddKeyBinding (Key.P | Key.CtrlMask, Command.LineUp);
  307. AddKeyBinding (Key.CursorDown, Command.LineDown);
  308. AddKeyBinding (Key.N | Key.CtrlMask, Command.LineDown);
  309. AddKeyBinding (Key.PageUp, Command.PageUp);
  310. AddKeyBinding (Key.PageDown, Command.PageDown);
  311. AddKeyBinding (Key.V | Key.CtrlMask, Command.PageDown);
  312. AddKeyBinding (Key.Home, Command.TopHome);
  313. AddKeyBinding (Key.End, Command.BottomEnd);
  314. AddKeyBinding (Key.Enter, Command.OpenSelectedItem);
  315. }
  316. ///<inheritdoc/>
  317. public override void OnDrawContent (Rect contentArea)
  318. {
  319. base.OnDrawContent (contentArea);
  320. var current = ColorScheme.Focus;
  321. Driver.SetAttribute (current);
  322. Move (0, 0);
  323. var f = Bounds;
  324. var item = top;
  325. bool focused = HasFocus;
  326. int col = allowsMarking ? 2 : 0;
  327. int start = left;
  328. for (int row = 0; row < f.Height; row++, item++) {
  329. bool isSelected = item == selected;
  330. var newcolor = focused ? (isSelected ? ColorScheme.Focus : GetNormalColor ())
  331. : (isSelected ? ColorScheme.HotNormal : GetNormalColor ());
  332. if (newcolor != current) {
  333. Driver.SetAttribute (newcolor);
  334. current = newcolor;
  335. }
  336. Move (0, row);
  337. if (source == null || item >= source.Count) {
  338. for (int c = 0; c < f.Width; c++)
  339. Driver.AddRune ((Rune)' ');
  340. } else {
  341. var rowEventArgs = new ListViewRowEventArgs (item);
  342. OnRowRender (rowEventArgs);
  343. if (rowEventArgs.RowAttribute != null && current != rowEventArgs.RowAttribute) {
  344. current = (Attribute)rowEventArgs.RowAttribute;
  345. Driver.SetAttribute (current);
  346. }
  347. if (allowsMarking) {
  348. Driver.AddRune (source.IsMarked (item) ? (AllowsMultipleSelection ? CM.Glyphs.Checked : CM.Glyphs.Selected) :
  349. (AllowsMultipleSelection ? CM.Glyphs.UnChecked : CM.Glyphs.UnSelected));
  350. Driver.AddRune ((Rune)' ');
  351. }
  352. Source.Render (this, Driver, isSelected, item, col, row, f.Width - col, start);
  353. }
  354. }
  355. }
  356. /// <summary>
  357. /// This event is raised when the selected item in the <see cref="ListView"/> has changed.
  358. /// </summary>
  359. public event EventHandler<ListViewItemEventArgs> SelectedItemChanged;
  360. /// <summary>
  361. /// This event is raised when the user Double Clicks on an item or presses ENTER to open the selected item.
  362. /// </summary>
  363. public event EventHandler<ListViewItemEventArgs> OpenSelectedItem;
  364. /// <summary>
  365. /// This event is invoked when this <see cref="ListView"/> is being drawn before rendering.
  366. /// </summary>
  367. public event EventHandler<ListViewRowEventArgs> RowRender;
  368. /// <summary>
  369. /// Gets the <see cref="CollectionNavigator"/> that searches the <see cref="ListView.Source"/> collection as
  370. /// the user types.
  371. /// </summary>
  372. public CollectionNavigator KeystrokeNavigator { get; private set; } = new CollectionNavigator ();
  373. ///<inheritdoc/>
  374. public override bool ProcessKey (KeyEvent kb)
  375. {
  376. if (source == null) {
  377. return base.ProcessKey (kb);
  378. }
  379. var result = InvokeKeybindings (kb);
  380. if (result != null) {
  381. return (bool)result;
  382. }
  383. // Enable user to find & select an item by typing text
  384. if (CollectionNavigator.IsCompatibleKey (kb)) {
  385. var newItem = KeystrokeNavigator?.GetNextMatchingItem (SelectedItem, (char)kb.KeyValue);
  386. if (newItem is int && newItem != -1) {
  387. SelectedItem = (int)newItem;
  388. EnsureSelectedItemVisible ();
  389. SetNeedsDisplay ();
  390. return true;
  391. }
  392. }
  393. return false;
  394. }
  395. /// <summary>
  396. /// If <see cref="AllowsMarking"/> and <see cref="AllowsMultipleSelection"/> are both <see langword="true"/>,
  397. /// unmarks all marked items other than the currently selected.
  398. /// </summary>
  399. /// <returns><see langword="true"/> if unmarking was successful.</returns>
  400. public virtual bool AllowsAll ()
  401. {
  402. if (!allowsMarking)
  403. return false;
  404. if (!AllowsMultipleSelection) {
  405. for (int i = 0; i < Source.Count; i++) {
  406. if (Source.IsMarked (i) && i != selected) {
  407. Source.SetMark (i, false);
  408. return true;
  409. }
  410. }
  411. }
  412. return true;
  413. }
  414. /// <summary>
  415. /// Marks the <see cref="SelectedItem"/> if it is not already marked.
  416. /// </summary>
  417. /// <returns><see langword="true"/> if the <see cref="SelectedItem"/> was marked.</returns>
  418. public virtual bool MarkUnmarkRow ()
  419. {
  420. if (AllowsAll ()) {
  421. Source.SetMark (SelectedItem, !Source.IsMarked (SelectedItem));
  422. SetNeedsDisplay ();
  423. return true;
  424. }
  425. return false;
  426. }
  427. /// <summary>
  428. /// Changes the <see cref="SelectedItem"/> to the item at the top of the visible list.
  429. /// </summary>
  430. /// <returns></returns>
  431. public virtual bool MovePageUp ()
  432. {
  433. int n = (selected - Bounds.Height);
  434. if (n < 0)
  435. n = 0;
  436. if (n != selected) {
  437. selected = n;
  438. top = Math.Max (selected, 0);
  439. OnSelectedChanged ();
  440. SetNeedsDisplay ();
  441. }
  442. return true;
  443. }
  444. /// <summary>
  445. /// Changes the <see cref="SelectedItem"/> to the item just below the bottom
  446. /// of the visible list, scrolling if needed.
  447. /// </summary>
  448. /// <returns></returns>
  449. public virtual bool MovePageDown ()
  450. {
  451. var n = (selected + Bounds.Height);
  452. if (n >= source.Count)
  453. n = source.Count - 1;
  454. if (n != selected) {
  455. selected = n;
  456. if (source.Count >= Bounds.Height)
  457. top = Math.Max (selected, 0);
  458. else
  459. top = 0;
  460. OnSelectedChanged ();
  461. SetNeedsDisplay ();
  462. }
  463. return true;
  464. }
  465. /// <summary>
  466. /// Changes the <see cref="SelectedItem"/> to the next item in the list,
  467. /// scrolling the list if needed.
  468. /// </summary>
  469. /// <returns></returns>
  470. public virtual bool MoveDown ()
  471. {
  472. if (source.Count == 0) {
  473. // Do we set lastSelectedItem to -1 here?
  474. return false; //Nothing for us to move to
  475. }
  476. if (selected >= source.Count) {
  477. // If for some reason we are currently outside of the
  478. // valid values range, we should select the bottommost valid value.
  479. // This can occur if the backing data source changes.
  480. selected = source.Count - 1;
  481. OnSelectedChanged ();
  482. SetNeedsDisplay ();
  483. } else if (selected + 1 < source.Count) { //can move by down by one.
  484. selected++;
  485. if (selected >= top + Bounds.Height) {
  486. top++;
  487. } else if (selected < top) {
  488. top = Math.Max (selected, 0);
  489. }
  490. OnSelectedChanged ();
  491. SetNeedsDisplay ();
  492. } else if (selected == 0) {
  493. OnSelectedChanged ();
  494. SetNeedsDisplay ();
  495. } else if (selected >= top + Bounds.Height) {
  496. top = Math.Max (source.Count - Bounds.Height, 0);
  497. SetNeedsDisplay ();
  498. }
  499. return true;
  500. }
  501. /// <summary>
  502. /// Changes the <see cref="SelectedItem"/> to the previous item in the list,
  503. /// scrolling the list if needed.
  504. /// </summary>
  505. /// <returns></returns>
  506. public virtual bool MoveUp ()
  507. {
  508. if (source.Count == 0) {
  509. // Do we set lastSelectedItem to -1 here?
  510. return false; //Nothing for us to move to
  511. }
  512. if (selected >= source.Count) {
  513. // If for some reason we are currently outside of the
  514. // valid values range, we should select the bottommost valid value.
  515. // This can occur if the backing data source changes.
  516. selected = source.Count - 1;
  517. OnSelectedChanged ();
  518. SetNeedsDisplay ();
  519. } else if (selected > 0) {
  520. selected--;
  521. if (selected > Source.Count) {
  522. selected = Source.Count - 1;
  523. }
  524. if (selected < top) {
  525. top = Math.Max (selected, 0);
  526. } else if (selected > top + Bounds.Height) {
  527. top = Math.Max (selected - Bounds.Height + 1, 0);
  528. }
  529. OnSelectedChanged ();
  530. SetNeedsDisplay ();
  531. } else if (selected < top) {
  532. top = Math.Max (selected, 0);
  533. SetNeedsDisplay ();
  534. }
  535. return true;
  536. }
  537. /// <summary>
  538. /// Changes the <see cref="SelectedItem"/> to last item in the list,
  539. /// scrolling the list if needed.
  540. /// </summary>
  541. /// <returns></returns>
  542. public virtual bool MoveEnd ()
  543. {
  544. if (source.Count > 0 && selected != source.Count - 1) {
  545. selected = source.Count - 1;
  546. if (top + selected > Bounds.Height - 1) {
  547. top = Math.Max (selected, 0);
  548. }
  549. OnSelectedChanged ();
  550. SetNeedsDisplay ();
  551. }
  552. return true;
  553. }
  554. /// <summary>
  555. /// Changes the <see cref="SelectedItem"/> to the first item in the list,
  556. /// scrolling the list if needed.
  557. /// </summary>
  558. /// <returns></returns>
  559. public virtual bool MoveHome ()
  560. {
  561. if (selected != 0) {
  562. selected = 0;
  563. top = Math.Max (selected, 0);
  564. OnSelectedChanged ();
  565. SetNeedsDisplay ();
  566. }
  567. return true;
  568. }
  569. /// <summary>
  570. /// Scrolls the view down by <paramref name="items"/> items.
  571. /// </summary>
  572. /// <param name="items">Number of items to scroll down.</param>
  573. public virtual bool ScrollDown (int items)
  574. {
  575. top = Math.Max (Math.Min (top + items, source.Count - 1), 0);
  576. SetNeedsDisplay ();
  577. return true;
  578. }
  579. /// <summary>
  580. /// Scrolls the view up by <paramref name="items"/> items.
  581. /// </summary>
  582. /// <param name="items">Number of items to scroll up.</param>
  583. public virtual bool ScrollUp (int items)
  584. {
  585. top = Math.Max (top - items, 0);
  586. SetNeedsDisplay ();
  587. return true;
  588. }
  589. /// <summary>
  590. /// Scrolls the view right.
  591. /// </summary>
  592. /// <param name="cols">Number of columns to scroll right.</param>
  593. public virtual bool ScrollRight (int cols)
  594. {
  595. left = Math.Max (Math.Min (left + cols, Maxlength - 1), 0);
  596. SetNeedsDisplay ();
  597. return true;
  598. }
  599. /// <summary>
  600. /// Scrolls the view left.
  601. /// </summary>
  602. /// <param name="cols">Number of columns to scroll left.</param>
  603. public virtual bool ScrollLeft (int cols)
  604. {
  605. left = Math.Max (left - cols, 0);
  606. SetNeedsDisplay ();
  607. return true;
  608. }
  609. int lastSelectedItem = -1;
  610. private bool allowsMultipleSelection = true;
  611. /// <summary>
  612. /// Invokes the <see cref="SelectedItemChanged"/> event if it is defined.
  613. /// </summary>
  614. /// <returns></returns>
  615. public virtual bool OnSelectedChanged ()
  616. {
  617. if (selected != lastSelectedItem) {
  618. var value = source?.Count > 0 ? source.ToList () [selected] : null;
  619. SelectedItemChanged?.Invoke (this, new ListViewItemEventArgs (selected, value));
  620. lastSelectedItem = selected;
  621. EnsureSelectedItemVisible ();
  622. return true;
  623. }
  624. return false;
  625. }
  626. /// <summary>
  627. /// Invokes the <see cref="OpenSelectedItem"/> event if it is defined.
  628. /// </summary>
  629. /// <returns></returns>
  630. public virtual bool OnOpenSelectedItem ()
  631. {
  632. if (source.Count <= selected || selected < 0 || OpenSelectedItem == null) {
  633. return false;
  634. }
  635. var value = source.ToList () [selected];
  636. OpenSelectedItem?.Invoke (this, new ListViewItemEventArgs (selected, value));
  637. return true;
  638. }
  639. /// <summary>
  640. /// Virtual method that will invoke the <see cref="RowRender"/>.
  641. /// </summary>
  642. /// <param name="rowEventArgs"></param>
  643. public virtual void OnRowRender (ListViewRowEventArgs rowEventArgs)
  644. {
  645. RowRender?.Invoke (this, rowEventArgs);
  646. }
  647. ///<inheritdoc/>
  648. public override bool OnEnter (View view)
  649. {
  650. if (IsInitialized) {
  651. Application.Driver.SetCursorVisibility (CursorVisibility.Invisible);
  652. }
  653. if (lastSelectedItem != selected) {
  654. EnsureSelectedItemVisible ();
  655. }
  656. return base.OnEnter (view);
  657. }
  658. /// <summary>
  659. /// Ensures the selected item is always visible on the screen.
  660. /// </summary>
  661. public void EnsureSelectedItemVisible ()
  662. {
  663. if (SuperView?.IsInitialized == true) {
  664. if (selected < top) {
  665. top = Math.Max (selected, 0);
  666. } else if (Bounds.Height > 0 && selected >= top + Bounds.Height) {
  667. top = Math.Max (selected - Bounds.Height + 1, 0);
  668. }
  669. LayoutStarted -= ListView_LayoutStarted;
  670. } else {
  671. LayoutStarted += ListView_LayoutStarted;
  672. }
  673. }
  674. private void ListView_LayoutStarted (object sender, LayoutEventArgs e)
  675. {
  676. EnsureSelectedItemVisible ();
  677. }
  678. ///<inheritdoc/>
  679. public override void PositionCursor ()
  680. {
  681. if (allowsMarking)
  682. Move (0, selected - top);
  683. else
  684. Move (Bounds.Width - 1, selected - top);
  685. }
  686. ///<inheritdoc/>
  687. public override bool MouseEvent (MouseEvent me)
  688. {
  689. if (!me.Flags.HasFlag (MouseFlags.Button1Clicked) && !me.Flags.HasFlag (MouseFlags.Button1DoubleClicked) &&
  690. me.Flags != MouseFlags.WheeledDown && me.Flags != MouseFlags.WheeledUp &&
  691. me.Flags != MouseFlags.WheeledRight && me.Flags != MouseFlags.WheeledLeft)
  692. return false;
  693. if (!HasFocus && CanFocus) {
  694. SetFocus ();
  695. }
  696. if (source == null) {
  697. return false;
  698. }
  699. if (me.Flags == MouseFlags.WheeledDown) {
  700. ScrollDown (1);
  701. return true;
  702. } else if (me.Flags == MouseFlags.WheeledUp) {
  703. ScrollUp (1);
  704. return true;
  705. } else if (me.Flags == MouseFlags.WheeledRight) {
  706. ScrollRight (1);
  707. return true;
  708. } else if (me.Flags == MouseFlags.WheeledLeft) {
  709. ScrollLeft (1);
  710. return true;
  711. }
  712. if (me.Y + top >= source.Count
  713. || me.Y + top < 0
  714. || me.Y + top > top + Bounds.Height) {
  715. return true;
  716. }
  717. selected = top + me.Y;
  718. if (AllowsAll ()) {
  719. Source.SetMark (SelectedItem, !Source.IsMarked (SelectedItem));
  720. SetNeedsDisplay ();
  721. return true;
  722. }
  723. OnSelectedChanged ();
  724. SetNeedsDisplay ();
  725. if (me.Flags == MouseFlags.Button1DoubleClicked) {
  726. OnOpenSelectedItem ();
  727. }
  728. return true;
  729. }
  730. }
  731. /// <summary>
  732. /// Provides a default implementation of <see cref="IListDataSource"/> that renders
  733. /// <see cref="ListView"/> items using <see cref="object.ToString()"/>.
  734. /// </summary>
  735. public class ListWrapper : IListDataSource {
  736. IList src;
  737. BitArray marks;
  738. int count, len;
  739. /// <inheritdoc/>
  740. public ListWrapper (IList source)
  741. {
  742. if (source != null) {
  743. count = source.Count;
  744. marks = new BitArray (count);
  745. src = source;
  746. len = GetMaxLengthItem ();
  747. }
  748. }
  749. /// <inheritdoc/>
  750. public int Count => src != null ? src.Count : 0;
  751. /// <inheritdoc/>
  752. public int Length => len;
  753. int GetMaxLengthItem ()
  754. {
  755. if (src == null || src?.Count == 0) {
  756. return 0;
  757. }
  758. int maxLength = 0;
  759. for (int i = 0; i < src.Count; i++) {
  760. var t = src [i];
  761. int l;
  762. if (t is string u) {
  763. l = u.GetColumns ();
  764. } else if (t is string s) {
  765. l = s.Length;
  766. } else {
  767. l = t.ToString ().Length;
  768. }
  769. if (l > maxLength) {
  770. maxLength = l;
  771. }
  772. }
  773. return maxLength;
  774. }
  775. void RenderUstr (ConsoleDriver driver, string ustr, int col, int line, int width, int start = 0)
  776. {
  777. var u = TextFormatter.ClipAndJustify (ustr, width, TextAlignment.Left);
  778. driver.AddStr (u);
  779. width -= u.GetColumns ();
  780. while (width-- > 0) {
  781. driver.AddRune ((Rune)' ');
  782. }
  783. }
  784. /// <inheritdoc/>
  785. public void Render (ListView container, ConsoleDriver driver, bool marked, int item, int col, int line, int width, int start = 0)
  786. {
  787. container.Move (col, line);
  788. var t = src? [item];
  789. if (t == null) {
  790. RenderUstr (driver, "", col, line, width);
  791. } else {
  792. if (t is string u) {
  793. RenderUstr (driver, u, col, line, width, start);
  794. } else if (t is string s) {
  795. RenderUstr (driver, s, col, line, width, start);
  796. } else {
  797. RenderUstr (driver, t.ToString (), col, line, width, start);
  798. }
  799. }
  800. }
  801. /// <inheritdoc/>
  802. public bool IsMarked (int item)
  803. {
  804. if (item >= 0 && item < count)
  805. return marks [item];
  806. return false;
  807. }
  808. /// <inheritdoc/>
  809. public void SetMark (int item, bool value)
  810. {
  811. if (item >= 0 && item < count)
  812. marks [item] = value;
  813. }
  814. /// <inheritdoc/>
  815. public IList ToList ()
  816. {
  817. return src;
  818. }
  819. /// <inheritdoc/>
  820. public int StartsWith (string search)
  821. {
  822. if (src == null || src?.Count == 0) {
  823. return -1;
  824. }
  825. for (int i = 0; i < src.Count; i++) {
  826. var t = src [i];
  827. if (t is string u) {
  828. if (u.ToUpper ().StartsWith (search.ToUpperInvariant ())) {
  829. return i;
  830. }
  831. } else if (t is string s) {
  832. if (s.StartsWith (search, StringComparison.InvariantCultureIgnoreCase)) {
  833. return i;
  834. }
  835. }
  836. }
  837. return -1;
  838. }
  839. }
  840. }