ViewSubViews.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867
  1. namespace Terminal.Gui;
  2. public partial class View
  3. {
  4. private static readonly IList<View> _empty = new List<View> (0).AsReadOnly ();
  5. internal bool _addingView;
  6. private List<View> _subviews; // This is null, and allocated on demand.
  7. private View _superView;
  8. /// <summary>Indicates whether the view was added to <see cref="SuperView"/>.</summary>
  9. public bool IsAdded { get; private set; }
  10. /// <summary>Returns a value indicating if this View is currently on Top (Active)</summary>
  11. public bool IsCurrentTop => Application.Current == this;
  12. /// <summary>This returns a list of the subviews contained by this view.</summary>
  13. /// <value>The subviews.</value>
  14. public IList<View> Subviews => _subviews?.AsReadOnly () ?? _empty;
  15. /// <summary>Returns the container for this view, or null if this view has not been added to a container.</summary>
  16. /// <value>The super view.</value>
  17. public virtual View SuperView
  18. {
  19. get => _superView;
  20. set => throw new NotImplementedException ();
  21. }
  22. // Internally, we use InternalSubviews rather than subviews, as we do not expect us
  23. // to make the same mistakes our users make when they poke at the Subviews.
  24. internal IList<View> InternalSubviews => _subviews ?? _empty;
  25. /// <summary>Adds a subview (child) to this view.</summary>
  26. /// <remarks>
  27. /// The Views that have been added to this view can be retrieved via the <see cref="Subviews"/> property. See also
  28. /// <seealso cref="Remove(View)"/> <seealso cref="RemoveAll"/>
  29. /// </remarks>
  30. public virtual void Add (View view)
  31. {
  32. if (view is null)
  33. {
  34. return;
  35. }
  36. if (_subviews is null)
  37. {
  38. _subviews = new List<View> ();
  39. }
  40. if (_tabIndexes is null)
  41. {
  42. _tabIndexes = new List<View> ();
  43. }
  44. _subviews.Add (view);
  45. _tabIndexes.Add (view);
  46. view._superView = this;
  47. if (view.CanFocus)
  48. {
  49. _addingView = true;
  50. if (SuperView?.CanFocus == false)
  51. {
  52. SuperView._addingView = true;
  53. SuperView.CanFocus = true;
  54. SuperView._addingView = false;
  55. }
  56. CanFocus = true;
  57. view._tabIndex = _tabIndexes.IndexOf (view);
  58. _addingView = false;
  59. }
  60. if (view.Enabled && !Enabled)
  61. {
  62. view._oldEnabled = true;
  63. view.Enabled = false;
  64. }
  65. OnAdded (new SuperViewChangedEventArgs (this, view));
  66. if (IsInitialized && !view.IsInitialized)
  67. {
  68. view.BeginInit ();
  69. view.EndInit ();
  70. }
  71. SetNeedsLayout ();
  72. SetNeedsDisplay ();
  73. }
  74. /// <summary>Adds the specified views (children) to the view.</summary>
  75. /// <param name="views">Array of one or more views (can be optional parameter).</param>
  76. /// <remarks>
  77. /// The Views that have been added to this view can be retrieved via the <see cref="Subviews"/> property. See also
  78. /// <seealso cref="Remove(View)"/> <seealso cref="RemoveAll"/>
  79. /// </remarks>
  80. public void Add (params View [] views)
  81. {
  82. if (views is null)
  83. {
  84. return;
  85. }
  86. foreach (View view in views)
  87. {
  88. Add (view);
  89. }
  90. }
  91. /// <summary>Event fired when this view is added to another.</summary>
  92. public event EventHandler<SuperViewChangedEventArgs> Added;
  93. /// <summary>Moves the subview backwards in the hierarchy, only one step</summary>
  94. /// <param name="subview">The subview to send backwards</param>
  95. /// <remarks>If you want to send the view all the way to the back use SendSubviewToBack.</remarks>
  96. public void BringSubviewForward (View subview)
  97. {
  98. PerformActionForSubview (
  99. subview,
  100. x =>
  101. {
  102. int idx = _subviews.IndexOf (x);
  103. if (idx + 1 < _subviews.Count)
  104. {
  105. _subviews.Remove (x);
  106. _subviews.Insert (idx + 1, x);
  107. }
  108. }
  109. );
  110. }
  111. /// <summary>Brings the specified subview to the front so it is drawn on top of any other views.</summary>
  112. /// <param name="subview">The subview to send to the front</param>
  113. /// <remarks><seealso cref="SendSubviewToBack"/>.</remarks>
  114. public void BringSubviewToFront (View subview)
  115. {
  116. PerformActionForSubview (
  117. subview,
  118. x =>
  119. {
  120. _subviews.Remove (x);
  121. _subviews.Add (x);
  122. }
  123. );
  124. }
  125. /// <summary>Get the top superview of a given <see cref="View"/>.</summary>
  126. /// <returns>The superview view.</returns>
  127. public View GetTopSuperView (View view = null, View superview = null)
  128. {
  129. View top = superview ?? Application.Top;
  130. for (View v = view?.SuperView ?? this?.SuperView; v != null; v = v.SuperView)
  131. {
  132. top = v;
  133. if (top == superview)
  134. {
  135. break;
  136. }
  137. }
  138. return top;
  139. }
  140. /// <summary>Method invoked when a subview is being added to this view.</summary>
  141. /// <param name="e">Event where <see cref="ViewEventArgs.View"/> is the subview being added.</param>
  142. public virtual void OnAdded (SuperViewChangedEventArgs e)
  143. {
  144. View view = e.Child;
  145. view.IsAdded = true;
  146. view.OnResizeNeeded ();
  147. view.Added?.Invoke (this, e);
  148. }
  149. /// <summary>Method invoked when a subview is being removed from this view.</summary>
  150. /// <param name="e">Event args describing the subview being removed.</param>
  151. public virtual void OnRemoved (SuperViewChangedEventArgs e)
  152. {
  153. View view = e.Child;
  154. view.IsAdded = false;
  155. view.Removed?.Invoke (this, e);
  156. }
  157. /// <summary>Removes a subview added via <see cref="Add(View)"/> or <see cref="Add(View[])"/> from this View.</summary>
  158. /// <remarks></remarks>
  159. public virtual void Remove (View view)
  160. {
  161. if (view is null || _subviews is null)
  162. {
  163. return;
  164. }
  165. Rect touched = view.Frame;
  166. _subviews.Remove (view);
  167. _tabIndexes.Remove (view);
  168. view._superView = null;
  169. view._tabIndex = -1;
  170. SetNeedsLayout ();
  171. SetNeedsDisplay ();
  172. foreach (View v in _subviews)
  173. {
  174. if (v.Frame.IntersectsWith (touched))
  175. {
  176. view.SetNeedsDisplay ();
  177. }
  178. }
  179. OnRemoved (new SuperViewChangedEventArgs (this, view));
  180. if (Focused == view)
  181. {
  182. Focused = null;
  183. }
  184. }
  185. /// <summary>Removes all subviews (children) added via <see cref="Add(View)"/> or <see cref="Add(View[])"/> from this View.</summary>
  186. public virtual void RemoveAll ()
  187. {
  188. if (_subviews is null)
  189. {
  190. return;
  191. }
  192. while (_subviews.Count > 0)
  193. {
  194. Remove (_subviews [0]);
  195. }
  196. }
  197. /// <summary>Event fired when this view is removed from another.</summary>
  198. public event EventHandler<SuperViewChangedEventArgs> Removed;
  199. /// <summary>Moves the subview backwards in the hierarchy, only one step</summary>
  200. /// <param name="subview">The subview to send backwards</param>
  201. /// <remarks>If you want to send the view all the way to the back use SendSubviewToBack.</remarks>
  202. public void SendSubviewBackwards (View subview)
  203. {
  204. PerformActionForSubview (
  205. subview,
  206. x =>
  207. {
  208. int idx = _subviews.IndexOf (x);
  209. if (idx > 0)
  210. {
  211. _subviews.Remove (x);
  212. _subviews.Insert (idx - 1, x);
  213. }
  214. }
  215. );
  216. }
  217. /// <summary>Sends the specified subview to the front so it is the first view drawn</summary>
  218. /// <param name="subview">The subview to send to the front</param>
  219. /// <remarks><seealso cref="BringSubviewToFront(View)"/>.</remarks>
  220. public void SendSubviewToBack (View subview)
  221. {
  222. PerformActionForSubview (
  223. subview,
  224. x =>
  225. {
  226. _subviews.Remove (x);
  227. _subviews.Insert (0, subview);
  228. }
  229. );
  230. }
  231. private void PerformActionForSubview (View subview, Action<View> action)
  232. {
  233. if (_subviews.Contains (subview))
  234. {
  235. action (subview);
  236. }
  237. SetNeedsDisplay ();
  238. subview.SetNeedsDisplay ();
  239. }
  240. #region Focus
  241. /// <summary>Exposed as `internal` for unit tests. Indicates focus navigation direction.</summary>
  242. internal enum NavigationDirection
  243. {
  244. /// <summary>Navigate forward.</summary>
  245. Forward,
  246. /// <summary>Navigate backwards.</summary>
  247. Backward
  248. }
  249. /// <summary>Event fired when the view gets focus.</summary>
  250. public event EventHandler<FocusEventArgs> Enter;
  251. /// <summary>Event fired when the view looses focus.</summary>
  252. public event EventHandler<FocusEventArgs> Leave;
  253. private NavigationDirection _focusDirection;
  254. internal NavigationDirection FocusDirection
  255. {
  256. get => SuperView?.FocusDirection ?? _focusDirection;
  257. set
  258. {
  259. if (SuperView != null)
  260. {
  261. SuperView.FocusDirection = value;
  262. }
  263. else
  264. {
  265. _focusDirection = value;
  266. }
  267. }
  268. }
  269. // BUGBUG: v2 - Seems weird that this is in View and not Responder.
  270. private bool _hasFocus;
  271. /// <inheritdoc/>
  272. public override bool HasFocus => _hasFocus;
  273. private void SetHasFocus (bool value, View view, bool force = false)
  274. {
  275. if (_hasFocus != value || force)
  276. {
  277. _hasFocus = value;
  278. if (value)
  279. {
  280. OnEnter (view);
  281. }
  282. else
  283. {
  284. OnLeave (view);
  285. }
  286. SetNeedsDisplay ();
  287. }
  288. // Remove focus down the chain of subviews if focus is removed
  289. if (!value && Focused != null)
  290. {
  291. View f = Focused;
  292. f.OnLeave (view);
  293. f.SetHasFocus (false, view);
  294. Focused = null;
  295. }
  296. }
  297. /// <summary>Event fired when the <see cref="CanFocus"/> value is being changed.</summary>
  298. public event EventHandler CanFocusChanged;
  299. /// <inheritdoc/>
  300. public override void OnCanFocusChanged () { CanFocusChanged?.Invoke (this, EventArgs.Empty); }
  301. private bool _oldCanFocus;
  302. /// <inheritdoc/>
  303. public override bool CanFocus
  304. {
  305. get => base.CanFocus;
  306. set
  307. {
  308. if (!_addingView && IsInitialized && SuperView?.CanFocus == false && value)
  309. {
  310. throw new InvalidOperationException ("Cannot set CanFocus to true if the SuperView CanFocus is false!");
  311. }
  312. if (base.CanFocus != value)
  313. {
  314. base.CanFocus = value;
  315. switch (value)
  316. {
  317. case false when _tabIndex > -1:
  318. TabIndex = -1;
  319. break;
  320. case true when SuperView?.CanFocus == false && _addingView:
  321. SuperView.CanFocus = true;
  322. break;
  323. }
  324. if (value && _tabIndex == -1)
  325. {
  326. TabIndex = SuperView != null ? SuperView._tabIndexes.IndexOf (this) : -1;
  327. }
  328. TabStop = value;
  329. if (!value && SuperView?.Focused == this)
  330. {
  331. SuperView.Focused = null;
  332. }
  333. if (!value && HasFocus)
  334. {
  335. SetHasFocus (false, this);
  336. SuperView?.EnsureFocus ();
  337. if (SuperView != null && SuperView.Focused is null)
  338. {
  339. SuperView.FocusNext ();
  340. if (SuperView.Focused is null && Application.Current != null)
  341. {
  342. Application.Current.FocusNext ();
  343. }
  344. Application.BringOverlappedTopToFront ();
  345. }
  346. }
  347. if (_subviews != null && IsInitialized)
  348. {
  349. foreach (View view in _subviews)
  350. {
  351. if (view.CanFocus != value)
  352. {
  353. if (!value)
  354. {
  355. view._oldCanFocus = view.CanFocus;
  356. view._oldTabIndex = view._tabIndex;
  357. view.CanFocus = false;
  358. view._tabIndex = -1;
  359. }
  360. else
  361. {
  362. if (_addingView)
  363. {
  364. view._addingView = true;
  365. }
  366. view.CanFocus = view._oldCanFocus;
  367. view._tabIndex = view._oldTabIndex;
  368. view._addingView = false;
  369. }
  370. }
  371. }
  372. }
  373. OnCanFocusChanged ();
  374. SetNeedsDisplay ();
  375. }
  376. }
  377. }
  378. /// <inheritdoc/>
  379. public override bool OnEnter (View view)
  380. {
  381. var args = new FocusEventArgs (view);
  382. Enter?.Invoke (this, args);
  383. if (args.Handled)
  384. {
  385. return true;
  386. }
  387. if (base.OnEnter (view))
  388. {
  389. return true;
  390. }
  391. return false;
  392. }
  393. /// <inheritdoc/>
  394. public override bool OnLeave (View view)
  395. {
  396. var args = new FocusEventArgs (view);
  397. Leave?.Invoke (this, args);
  398. if (args.Handled)
  399. {
  400. return true;
  401. }
  402. if (base.OnLeave (view))
  403. {
  404. return true;
  405. }
  406. Driver?.SetCursorVisibility (CursorVisibility.Invisible);
  407. return false;
  408. }
  409. /// <summary>Returns the currently focused view inside this view, or null if nothing is focused.</summary>
  410. /// <value>The focused.</value>
  411. public View Focused { get; private set; }
  412. /// <summary>Returns the most focused view in the chain of subviews (the leaf view that has the focus).</summary>
  413. /// <value>The most focused View.</value>
  414. public View MostFocused
  415. {
  416. get
  417. {
  418. if (Focused is null)
  419. {
  420. return null;
  421. }
  422. View most = Focused.MostFocused;
  423. if (most != null)
  424. {
  425. return most;
  426. }
  427. return Focused;
  428. }
  429. }
  430. /// <summary>Causes the specified subview to have focus.</summary>
  431. /// <param name="view">View.</param>
  432. private void SetFocus (View view)
  433. {
  434. if (view is null)
  435. {
  436. return;
  437. }
  438. //Console.WriteLine ($"Request to focus {view}");
  439. if (!view.CanFocus || !view.Visible || !view.Enabled)
  440. {
  441. return;
  442. }
  443. if (Focused?._hasFocus == true && Focused == view)
  444. {
  445. return;
  446. }
  447. if ((Focused?._hasFocus == true && Focused?.SuperView == view) || view == this)
  448. {
  449. if (!view._hasFocus)
  450. {
  451. view._hasFocus = true;
  452. }
  453. return;
  454. }
  455. // Make sure that this view is a subview
  456. View c;
  457. for (c = view._superView; c != null; c = c._superView)
  458. {
  459. if (c == this)
  460. {
  461. break;
  462. }
  463. }
  464. if (c is null)
  465. {
  466. throw new ArgumentException ("the specified view is not part of the hierarchy of this view");
  467. }
  468. if (Focused != null)
  469. {
  470. Focused.SetHasFocus (false, view);
  471. }
  472. View f = Focused;
  473. Focused = view;
  474. Focused.SetHasFocus (true, f);
  475. Focused.EnsureFocus ();
  476. // Send focus upwards
  477. if (SuperView != null)
  478. {
  479. SuperView.SetFocus (this);
  480. }
  481. else
  482. {
  483. SetFocus (this);
  484. }
  485. }
  486. /// <summary>Causes the specified view and the entire parent hierarchy to have the focused order updated.</summary>
  487. public void SetFocus ()
  488. {
  489. if (!CanBeVisible (this) || !Enabled)
  490. {
  491. if (HasFocus)
  492. {
  493. SetHasFocus (false, this);
  494. }
  495. return;
  496. }
  497. if (SuperView != null)
  498. {
  499. SuperView.SetFocus (this);
  500. }
  501. else
  502. {
  503. SetFocus (this);
  504. }
  505. }
  506. /// <summary>
  507. /// Finds the first view in the hierarchy that wants to get the focus if nothing is currently focused, otherwise,
  508. /// does nothing.
  509. /// </summary>
  510. public void EnsureFocus ()
  511. {
  512. if (Focused is null && _subviews?.Count > 0)
  513. {
  514. if (FocusDirection == NavigationDirection.Forward)
  515. {
  516. FocusFirst ();
  517. }
  518. else
  519. {
  520. FocusLast ();
  521. }
  522. }
  523. }
  524. /// <summary>Focuses the first focusable subview if one exists.</summary>
  525. public void FocusFirst ()
  526. {
  527. if (!CanBeVisible (this))
  528. {
  529. return;
  530. }
  531. if (_tabIndexes is null)
  532. {
  533. SuperView?.SetFocus (this);
  534. return;
  535. }
  536. foreach (View view in _tabIndexes)
  537. {
  538. if (view.CanFocus && view._tabStop && view.Visible && view.Enabled)
  539. {
  540. SetFocus (view);
  541. return;
  542. }
  543. }
  544. }
  545. /// <summary>Focuses the last focusable subview if one exists.</summary>
  546. public void FocusLast ()
  547. {
  548. if (!CanBeVisible (this))
  549. {
  550. return;
  551. }
  552. if (_tabIndexes is null)
  553. {
  554. SuperView?.SetFocus (this);
  555. return;
  556. }
  557. for (int i = _tabIndexes.Count; i > 0;)
  558. {
  559. i--;
  560. View v = _tabIndexes [i];
  561. if (v.CanFocus && v._tabStop && v.Visible && v.Enabled)
  562. {
  563. SetFocus (v);
  564. return;
  565. }
  566. }
  567. }
  568. /// <summary>Focuses the previous view.</summary>
  569. /// <returns><see langword="true"/> if previous was focused, <see langword="false"/> otherwise.</returns>
  570. public bool FocusPrev ()
  571. {
  572. if (!CanBeVisible (this))
  573. {
  574. return false;
  575. }
  576. FocusDirection = NavigationDirection.Backward;
  577. if (_tabIndexes is null || _tabIndexes.Count == 0)
  578. {
  579. return false;
  580. }
  581. if (Focused is null)
  582. {
  583. FocusLast ();
  584. return Focused != null;
  585. }
  586. int focusedIdx = -1;
  587. for (int i = _tabIndexes.Count; i > 0;)
  588. {
  589. i--;
  590. View w = _tabIndexes [i];
  591. if (w.HasFocus)
  592. {
  593. if (w.FocusPrev ())
  594. {
  595. return true;
  596. }
  597. focusedIdx = i;
  598. continue;
  599. }
  600. if (w.CanFocus && focusedIdx != -1 && w._tabStop && w.Visible && w.Enabled)
  601. {
  602. Focused.SetHasFocus (false, w);
  603. if (w.CanFocus && w._tabStop && w.Visible && w.Enabled)
  604. {
  605. w.FocusLast ();
  606. }
  607. SetFocus (w);
  608. return true;
  609. }
  610. }
  611. if (Focused != null)
  612. {
  613. Focused.SetHasFocus (false, this);
  614. Focused = null;
  615. }
  616. return false;
  617. }
  618. /// <summary>Focuses the next view.</summary>
  619. /// <returns><see langword="true"/> if next was focused, <see langword="false"/> otherwise.</returns>
  620. public bool FocusNext ()
  621. {
  622. if (!CanBeVisible (this))
  623. {
  624. return false;
  625. }
  626. FocusDirection = NavigationDirection.Forward;
  627. if (_tabIndexes is null || _tabIndexes.Count == 0)
  628. {
  629. return false;
  630. }
  631. if (Focused is null)
  632. {
  633. FocusFirst ();
  634. return Focused != null;
  635. }
  636. int focusedIdx = -1;
  637. for (var i = 0; i < _tabIndexes.Count; i++)
  638. {
  639. View w = _tabIndexes [i];
  640. if (w.HasFocus)
  641. {
  642. if (w.FocusNext ())
  643. {
  644. return true;
  645. }
  646. focusedIdx = i;
  647. continue;
  648. }
  649. if (w.CanFocus && focusedIdx != -1 && w._tabStop && w.Visible && w.Enabled)
  650. {
  651. Focused.SetHasFocus (false, w);
  652. if (w.CanFocus && w._tabStop && w.Visible && w.Enabled)
  653. {
  654. w.FocusFirst ();
  655. }
  656. SetFocus (w);
  657. return true;
  658. }
  659. }
  660. if (Focused != null)
  661. {
  662. Focused.SetHasFocus (false, this);
  663. Focused = null;
  664. }
  665. return false;
  666. }
  667. private View GetMostFocused (View view)
  668. {
  669. if (view is null)
  670. {
  671. return null;
  672. }
  673. return view.Focused != null ? GetMostFocused (view.Focused) : view;
  674. }
  675. /// <summary>Positions the cursor in the right position based on the currently focused view in the chain.</summary>
  676. /// Views that are focusable should override
  677. /// <see cref="PositionCursor"/>
  678. /// to ensure
  679. /// the cursor is placed in a location that makes sense. Unix terminals do not have
  680. /// a way of hiding the cursor, so it can be distracting to have the cursor left at
  681. /// the last focused view. Views should make sure that they place the cursor
  682. /// in a visually sensible place.
  683. public virtual void PositionCursor ()
  684. {
  685. if (!CanBeVisible (this) || !Enabled)
  686. {
  687. return;
  688. }
  689. // BUGBUG: v2 - This needs to support children of Frames too
  690. if (Focused is null && SuperView != null)
  691. {
  692. SuperView.EnsureFocus ();
  693. }
  694. else if (Focused?.Visible == true
  695. && Focused?.Enabled == true
  696. && Focused?.Frame.Width > 0
  697. && Focused.Frame.Height > 0)
  698. {
  699. Focused.PositionCursor ();
  700. }
  701. else if (Focused?.Visible == true && Focused?.Enabled == false)
  702. {
  703. Focused = null;
  704. }
  705. else if (CanFocus && HasFocus && Visible && Frame.Width > 0 && Frame.Height > 0)
  706. {
  707. Move (TextFormatter.HotKeyPos == -1 ? 0 : TextFormatter.CursorPosition, 0);
  708. }
  709. else
  710. {
  711. Move (_frame.X, _frame.Y);
  712. }
  713. }
  714. #endregion Focus
  715. }