ViewSubViews.cs 17 KB

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