ViewSubViews.cs 18 KB

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