ListView.cs 32 KB

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