ViewSubViews.cs 18 KB

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