ListView.cs 37 KB

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