ListView.cs 29 KB

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