ListView.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932
  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. KeyBindings.Add (KeyCode.Space, Command.ToggleChecked);
  159. } else {
  160. KeyBindings.Remove (KeyCode.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. KeyBindings.Add (KeyCode.CursorUp, Command.LineUp);
  306. KeyBindings.Add (KeyCode.P | KeyCode.CtrlMask, Command.LineUp);
  307. KeyBindings.Add (KeyCode.CursorDown, Command.LineDown);
  308. KeyBindings.Add (KeyCode.N | KeyCode.CtrlMask, Command.LineDown);
  309. KeyBindings.Add (KeyCode.PageUp, Command.PageUp);
  310. KeyBindings.Add (KeyCode.PageDown, Command.PageDown);
  311. KeyBindings.Add (KeyCode.V | KeyCode.CtrlMask, Command.PageDown);
  312. KeyBindings.Add (KeyCode.Home, Command.TopHome);
  313. KeyBindings.Add (KeyCode.End, Command.BottomEnd);
  314. KeyBindings.Add (KeyCode.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 OnProcessKeyDown (Key a)
  375. {
  376. // Enable user to find & select an item by typing text
  377. if (CollectionNavigator.IsCompatibleKey (a)) {
  378. var newItem = KeystrokeNavigator?.GetNextMatchingItem (SelectedItem, (char)a);
  379. if (newItem is int && newItem != -1) {
  380. SelectedItem = (int)newItem;
  381. EnsureSelectedItemVisible ();
  382. SetNeedsDisplay ();
  383. return true;
  384. }
  385. }
  386. return false;
  387. }
  388. /// <summary>
  389. /// If <see cref="AllowsMarking"/> and <see cref="AllowsMultipleSelection"/> are both <see langword="true"/>,
  390. /// unmarks all marked items other than the currently selected.
  391. /// </summary>
  392. /// <returns><see langword="true"/> if unmarking was successful.</returns>
  393. public virtual bool AllowsAll ()
  394. {
  395. if (!allowsMarking)
  396. return false;
  397. if (!AllowsMultipleSelection) {
  398. for (int i = 0; i < Source.Count; i++) {
  399. if (Source.IsMarked (i) && i != selected) {
  400. Source.SetMark (i, false);
  401. return true;
  402. }
  403. }
  404. }
  405. return true;
  406. }
  407. /// <summary>
  408. /// Marks the <see cref="SelectedItem"/> if it is not already marked.
  409. /// </summary>
  410. /// <returns><see langword="true"/> if the <see cref="SelectedItem"/> was marked.</returns>
  411. public virtual bool MarkUnmarkRow ()
  412. {
  413. if (AllowsAll ()) {
  414. Source.SetMark (SelectedItem, !Source.IsMarked (SelectedItem));
  415. SetNeedsDisplay ();
  416. return true;
  417. }
  418. return false;
  419. }
  420. /// <summary>
  421. /// Changes the <see cref="SelectedItem"/> to the item at the top of the visible list.
  422. /// </summary>
  423. /// <returns></returns>
  424. public virtual bool MovePageUp ()
  425. {
  426. int n = (selected - Bounds.Height);
  427. if (n < 0)
  428. n = 0;
  429. if (n != selected) {
  430. selected = n;
  431. top = Math.Max (selected, 0);
  432. OnSelectedChanged ();
  433. SetNeedsDisplay ();
  434. }
  435. return true;
  436. }
  437. /// <summary>
  438. /// Changes the <see cref="SelectedItem"/> to the item just below the bottom
  439. /// of the visible list, scrolling if needed.
  440. /// </summary>
  441. /// <returns></returns>
  442. public virtual bool MovePageDown ()
  443. {
  444. var n = (selected + Bounds.Height);
  445. if (n >= source.Count)
  446. n = source.Count - 1;
  447. if (n != selected) {
  448. selected = n;
  449. if (source.Count >= Bounds.Height)
  450. top = Math.Max (selected, 0);
  451. else
  452. top = 0;
  453. OnSelectedChanged ();
  454. SetNeedsDisplay ();
  455. }
  456. return true;
  457. }
  458. /// <summary>
  459. /// Changes the <see cref="SelectedItem"/> to the next item in the list,
  460. /// scrolling the list if needed.
  461. /// </summary>
  462. /// <returns></returns>
  463. public virtual bool MoveDown ()
  464. {
  465. if (source.Count == 0) {
  466. // Do we set lastSelectedItem to -1 here?
  467. return false; //Nothing for us to move to
  468. }
  469. if (selected >= source.Count) {
  470. // If for some reason we are currently outside of the
  471. // valid values range, we should select the bottommost valid value.
  472. // This can occur if the backing data source changes.
  473. selected = source.Count - 1;
  474. OnSelectedChanged ();
  475. SetNeedsDisplay ();
  476. } else if (selected + 1 < source.Count) { //can move by down by one.
  477. selected++;
  478. if (selected >= top + Bounds.Height) {
  479. top++;
  480. } else if (selected < top) {
  481. top = Math.Max (selected, 0);
  482. }
  483. OnSelectedChanged ();
  484. SetNeedsDisplay ();
  485. } else if (selected == 0) {
  486. OnSelectedChanged ();
  487. SetNeedsDisplay ();
  488. } else if (selected >= top + Bounds.Height) {
  489. top = Math.Max (source.Count - Bounds.Height, 0);
  490. SetNeedsDisplay ();
  491. }
  492. return true;
  493. }
  494. /// <summary>
  495. /// Changes the <see cref="SelectedItem"/> to the previous item in the list,
  496. /// scrolling the list if needed.
  497. /// </summary>
  498. /// <returns></returns>
  499. public virtual bool MoveUp ()
  500. {
  501. if (source.Count == 0) {
  502. // Do we set lastSelectedItem to -1 here?
  503. return false; //Nothing for us to move to
  504. }
  505. if (selected >= source.Count) {
  506. // If for some reason we are currently outside of the
  507. // valid values range, we should select the bottommost valid value.
  508. // This can occur if the backing data source changes.
  509. selected = source.Count - 1;
  510. OnSelectedChanged ();
  511. SetNeedsDisplay ();
  512. } else if (selected > 0) {
  513. selected--;
  514. if (selected > Source.Count) {
  515. selected = Source.Count - 1;
  516. }
  517. if (selected < top) {
  518. top = Math.Max (selected, 0);
  519. } else if (selected > top + Bounds.Height) {
  520. top = Math.Max (selected - Bounds.Height + 1, 0);
  521. }
  522. OnSelectedChanged ();
  523. SetNeedsDisplay ();
  524. } else if (selected < top) {
  525. top = Math.Max (selected, 0);
  526. SetNeedsDisplay ();
  527. }
  528. return true;
  529. }
  530. /// <summary>
  531. /// Changes the <see cref="SelectedItem"/> to last item in the list,
  532. /// scrolling the list if needed.
  533. /// </summary>
  534. /// <returns></returns>
  535. public virtual bool MoveEnd ()
  536. {
  537. if (source.Count > 0 && selected != source.Count - 1) {
  538. selected = source.Count - 1;
  539. if (top + selected > Bounds.Height - 1) {
  540. top = Math.Max (selected, 0);
  541. }
  542. OnSelectedChanged ();
  543. SetNeedsDisplay ();
  544. }
  545. return true;
  546. }
  547. /// <summary>
  548. /// Changes the <see cref="SelectedItem"/> to the first item in the list,
  549. /// scrolling the list if needed.
  550. /// </summary>
  551. /// <returns></returns>
  552. public virtual bool MoveHome ()
  553. {
  554. if (selected != 0) {
  555. selected = 0;
  556. top = Math.Max (selected, 0);
  557. OnSelectedChanged ();
  558. SetNeedsDisplay ();
  559. }
  560. return true;
  561. }
  562. /// <summary>
  563. /// Scrolls the view down by <paramref name="items"/> items.
  564. /// </summary>
  565. /// <param name="items">Number of items to scroll down.</param>
  566. public virtual bool ScrollDown (int items)
  567. {
  568. top = Math.Max (Math.Min (top + items, source.Count - 1), 0);
  569. SetNeedsDisplay ();
  570. return true;
  571. }
  572. /// <summary>
  573. /// Scrolls the view up by <paramref name="items"/> items.
  574. /// </summary>
  575. /// <param name="items">Number of items to scroll up.</param>
  576. public virtual bool ScrollUp (int items)
  577. {
  578. top = Math.Max (top - items, 0);
  579. SetNeedsDisplay ();
  580. return true;
  581. }
  582. /// <summary>
  583. /// Scrolls the view right.
  584. /// </summary>
  585. /// <param name="cols">Number of columns to scroll right.</param>
  586. public virtual bool ScrollRight (int cols)
  587. {
  588. left = Math.Max (Math.Min (left + cols, Maxlength - 1), 0);
  589. SetNeedsDisplay ();
  590. return true;
  591. }
  592. /// <summary>
  593. /// Scrolls the view left.
  594. /// </summary>
  595. /// <param name="cols">Number of columns to scroll left.</param>
  596. public virtual bool ScrollLeft (int cols)
  597. {
  598. left = Math.Max (left - cols, 0);
  599. SetNeedsDisplay ();
  600. return true;
  601. }
  602. int lastSelectedItem = -1;
  603. private bool allowsMultipleSelection = true;
  604. /// <summary>
  605. /// Invokes the <see cref="SelectedItemChanged"/> event if it is defined.
  606. /// </summary>
  607. /// <returns></returns>
  608. public virtual bool OnSelectedChanged ()
  609. {
  610. if (selected != lastSelectedItem) {
  611. var value = source?.Count > 0 ? source.ToList () [selected] : null;
  612. SelectedItemChanged?.Invoke (this, new ListViewItemEventArgs (selected, value));
  613. lastSelectedItem = selected;
  614. EnsureSelectedItemVisible ();
  615. return true;
  616. }
  617. return false;
  618. }
  619. /// <summary>
  620. /// Invokes the <see cref="OpenSelectedItem"/> event if it is defined.
  621. /// </summary>
  622. /// <returns></returns>
  623. public virtual bool OnOpenSelectedItem ()
  624. {
  625. if (source.Count <= selected || selected < 0 || OpenSelectedItem == null) {
  626. return false;
  627. }
  628. var value = source.ToList () [selected];
  629. OpenSelectedItem?.Invoke (this, new ListViewItemEventArgs (selected, value));
  630. return true;
  631. }
  632. /// <summary>
  633. /// Virtual method that will invoke the <see cref="RowRender"/>.
  634. /// </summary>
  635. /// <param name="rowEventArgs"></param>
  636. public virtual void OnRowRender (ListViewRowEventArgs rowEventArgs)
  637. {
  638. RowRender?.Invoke (this, rowEventArgs);
  639. }
  640. ///<inheritdoc/>
  641. public override bool OnEnter (View view)
  642. {
  643. if (IsInitialized) {
  644. Application.Driver.SetCursorVisibility (CursorVisibility.Invisible);
  645. }
  646. if (lastSelectedItem != selected) {
  647. EnsureSelectedItemVisible ();
  648. }
  649. return base.OnEnter (view);
  650. }
  651. /// <summary>
  652. /// Ensures the selected item is always visible on the screen.
  653. /// </summary>
  654. public void EnsureSelectedItemVisible ()
  655. {
  656. if (SuperView?.IsInitialized == true) {
  657. if (selected < top) {
  658. top = Math.Max (selected, 0);
  659. } else if (Bounds.Height > 0 && selected >= top + Bounds.Height) {
  660. top = Math.Max (selected - Bounds.Height + 1, 0);
  661. }
  662. LayoutStarted -= ListView_LayoutStarted;
  663. } else {
  664. LayoutStarted += ListView_LayoutStarted;
  665. }
  666. }
  667. private void ListView_LayoutStarted (object sender, LayoutEventArgs e)
  668. {
  669. EnsureSelectedItemVisible ();
  670. }
  671. ///<inheritdoc/>
  672. public override void PositionCursor ()
  673. {
  674. if (allowsMarking)
  675. Move (0, selected - top);
  676. else
  677. Move (Bounds.Width - 1, selected - top);
  678. }
  679. ///<inheritdoc/>
  680. public override bool MouseEvent (MouseEvent me)
  681. {
  682. if (!me.Flags.HasFlag (MouseFlags.Button1Clicked) && !me.Flags.HasFlag (MouseFlags.Button1DoubleClicked) &&
  683. me.Flags != MouseFlags.WheeledDown && me.Flags != MouseFlags.WheeledUp &&
  684. me.Flags != MouseFlags.WheeledRight && me.Flags != MouseFlags.WheeledLeft)
  685. return false;
  686. if (!HasFocus && CanFocus) {
  687. SetFocus ();
  688. }
  689. if (source == null) {
  690. return false;
  691. }
  692. if (me.Flags == MouseFlags.WheeledDown) {
  693. ScrollDown (1);
  694. return true;
  695. } else if (me.Flags == MouseFlags.WheeledUp) {
  696. ScrollUp (1);
  697. return true;
  698. } else if (me.Flags == MouseFlags.WheeledRight) {
  699. ScrollRight (1);
  700. return true;
  701. } else if (me.Flags == MouseFlags.WheeledLeft) {
  702. ScrollLeft (1);
  703. return true;
  704. }
  705. if (me.Y + top >= source.Count
  706. || me.Y + top < 0
  707. || me.Y + top > top + Bounds.Height) {
  708. return true;
  709. }
  710. selected = top + me.Y;
  711. if (AllowsAll ()) {
  712. Source.SetMark (SelectedItem, !Source.IsMarked (SelectedItem));
  713. SetNeedsDisplay ();
  714. return true;
  715. }
  716. OnSelectedChanged ();
  717. SetNeedsDisplay ();
  718. if (me.Flags == MouseFlags.Button1DoubleClicked) {
  719. OnOpenSelectedItem ();
  720. }
  721. return true;
  722. }
  723. }
  724. /// <summary>
  725. /// Provides a default implementation of <see cref="IListDataSource"/> that renders
  726. /// <see cref="ListView"/> items using <see cref="object.ToString()"/>.
  727. /// </summary>
  728. public class ListWrapper : IListDataSource {
  729. IList src;
  730. BitArray marks;
  731. int count, len;
  732. /// <inheritdoc/>
  733. public ListWrapper (IList source)
  734. {
  735. if (source != null) {
  736. count = source.Count;
  737. marks = new BitArray (count);
  738. src = source;
  739. len = GetMaxLengthItem ();
  740. }
  741. }
  742. /// <inheritdoc/>
  743. public int Count => src != null ? src.Count : 0;
  744. /// <inheritdoc/>
  745. public int Length => len;
  746. int GetMaxLengthItem ()
  747. {
  748. if (src == null || src?.Count == 0) {
  749. return 0;
  750. }
  751. int maxLength = 0;
  752. for (int i = 0; i < src.Count; i++) {
  753. var t = src [i];
  754. int l;
  755. if (t is string u) {
  756. l = u.GetColumns ();
  757. } else if (t is string s) {
  758. l = s.Length;
  759. } else {
  760. l = t.ToString ().Length;
  761. }
  762. if (l > maxLength) {
  763. maxLength = l;
  764. }
  765. }
  766. return maxLength;
  767. }
  768. void RenderUstr (ConsoleDriver driver, string ustr, int col, int line, int width, int start = 0)
  769. {
  770. var u = TextFormatter.ClipAndJustify (ustr, width, TextAlignment.Left);
  771. driver.AddStr (u);
  772. width -= u.GetColumns ();
  773. while (width-- > 0) {
  774. driver.AddRune ((Rune)' ');
  775. }
  776. }
  777. /// <inheritdoc/>
  778. public void Render (ListView container, ConsoleDriver driver, bool marked, int item, int col, int line, int width, int start = 0)
  779. {
  780. container.Move (col, line);
  781. var t = src? [item];
  782. if (t == null) {
  783. RenderUstr (driver, "", col, line, width);
  784. } else {
  785. if (t is string u) {
  786. RenderUstr (driver, u, col, line, width, start);
  787. } else if (t is string s) {
  788. RenderUstr (driver, s, col, line, width, start);
  789. } else {
  790. RenderUstr (driver, t.ToString (), col, line, width, start);
  791. }
  792. }
  793. }
  794. /// <inheritdoc/>
  795. public bool IsMarked (int item)
  796. {
  797. if (item >= 0 && item < count)
  798. return marks [item];
  799. return false;
  800. }
  801. /// <inheritdoc/>
  802. public void SetMark (int item, bool value)
  803. {
  804. if (item >= 0 && item < count)
  805. marks [item] = value;
  806. }
  807. /// <inheritdoc/>
  808. public IList ToList ()
  809. {
  810. return src;
  811. }
  812. /// <inheritdoc/>
  813. public int StartsWith (string search)
  814. {
  815. if (src == null || src?.Count == 0) {
  816. return -1;
  817. }
  818. for (int i = 0; i < src.Count; i++) {
  819. var t = src [i];
  820. if (t is string u) {
  821. if (u.ToUpper ().StartsWith (search.ToUpperInvariant ())) {
  822. return i;
  823. }
  824. } else if (t is string s) {
  825. if (s.StartsWith (search, StringComparison.InvariantCultureIgnoreCase)) {
  826. return i;
  827. }
  828. }
  829. }
  830. return -1;
  831. }
  832. }
  833. }